Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add a snippet to remove LangSys from DFLT script
#!/usr/bin/env python import argparse import logging import os import sys from fontTools.ttLib import TTFont def ProcessTable(table): found = set() for rec in table.ScriptList.ScriptRecord: if rec.ScriptTag == "DFLT" and rec.Script.LangSysCount != 0: tags = [r.LangSysTag for r in rec.Sc...
Add magice circle demo app
#!/usr/bin/python2 import sys sys.path = ['', 'pyglet-1.1.4'] + sys.path import math import pyglet from pyglet.graphics import vertex_list from pyglet import gl from pyglet.window import key window = pyglet.window.Window(width=800, height=600, resizable=True) fps_display = pyglet.clock.ClockDisplay() num_points =...
Improve robustness: surround the 'id' fetch from result array with a try clause.
""" Username to UUID Converts a Minecraft username to it's UUID equivalent. Uses the official Mojang API to fetch player data. """ import http.client import json class UsernameToUUID: def __init__(self, username): self.username = username def get_uuid(self, timestamp=None): """ Ge...
""" Username to UUID Converts a Minecraft username to it's UUID equivalent. Uses the official Mojang API to fetch player data. """ import http.client import json class UsernameToUUID: def __init__(self, username): self.username = username def get_uuid(self, timestamp=None): """ Ge...
Reset script first pulls pin high
#!/usr/local/bin/python import mraa import time resetPin = mraa.Gpio(8) resetPin.dir(mraa.DIR_OUT) resetPin.write(0) time.sleep(0.2) resetPin.write(1)
#!/usr/local/bin/python import mraa import time resetPin = mraa.Gpio(8) resetPin.dir(mraa.DIR_OUT) resetPin.write(1) time.sleep(0.2) resetPin.write(0) time.sleep(0.2) resetPin.write(1)
Speed up Python tests by caching pip downloads
from __future__ import with_statement from fabric.api import * from fabtools import require import fabtools @task def python(): """ Check Python package installation """ require.python.virtualenv('/tmp/venv') assert fabtools.files.is_dir('/tmp/venv') assert fabtools.files.is_file('/tmp/venv/b...
from __future__ import with_statement from fabric.api import task @task def python_virtualenv(): """ Test Python virtualenv creation """ from fabtools import require import fabtools require.python.virtualenv('/tmp/venv') assert fabtools.files.is_dir('/tmp/venv') assert fabtools.file...
Add name fields to generated templates
import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Rea...
"""Generator functions for thesaurus files""" import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): """Generate a template for the given language and structure""" meta_info = MetaInfo() if structure_id not in meta_info.data_structures: ...
Fix test for upgrade-node command parser
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Use protocol-specific URL for media.
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DE...
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'docs', 'USER': 'postgres', # Not used with sqlite3. 'PASSWORD': '', 'HOST': '10.177.73.97', 'PORT': '', } } DEBUG = False TEMPLATE_DE...
Test add site_scons as SCons module
import platform from SCons.Script import AddOption, GetOption SYSTEMS = dict(Linux = "linux", Darwin = "osx", Windows = "windows") system = str(platform.system()) if not system in SYSTEMS: system = "unknown" AddOption('--system', dest = 'system', type = 'string'...
import platform from SCons.Script import AddOption, GetOption SYSTEMS = dict(Linux = "linux", Darwin = "osx", Windows = "windows") system = str(platform.system()) if not system in SYSTEMS: system = "unknown" AddOption('--system', dest = 'system', type = 'choice'...
Use `<input type="tel">` for phone number field
""" byceps.blueprints.user.current.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import DateField, StringField from wtforms.validators import InputRequired, Length, Optional from ....util.l10n import LocalizedFo...
""" byceps.blueprints.user.current.forms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from wtforms import DateField, StringField from wtforms.fields.html5 import TelField from wtforms.validators import InputRequired, Length, Optio...
Add tests for measuring the speed of probabilistic interleaving
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(100, 200)) for i in range(1000): method = il....
import interleaving as il import numpy as np import pytest np.random.seed(0) from .test_methods import TestMethods class TestProbabilisticInterleaveSpeed(TestMethods): def test_interleave(self): r1 = list(range(100)) r2 = list(range(50, 150)) r3 = list(range(100, 200)) r4 = list(ra...
Update the camb3lyp example to libxc 5 series
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' The default XC functional library (libxc) supports the energy and nuclear gradients for range separated functionals. Nuclear Hessian and TDDFT gradients need xcfun library. See also example 32-xcfun_as_default.py for how to set xcfun library a...
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # '''Density functional calculations can be run with either the default backend library, libxc, or an alternative library, xcfun. See also example 32-xcfun_as_default.py for how to set xcfun as the default XC functional library. ''' from pyscf impor...
Remove the unused convert_png_to_jpg method.
from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image def convert_png_to_jpg(img): """ Converts a png to a jpg. :param img: Absolute path to the image. :returns: the filename """ im = Image.open(img) bg = Image.new(...
from django.core.files.storage import get_storage_class from storages.backends.s3boto import S3BotoStorage from PIL import Image class CachedS3BotoStorage(S3BotoStorage): """ S3 storage backend that saves the files locally, too. """ def __init__(self, *args, **kwargs): super(CachedS3BotoStorag...
Fix other failure - assuming that the change in sort key value for winter sports was intentional.
assert_has_feature( 15, 5467, 12531, 'landuse', { 'kind': 'winter_sports', 'sort_key': 33 })
assert_has_feature( 15, 5467, 12531, 'landuse', { 'kind': 'winter_sports', 'sort_key': 36 })
Make it possible to specify which app to represent in sentry
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:pass@sentry.io/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), }
import os import raven from decouple import config RAVEN_CONFIG = { 'dsn': config('OW4_RAVEN_DSN', default='https://user:pass@sentry.io/project'), 'environment': config('OW4_ENVIRONMENT', default='DEVELOP'), # Use git to determine release 'release': raven.fetch_git_sha(os.path.dirname(os.pardir)), ...
Mark instance list as staff-only, and give it a view name
from __future__ import unicode_literals from django.conf.urls import patterns, url from . import views from django.contrib.admin.views.decorators import staff_member_required urlpatterns = patterns( "", url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"), url(r"^issued/$", "b...
from __future__ import unicode_literals from django.conf.urls import patterns, url from . import views from django.contrib.admin.views.decorators import staff_member_required urlpatterns = patterns( "", url(r"^hello/$", "badgekit_webhooks.views.hello", name="badgekit_webhooks_hello"), url(r"^issued/$", "b...
Handle the case where the bucket already exists
from boto.s3.connection import S3Connection from boto.exception import S3ResponseError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] t...
from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket...
Add second test, trying to trigger travis
# -*- coding:utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create()
# -*- coding:utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from django.test import TestCase from django_mysql_tests.models import MyModel class SimpleTests(TestCase): def test_simple(self): MyModel.objects.create() def test_t...
Add Slack action to init
from .actions import ( BasicValidationAction, NamespacedValidationAction, NoOpAction, SummarizeAndStoreAction, ) from .validation_operators import ( DefaultActionAwareValidationOperator )
from .actions import ( BasicValidationAction, NamespacedValidationAction, NoOpAction, SummarizeAndStoreAction, SlackNotificationAction ) from .validation_operators import ( DefaultActionAwareValidationOperator )
Add docstring to matplotlib imshow plugin
import matplotlib.pyplot as plt def imshow(*args, **kwargs): if plt.gca().has_data(): plt.figure() kwargs.setdefault('interpolation', 'nearest') kwargs.setdefault('cmap', 'gray') plt.imshow(*args, **kwargs) imread = plt.imread show = plt.show def _app_show(): show()
import matplotlib.pyplot as plt def imshow(im, *args, **kwargs): """Show the input image and return the current axes. Parameters ---------- im : array, shape (M, N[, 3]) The image to display. *args, **kwargs : positional and keyword arguments These are passed directly to `matplot...
Add switch and sample decorators.
import waffle from rest_framework.exceptions import NotFound def require_flag(flag_name): """ Decorator to check whether flag is active. If inactive, raise NotFound. """ def wrapper(fn): def check_flag(*args,**kwargs): if waffle.flag_is_active(args[0].request, flag_name): ...
import waffle from rest_framework.exceptions import NotFound def require_flag(flag_name): """ Decorator to check whether waffle flag is active. If inactive, raise NotFound. """ def wrapper(fn): def check_flag(*args,**kwargs): if waffle.flag_is_active(args[0].request, flag_name)...
Allow bootstrapping config with values
import os import click from parsec.cli import pass_context from parsec import options from parsec import config from parsec.io import warn, info CONFIG_TEMPLATE = """## Parsec Global Configuration File. # Each stanza should contian a single galaxy server to control. local: key: "<TODO>" email: "<TODO>" ...
import os import click from parsec.cli import pass_context from parsec import options from parsec import config from parsec.io import warn, info CONFIG_TEMPLATE = """## Parsec Global Configuration File. # Each stanza should contian a single galaxy server to control. local: key: "%(key)s" email: "<TODO>" ...
Update description and add 'tox' as a testing dependency.
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ # TODO: put package requirements here ] test_requi...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ # None ] test_requirements = [ 'tox', ] setup...
Add another PyPI package classifier of Python 3.5 programming language
#!/usr/bin/env python import setuptools import sys if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5) or sys.version_info.major > 3): exit("Sorry, Python's version must be later than 3.5.") import shakyo setuptools.setup( name=shakyo.__name__, version=shakyo.__version__, descri...
#!/usr/bin/env python import setuptools import sys if not ((sys.version_info.major >= 3 and sys.version_info.minor >= 5) or sys.version_info.major > 3): exit("Sorry, Python's version must be later than 3.5.") import shakyo setuptools.setup( name=shakyo.__name__, version=shakyo.__version__, descri...
Use absolute imports, not relative ones.
""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' fro...
""" raven ~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception, e: VERSION = 'unknown' fro...
Read samples faster but log only once a second
#!/usr/bin/env python3 from sense_hat import SenseHat from pymongo import MongoClient import time DELAY = 1 # in seconds sense = SenseHat() client = MongoClient("mongodb://10.0.1.25:27017") db = client.g2x while True: orientation = sense.get_orientation_degrees() print(orientation) acceleration = sen...
#!/usr/bin/env python3 from sense_hat import SenseHat from pymongo import MongoClient from datetime import datetime sense = SenseHat() client = MongoClient("mongodb://10.0.1.25:27017") db = client.g2x last_time = datetime.utcnow() sample_count = 0 while True: current_time = datetime.utcnow() elapsed_time =...
Send and Connect frame tests
import unittest from Decode import Decoder import Frames class TestDecoder(unittest.TestCase): """ """ def setUp(self): self.decoder = Decoder() def test_decoder_get_frame_class(self): command = 'SEND' self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND) d...
import unittest from Decode import Decoder import Frames class TestDecoder(unittest.TestCase): """ """ def setUp(self): self.decoder = Decoder() def test_decoder_get_frame_class(self): command = 'SEND' self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND) d...
Clean up socket file on exiting
#!/usr/bin/python3 import asyncio, signal, os from blink import blink import ipc.coordinator loop = asyncio.get_event_loop() def my_interrupt_handler(): print('Stopping') for task in asyncio.Task.all_tasks(): task.cancel() loop.stop() loop.add_signal_handler(signal.SIGINT, my_interrupt_handle...
#!/usr/bin/python3 import asyncio, signal, os from blink import blink import ipc.coordinator loop = asyncio.get_event_loop() def my_interrupt_handler(): print('Stopping') for task in asyncio.Task.all_tasks(): task.cancel() loop.stop() loop.add_signal_handler(signal.SIGINT, my_interrupt_handle...
Fix the add_media() hack for Django 2.0
""" Internal utils """ import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. Only required for Django < 2.0 """ if django.VERSION >= (2, 0): dest += media else: dest.add_css(media._css) dest.add...
""" Internal utils """ import django def add_media(dest, media): """ Optimized version of django.forms.Media.__add__() that doesn't create new objects. Only required for Django < 2.0 """ if django.VERSION >= (2, 0): combined = dest + media dest._css = combined._css dest._j...
Use 20 as default page size
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', # Any other renders, 'rest_framework.renderers.JSONRenderer', # 'rest_framework.renderers.BrowsableAPIRenderer', ), # 'DEFAULT_PARSER_CLASSES': ( # 'djangorestf...
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( # 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', # Any other renders, 'rest_framework.renderers.JSONRenderer', # 'rest_framework.renderers.BrowsableAPIRenderer', ), # 'DEFAULT_PARSER_CLASSES': ( # 'djangorestf...
Repair validate single shape validator
import pyblish.api class ValidateMindbenderSingleShape(pyblish.api.InstancePlugin): """One mesh per transform""" label = "Validate Single Shape" order = pyblish.api.ValidatorOrder hosts = ["maya"] active = False optional = True families = [ "mindbender.model", "mindbender....
import pyblish.api class ValidateMindbenderSingleShape(pyblish.api.InstancePlugin): """Transforms with a mesh must ever only contain a single mesh This ensures models only contain a single shape node. """ label = "Validate Single Shape" order = pyblish.api.ValidatorOrder hosts = ["maya"] ...
Add commentary explaining and/or lists
from pyparsing import * from ...constants.math.deff import NUM, FULLNUM from ...constants.zones.deff import TOP, BOTTOM from ...constants.verbs.deff import * from ...mana.deff import color from ...types.deff import nontype, supertype from ...functions.deff import delimitedListAnd, delimitedListOr from decl import * ...
from pyparsing import * from ...constants.math.deff import NUM, FULLNUM from ...constants.zones.deff import TOP, BOTTOM from ...constants.verbs.deff import * from ...mana.deff import color from ...types.deff import nontype, supertype from ...functions.deff import delimitedListAnd, delimitedListOr from decl import * ...
Set transport name as public
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self._name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format....
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self.name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.d...
Revert accidental gums test change from previous commit.
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums...
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums...
Use r-strings for URL regexes
from django.conf.urls import url from . import views urlpatterns = [ url("^$", views.request_view, name="request_site"), url("^approve$", views.approve_view, name="approve_site"), url("^admin$", views.approve_admin_view, name="admin_site") ]
from django.conf.urls import url from . import views urlpatterns = [ url(r"^$", views.request_view, name="request_site"), url(r"^approve$", views.approve_view, name="approve_site"), url(r"^admin$", views.approve_admin_view, name="admin_site") ]
Document expected behaviour instead of leaving XXX comment
""" Fixtures in this file are available to all files automatically, no importing required. Only put general purpose fixtures here! """ import pytest import os from shutil import rmtree TEST_CONFIG = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'config.cfg') @pytest.fixture(scope='se...
""" Fixtures in this file are available to all files automatically, no importing required. Only put general purpose fixtures here! """ import pytest import os from shutil import rmtree TEST_CONFIG = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'config.cfg') @pytest.fixture(scope='se...
Remove dependency on unicodecsv module
# I started here: https://www.django-rest-framework.org/api-guide/renderers/#example from rest_framework import renderers import unicodecsv as csv import io import logging logger = logging.getLogger(__name__) class SimpleCSVRenderer(renderers.BaseRenderer): """Renders simple 1-level-deep data as csv""" med...
# I started here: https://www.django-rest-framework.org/api-guide/renderers/#example import csv import io import logging from rest_framework import renderers logger = logging.getLogger(__name__) class SimpleCSVRenderer(renderers.BaseRenderer): """Renders simple 1-level-deep data as csv""" media_type = "te...
Use faster password hashing in tests.
""" Settings for tests. """ from moztrap.settings.default import * DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage" ALLOW_ANONYMOUS_ACCESS = False SITE_URL = "http://localhost:80" USE_BROWSERID = True
""" Settings for tests. """ from moztrap.settings.default import * DEFAULT_FILE_STORAGE = "tests.storage.MemoryStorage" ALLOW_ANONYMOUS_ACCESS = False SITE_URL = "http://localhost:80" USE_BROWSERID = True PASSWORD_HASHERS = ['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']
Allow email in profile urls
from django.conf.urls import * from profiles import views urlpatterns = patterns('', url(r'^(?P<username>[\w.-]+)/$', views.profile_detail, {'template_name': 'profiles/public/profile_detail.html'}, name='profiles_...
from django.conf.urls import * from profiles import views urlpatterns = patterns('', url(r'^(?P<username>[\w@.-]+)/$', views.profile_detail, {'template_name': 'profiles/public/profile_detail.html'}, name='profiles...
Update python script util to detect if paths are already fully qualified
import os def hdfs_make_qualified(path): return path if 'CF_HADOOP_DEFAULT_FS' not in os.environ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
import os import re def hdfs_make_qualified(path): return path if (re.match(r'[.]*://[.]*', path) or 'CF_HADOOP_DEFAULT_FS' not in os.environ) \ else os.environ['CF_HADOOP_DEFAULT_FS'] + path
Use standart i18n key in meal model
from django.db import models from django.utils.translation import ugettext_lazy as _ class Meal(models.Model): class Meta: verbose_name_plural = _('Meals') #Meal information nom = models.CharField(max_length=50, verbose_name=_('Name')) description = models.TextFields(verbose_name=_('Description')) ingredients ...
from django.db import models from django.utils.translation import ugettext_lazy as _ class Meal(models.Model): class Meta: verbose_name_plural = _('meals') #Meal information nom = models.CharField(max_length=50, verbose_name=_('name')) description = models.TextFields(verbose_name=_('description')) ingredients ...
Replace SyftClient calls -> Direct Node calls - This avoids to build client ast for every single request making the backend faster
# stdlib from typing import Any from typing import Optional # third party from nacl.signing import SigningKey # syft absolute from syft import flags from syft.core.common.message import SyftMessage from syft.core.io.address import Address from syft.core.node.common.action.exception_action import ExceptionMessage from...
# stdlib from typing import Any from typing import Optional # third party from nacl.signing import SigningKey # syft absolute from syft.core.common.message import SyftMessage from syft.core.io.address import Address from syft.core.node.common.action.exception_action import ExceptionMessage from syft.lib.python.dict i...
Order people by associated production.
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('first_name', 'last_name', 'production', 'role') list_filter = ('role',...
from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('first_name', 'last_name', 'production', 'role') list_filter = ('role',...
Handle case of memory limit not set.
import os import json import psutil from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler def get_metrics(): cur_process = psutil.Process() all_processes = [cur_process] + cur_process.children(recursive=True) rss = sum([p.memory_info().rss for p in all_processes]) r...
import os import json import psutil from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler def get_metrics(): cur_process = psutil.Process() all_processes = [cur_process] + cur_process.children(recursive=True) rss = sum([p.memory_info().rss for p in all_processes]) m...
Increment version to 1.14.0 for release.
__version_info__ = ('1', '14', '0rc1') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_...
__version_info__ = ('1', '14', '0') __version__ = '.'.join(__version_info__) from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper, BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy, resolve_path, apply_patch, wrap_object, wrap_object_attribute, function_wra...
Test Class now returns to base state between different groups of tests
import pytest from cps2_zmq.gather import MameSink @pytest.mark.parametrize("message, expected",[ ({'wid': 420, 'message': 'closing'}, 'worksink closing'), ({'wid': 420, 'message': 'threaddead'}, '420 is dead'), ({'wid': 420, 'message': 'some result'}, 'another message'), ]) def test_process_message(messag...
import pytest from cps2_zmq.gather import MameSink @pytest.fixture(scope="module") def sink(): sink = MameSink.MameSink("inproc://frommockworkers") yield sink sink.cleanup() class TestSink(object): @pytest.fixture(autouse=True) def refresh(self, sink): pass yield sink._msgs...
Clean up date guessing benchmarking code
#!/usr/bin/env python import os import pytest import sys from mediawords.tm.guess_date import guess_date, McGuessDateException def main(): if (len(sys.argv) < 2): sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>') exit() directory = os.fsencode(sys.argv[1]).decode("utf-...
#!/usr/bin/env python3 import os import sys from mediawords.tm.guess_date import guess_date def benchmark_date_guessing(): """Benchmark Python date guessing code.""" if len(sys.argv) < 2: sys.exit("Usage: %s <directory of html files>" % sys.argv[0]) directory = sys.argv[1] for file in os.l...
Fix running on unconfigured virtualenv.
import os __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: from fields import TimedeltaField from helpers import ( divide, multiply, modulo, parse, nice_repr, percentage, decimal_percentage, total_seconds ) except ImportError: ...
import os __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() try: import django from fields import TimedeltaField from helpers import ( divide, multiply, modulo, parse, nice_repr, percentage, decimal_percentage, total_seconds ) excep...
Load docopt lazily (so that setup.py works)
"""Dispatch from command-line arguments to functions.""" import re from collections import OrderedDict from docopt import docopt __all__ = ('dispatch', 'DispatchError') __author__ = 'Vladimir Keleshev <vladimir@keleshev.com>' __version__ = '0.0.0' __license__ = 'MIT' __keywords__ = 'docopt dispatch function adapter ...
"""Dispatch from command-line arguments to functions.""" import re from collections import OrderedDict __all__ = ('dispatch', 'DispatchError') __author__ = 'Vladimir Keleshev <vladimir@keleshev.com>' __version__ = '0.0.0' __license__ = 'MIT' __keywords__ = 'docopt dispatch function adapter kwargs' __url__ = 'https://...
Update django.VERSION in trunk per previous discussion
VERSION = (1, 0, 'post-release-SVN') def get_version(): "Returns the version as a human-format string." v = '.'.join([str(i) for i in VERSION[:-1]]) if VERSION[-1]: from django.utils.version import get_svn_revision v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision()) return v
VERSION = (1, 1, 0, 'alpha', 0) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) if VERSION[3:] == ('alpha', 0): version = '%s pre-alpha' % version else: version = '%s %s' % (version, VERSION[3]) if ...
Add repository test for adding a dataset
import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface)
import pytest from d1lod.sesame import Store, Repository, Interface from d1lod import dataone def test_interface_can_be_created(interface): assert isinstance(interface, Interface) def test_can_add_a_dataset(): """Test whether the right triples are added when we add a known dataset. We pass the store to...
Make output_mimetype accessible from the class.
"""Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------...
"""Python script Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------...
Use a set for comparison
#!/usr/bin/env python # -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/sup...
#!/usr/bin/env python # -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/sup...
Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing.
"""Django DDP utils for DDP messaging.""" from dddp import THREAD_LOCAL as this def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] ...
"""Django DDP utils for DDP messaging.""" from copy import deepcopy from dddp import THREAD_LOCAL as this from django.db.models.expressions import ExpressionNode def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" # check for F expressions exps = [ name for n...
Replace legacy ipython import with jupyter_client
# Configuration file for Jupyter Hub c = get_config() # spawn with Docker c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' # The docker instances need access to the Hub, so the default loopback port doesn't work: from IPython.utils.localinterfaces import public_ips c.JupyterHub.hub_ip = public_ips()[0] # ...
# Configuration file for Jupyter Hub c = get_config() # spawn with Docker c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' # The docker instances need access to the Hub, so the default loopback port doesn't work: from jupyter_client.localinterfaces import public_ips c.JupyterHub.hub_ip = public_ips()[0] #...
Bump pyleus version to 0.1.4
import os import sys __version__ = '0.1.3' BASE_JAR = "pyleus-base.jar" BASE_JAR_INSTALL_DIR = "share/pyleus" BASE_JAR_PATH = os.path.join(sys.prefix, BASE_JAR_INSTALL_DIR, BASE_JAR)
import os import sys __version__ = '0.1.4' BASE_JAR = "pyleus-base.jar" BASE_JAR_INSTALL_DIR = "share/pyleus" BASE_JAR_PATH = os.path.join(sys.prefix, BASE_JAR_INSTALL_DIR, BASE_JAR)
Remove what's already done in KolibriTestBase
""" Tests for `kolibri` module. """ from __future__ import absolute_import, print_function, unicode_literals import logging import os import shutil import tempfile from kolibri.utils.cli import main from .base import KolibriTestBase logger = logging.getLogger(__name__) class TestKolibriCLI(KolibriTestBase): ...
""" Tests for `kolibri` module. """ from __future__ import absolute_import, print_function, unicode_literals import logging from kolibri.utils.cli import main from .base import KolibriTestBase logger = logging.getLogger(__name__) class TestKolibriCLI(KolibriTestBase): def test_cli(self): logger.debug...
Check for strip attr for none values
from django import forms class BugReportForm(forms.Form): bug = forms.CharField(label="Bug (required)", required=True) description = forms.CharField( label="Description (required)", widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=True) reproduce = forms.CharField( l...
from django import forms class BugReportForm(forms.Form): bug = forms.CharField(label="Bug (required)", required=True) description = forms.CharField( label="Description (required)", widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=True) reproduce = forms.CharField( l...
Add to doc string: time complexity
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm.""" for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[pos...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ for index in range(1, len(a_list)): current_value = a_list[index] position = index ...
Use sys.executable when executing nbgrader
import os import sys from .. import run_nbgrader, run_command from .base import BaseTestApp class TestNbGrader(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["--help-all"]) def test_no_subapp(self): """Is the help displayed when no subapp...
import os import sys from .. import run_nbgrader, run_command from .base import BaseTestApp class TestNbGrader(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["--help-all"]) def test_no_subapp(self): """Is the help displayed when no subapp...
Remove uniqueness constraint from page_scoped_id
from sqlalchemy import Column, BIGINT, String, Integer from meetup_facebook_bot.models.base import Base class Speaker(Base): __tablename__ = 'speakers' id = Column(Integer, primary_key=True, autoincrement=True) page_scoped_id = Column(BIGINT, unique=True) name = Column(String(128), nullable=False) ...
from sqlalchemy import Column, BIGINT, String, Integer from meetup_facebook_bot.models.base import Base class Speaker(Base): __tablename__ = 'speakers' id = Column(Integer, primary_key=True, autoincrement=True) page_scoped_id = Column(BIGINT) name = Column(String(128), nullable=False) token = Col...
Fix django view closure issue.
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) handler.h...
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) finalize_...
Set release version to 1.0.0a2
""" ChatterBot is a machine learning, conversational dialog engine. """ from .chatterbot import ChatBot __version__ = '1.0.0a1' __author__ = 'Gunther Cox' __email__ = 'gunthercx@gmail.com' __url__ = 'https://github.com/gunthercox/ChatterBot' __all__ = ( 'ChatBot', )
""" ChatterBot is a machine learning, conversational dialog engine. """ from .chatterbot import ChatBot __version__ = '1.0.0a2' __author__ = 'Gunther Cox' __email__ = 'gunthercx@gmail.com' __url__ = 'https://github.com/gunthercox/ChatterBot' __all__ = ( 'ChatBot', )
Reduce the size of log_name so it fits within mysql's limit.
from database import db from conversions import datetime_from_str class LogEntry(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True) server = db.Column(db.String(100), index=True) log_name = db.Column(db.String(760), index=True) message = db.Col...
from database import db from conversions import datetime_from_str class LogEntry(db.Model): id = db.Column(db.Integer, primary_key=True) timestamp = db.Column(db.DateTime, index=True) server = db.Column(db.String(100), index=True) log_name = db.Column(db.String(255), index=True) message = db.Col...
Monitor number of batches in a input batch queue
import functools import tensorflow as tf from . import cnn_dailymail_rc from ..flags import FLAGS READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files } def read_files(file_pattern, file_format): return READERS[file_format](_file_pattern_to_names(file_pattern)) def _file_pattern_to_names(pattern): re...
import functools import tensorflow as tf from . import cnn_dailymail_rc from .. import collections from ..flags import FLAGS from ..util import func_scope READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files } @func_scope def read_files(file_pattern, file_format): return monitored_batch_queue( *REA...
Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low.
import random attempts = 1 number = str(random.randint(1, 100)) while True: print number if raw_input("Guess (1 - 100): ") == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break else: print "Incorrect, Guess Again!" ...
import random attempts = 1 number = random.randint(1, 100) while True: guess = raw_input("Guess (1 - 100): ") if guess.isdigit(): guess = int(guess) if 1 <= guess and guess <= 100: if guess == number: print "Correct!" print "It Only Took You", attempt...
Use absolute import to correctly import local.py config file
from __future__ import unicode_literals try: from local import * except ImportError: try: from dev import * except ImportError: pass try: DEBUG TEMPLATE_DEBUG DATABASES['default'] CELERY_BROKER except NameError: raise NameError('Required config values not found. Abort !')
from __future__ import unicode_literals, absolute_import try: from .local import * except ImportError: try: from dev import * except ImportError: pass try: DEBUG TEMPLATE_DEBUG DATABASES['default'] CELERY_BROKER except NameError: raise NameError('Required config values not found. Abort !')
Fix example to use get
"""An example application using Confit for configuration.""" from __future__ import print_function from __future__ import unicode_literals import confit import argparse config = confit.LazyConfig('ConfitExample', __name__) def main(): parser = argparse.ArgumentParser(description='example Confit program') pa...
"""An example application using Confit for configuration.""" from __future__ import print_function from __future__ import unicode_literals import confit import argparse config = confit.LazyConfig('ConfitExample', __name__) def main(): parser = argparse.ArgumentParser(description='example Confit program') pa...
Add a test to check the right number of days in 400 year cycles.
from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) ...
from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) ...
Handle missing INCAR files gracefully
from django.shortcuts import render_to_response from django.template import RequestContext import os.path from qmpy.models import Calculation from ..tools import get_globals from bokeh.embed import components def calculation_view(request, calculation_id): calculation = Calculation.objects.get(pk=calculation_id) ...
from django.shortcuts import render_to_response from django.template import RequestContext import os from qmpy.models import Calculation from ..tools import get_globals from bokeh.embed import components def calculation_view(request, calculation_id): calculation = Calculation.objects.get(pk=calculation_id) d...
Allow passing use_list to msgpack_loads
# coding: utf8 from __future__ import unicode_literals import gc from . import msgpack from .util import force_path def msgpack_dumps(data): return msgpack.dumps(data, use_bin_type=True) def msgpack_loads(data): # msgpack-python docs suggest disabling gc before unpacking large messages gc.disable() ...
# coding: utf8 from __future__ import unicode_literals import gc from . import msgpack from .util import force_path def msgpack_dumps(data): return msgpack.dumps(data, use_bin_type=True) def msgpack_loads(data, use_list=True): # msgpack-python docs suggest disabling gc before unpacking large messages ...
Fix sentence index shifting with empty sentences
# -*- coding: utf-8 -*- from __future__ import unicode_literals from itertools import combinations from operator import itemgetter from distance import jaccard from networkx import Graph, pagerank from nltk import tokenize from .utils import get_stopwords, get_words def summarize(text, sentence_count=5, language='...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from itertools import combinations from operator import itemgetter from distance import jaccard from networkx import Graph, pagerank from nltk import tokenize from .utils import get_stopwords, get_words def summarize(text, sentence_count=5, language='...
Add Bot.run and an on_ready message
import asyncio import configparser import discord from discord.ext import commands class Bot(commands.Bot): def __init__(self, config_filepath, command_prefix): super().__init__(command_prefix) self._load_config_data(config_filepath) def _load_config_data(self, filepath): config = configparser.ConfigParser() ...
import asyncio import configparser import discord from discord.ext import commands class Bot(commands.Bot): def __init__(self, config_filepath, command_prefix): super().__init__(command_prefix) self._load_config_data(config_filepath) def _load_config_data(self, filepath): config = configparser.ConfigParser() ...
Fix a bug introduced in the latest revision, testing auth header in initialize_server_request now, thanks Chris McMichael for the report and patch
import oauth.oauth as oauth from django.conf import settings from django.http import HttpResponse from stores import DataStore OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME' def initialize_server_request(request): """Shortcut for initialization.""" oauth_request = oauth.OAuthRequest.from_request(request.meth...
import oauth.oauth as oauth from django.conf import settings from django.http import HttpResponse from stores import DataStore OAUTH_REALM_KEY_NAME = 'OAUTH_REALM_KEY_NAME' def initialize_server_request(request): """Shortcut for initialization.""" # Django converts Authorization header in HTTP_AUTHORIZATION...
Make XeLaTeX test harder (to actually test xelatex being used).
from latex.build import LatexMkBuilder def test_xelatex(): min_latex = r""" \documentclass{article} \begin{document} Hello, world! \end{document} """ builder = LatexMkBuilder(variant='xelatex') pdf = builder.build_pdf(min_latex) assert pdf
from latex.build import LatexMkBuilder def test_xelatex(): # the example below should not compile on pdflatex, but on xelatex min_latex = r""" \documentclass[12pt]{article} \usepackage{fontspec} \setmainfont{Times New Roman} \title{Sample font document} \author{Hubert Farnsworth} \date{this month, 2014} ...
Use common timezones and not all timezones pytz provides.
import pytz TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)
import pytz TIMEZONE_CHOICES = zip(pytz.common_timezones, pytz.common_timezones)
Print out the new track id.
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track.track_from_filename('audio/'+file.filename, force_upload=True)
import fore.apikeys import fore.mixer import fore.database import pyechonest.track for file in fore.database.get_many_mp3(status='all'): print("Name: {} Length: {}".format(file.filename, file.track_details['length'])) track = track.track_from_filename('audio/'+file.filename, force_upload=True) print(track.id)
Fix for the new cloudly APi.
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets from cloudly.twitterstream import Streamer from webapp import config class Publisher(Pusher): def publish(self, tweets, event): """Keep only relevant fields from the given tweets.""" stripped = [] for tweet in tweets: ...
from cloudly.pubsub import Pusher from cloudly.tweets import Tweets, StreamManager, keep from webapp import config pubsub = Pusher.open(config.pubsub_channel) def processor(tweets): pubsub.publish(keep(['coordinates'], tweets), "tweets") return len(tweets) def start(): streamer = StreamManager('locate...
Add import of django-annoying patch
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_o...
# This module contains built-in introspector plugins for various common # Django apps. # These imports trigger the lower-down files import south.introspection_plugins.geodjango import south.introspection_plugins.django_tagging import south.introspection_plugins.django_taggit import south.introspection_plugins.django_o...
Allow /dev/urandom for PHP 7
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$'] initialize = Executor.initialize
from .php_executor import PHPExecutor from dmoj.judgeenv import env class Executor(PHPExecutor): name = 'PHP7' command = env['runtime'].get('php7') fs = ['.*\.so', '/etc/localtime$', '.*\.ini$', '/dev/urandom$'] initialize = Executor.initialize
Set max celery connections to 1.
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLO...
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = os.urandom(32) SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] CELERY_BROKER_URL = os.environ['CLO...
Test importing of module with unexisting target inside
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'w...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import pytest from cihai import exc, utils def test_merge_dict(): dict1 = {'hi world': 1, 'innerdict': {'hey': 1}} dict2 = {'innerdict': {'welcome': 2}} expected = {'hi world': 1, 'innerdict': {'hey': 1, 'w...
Use nose.tools explicitly; test for port
from nose.tools import raises import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @raises(AssertionError) def test_config_bad_commands(self): """ Passes in a default config ...
import nose.tools import panoptes from panoptes.mount.ioptron import Mount class TestIOptron(): @nose.tools.raises(AssertionError) def test_no_config_no_commands(self): """ Mount needs a config """ mount = Mount() @nose.tools.raises(AssertionError) def test_config_bad_commands(self): """ Passes in a defau...
Add print function to demonstrate func calling
import datetime import csv # Question 1 # ---------- # Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app # users should be one dictionary while the count of registration month should be another dictionary. There will be # no checking or test harness so simpl...
import datetime import csv # Question 1 # ---------- # Using the csv data file users.csv aggregate app users as well as registration date by month. The count of app # users should be one dictionary while the count of registration month should be another dictionary. There will be # no checking or test harness so simpl...
Add period to end of long comment
import errno import os def file_exists(path): """Return True if a file exists at `path` (even if it can't be read), otherwise False. This is different from os.path.isfile and os.path.exists which return False if a file exists but the user doesn't have permission to read it. """ try: o...
import errno import os def file_exists(path): """Return True if a file exists at `path` (even if it can't be read), otherwise False. This is different from os.path.isfile and os.path.exists which return False if a file exists but the user doesn't have permission to read it. """ try: o...
Remove debugging print statement from changeMarginWidth
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0,...
from PyQt5.Qsci import QsciScintilla, QsciLexerPython class TextArea(QsciScintilla): def __init__(self): super().__init__() self.filePath = "Untitled" self.pythonLexer = QsciLexerPython(self) self.setLexer(self.pythonLexer) self.setMargins(1) self.setMarginType(0,...
Add print_ip method for debugging
import socks import socket from stem.control import Controller from stem import Signal class Tor(object): """Tor class for socks proxy and controller""" def __init__(self, socks_port=9050, control_port=9051, control_password=""): self.socks_port = socks_port self.control_port = control_port ...
import socks import socket import json from stem.control import Controller from stem import Signal from urllib2 import urlopen class Tor(object): """Tor class for socks proxy and controller""" def __init__(self, socks_port=9050, control_port=9051, control_password=""): self.socks_port = socks_port ...
Include ashist in the general namespace by default
#__all__ = ["hists", "binning"] from .hists import * #from .converter import ashist
#__all__ = ["hists", "binning"] from .hists import * from .converter import ashist
Remove unused modules, fix HTML response
#!/usr/bin/python # Based on examples from # http://www.tutorialspoint.com/python/python_cgi_programming.htm import sys import cgi import os import cgitb cgitb.enable() CSV_DIR = '../csv/' # CSV upload directory form = cgi.FieldStorage() fileitem = form['filename'] # Get filename # Check if the file was uploaded ...
#!/usr/bin/python # Based on examples from # http://www.tutorialspoint.com/python/python_cgi_programming.htm import cgi import os import cgitb cgitb.enable() CSV_DIR = '../csv/' # CSV upload directory form = cgi.FieldStorage() fileitem = form['filename'] # Get filename # Check if the file was uploaded if fileitem...
Make it work with Python 3.
# -*- coding: utf-8 -*- __author__ = 'Ardy Dedase' __email__ = 'ardy.dedase@skyscanner.net' __version__ = '0.1.0' from skyscanner import Flights, FlightsCache, Hotels, CarHire
# -*- coding: utf-8 -*- __author__ = 'Ardy Dedase' __email__ = 'ardy.dedase@skyscanner.net' __version__ = '0.1.0' from .skyscanner import Flights, FlightsCache, Hotels, CarHire
Fix uploader when there is nothing to upload
#!/usr/bin/env python # 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/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): ""...
#!/usr/bin/env python # 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/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): ""...
Add documentation and fix pop
class DepthFirstSearchStrategy: def __init__(self, content, max_depth): self.content = content self.max_depth = max_depth def __iter__(self): return self def __next__(self): try: global_state = self.content.pop(0) if global_state.mstate.depth >= sel...
""" This module implements basic symbolic execution search strategies """ class DepthFirstSearchStrategy: """ Implements a depth first search strategy I.E. Follow one path to a leaf, and then continue to the next one """ def __init__(self, work_list, max_depth): self.work_list = work_list ...
Truncate ROI-smoothing Gaussian at 2 STD per default.
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D...
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- ...
Print progress from the indexing script
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path): count = 0 index = [] for path in sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))): data = task...
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path, report_each=10000): print('Looking for data in "{}"...'.format(data_path)) paths = sorted(glob.glob('{}/**/*.sqli...
Make the test runner more resilient to weird registry configurations.
"""Runs the PyExtTest project against all installed python instances.""" import sys, subprocess, python_installations if __name__ == '__main__': num_failed_tests = 0 for installation in python_installations.get_python_installations(): # Only test against official CPython installations. if insta...
"""Runs the PyExtTest project against all installed python instances.""" import sys, subprocess, python_installations if __name__ == '__main__': num_failed_tests = 0 for installation in python_installations.get_python_installations(): # Skip versions with no executable. if installation.exec_pa...
Make site url be http, not https
from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.contrib.syndication.views import add_domain from django.contrib.sites.models import get_current_site def get_site_url(request, path): current_site = get_current_site(request) return add_domain(current_site.domain, path, request.i...
from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.contrib.syndication.views import add_domain from django.contrib.sites.models import get_current_site def get_site_url(request, path): """Retrieve current site site Always returns as http (never https) """ current_site = g...
Fix correction to comply with black
from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path admin.autodiscover() urlpatterns = [ path("admin/", admin.site.urls), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Simplify the output for copypaste
from django.core.management.base import BaseCommand, CommandError from stationspinner.character.models import CharacterSheet class Command(BaseCommand): help = 'Lists all enabled characterIDs with their APIKey PKs. Handy for sending tasks' def handle(self, *args, **options): characters = CharacterShee...
from django.core.management.base import BaseCommand, CommandError from stationspinner.character.models import CharacterSheet class Command(BaseCommand): help = 'Lists all enabled characterIDs with their APIKey PKs. Handy for sending tasks' def handle(self, *args, **options): characters = CharacterShee...
Update config test to use eq_ matcher
from nose.tools import assert_equals from openpassword.config import Config class ConfigSpec: def it_sets_the_path_to_the_keychain(self): cfg = Config() cfg.set_path("path/to/keychain") assert_equals(cfg.get_path(), "path/to/keychain")
from nose.tools import * from openpassword.config import Config class ConfigSpec: def it_sets_the_path_to_the_keychain(self): cfg = Config() cfg.set_path("path/to/keychain") eq_(cfg.get_path(), "path/to/keychain")
Increment version in preperation for release of version 1.2.0
try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Ignore import error and assume Python 3 which already has setuptools. pass from setuptools import setup DESC = ('This Python library for Raspberry Pi...
try: # Try using ez_setup to install setuptools if not already installed. from ez_setup import use_setuptools use_setuptools() except ImportError: # Ignore import error and assume Python 3 which already has setuptools. pass from setuptools import setup DESC = ('This Python library for Raspberry Pi...