Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix "AppRegistryNotReady: Models aren't loaded yet"
#!/usr/bin/env python import sys from os.path import dirname, abspath import django from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'django.db.bac...
#!/usr/bin/env python import sys from os.path import dirname, abspath import django from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'django.db.bac...
Make data_files paths absolute again
# -*- coding: utf-8 -*- import sys import os.path from setuptools import Command, find_packages, setup HERE = os.path.abspath(os.path.dirname(__file__)) README_PATH = os.path.join(HERE, 'README.rst') try: README = open(README_PATH).read() except IOError: README = '' setup( name='rollbar-udp-agent', v...
# -*- coding: utf-8 -*- import sys import os.path from setuptools import Command, find_packages, setup HERE = os.path.abspath(os.path.dirname(__file__)) README_PATH = os.path.join(HERE, 'README.rst') try: README = open(README_PATH).read() except IOError: README = '' setup( name='rollbar-udp-agent', v...
Update six version to match
from setuptools import setup, find_packages setup( name="cdispyutils", version="0.1.0", description="General utilities", license="Apache", install_requires=[ "six==1.10.0", "requests==2.13.0", ], packages=find_packages(), )
from setuptools import setup, find_packages setup( name="cdispyutils", version="0.1.0", description="General utilities", license="Apache", install_requires=[ "six==1.11.0", "requests==2.13.0", ], packages=find_packages(), )
Create profile if user is created
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User) def __str__(self): return self.user.get_full_name() or self.user.username
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User) def __str__(self): return self.user.get_full_name() or self.user.username def create_user_profile(sender, instance, ...
Add limit_choices_to to CustomLink.content_type field
# Generated by Django 2.2 on 2019-04-15 19:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('extras', '0021_add_color_comments_changelog_to_tag'), ] op...
# Generated by Django 2.2 on 2019-04-15 19:28 from django.db import migrations, models import django.db.models.deletion import extras.models class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('extras', '0021_add_color_comments_changelog_to...
Disable test for py27 (mock not available)
"""Unit test some basic response rendering functionality. These tests use the unittest.mock mechanism to provide a simple Assistant instance for the _Response initialization. """ from unittest.mock import patch from flask import Flask from flask_assistant import Assistant from flask_assistant.response import _Respons...
"""Unit test some basic response rendering functionality. These tests use the unittest.mock mechanism to provide a simple Assistant instance for the _Response initialization. """ from flask import Flask from flask_assistant import Assistant from flask_assistant.response import _Response import pytest patch = pytest.i...
Fix passed args (no more program name)
# -*- coding: utf-8 -*- """ Entrypoint module, in case you use `python -mdependenpy`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ ...
# -*- coding: utf-8 -*- """ Entrypoint module, in case you use `python -mdependenpy`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ ...
Fix usage comment to refer to the correct filename
""" Usage: $ python test_group_name.py group_1 test_foo.py test_bar.py::TestClass $ This is used by CI to run only a certain set of tests on a particular builder. See ``test_groups.yaml`` for details. """ import yaml from pathlib import Path from typing import List import click def patterns_from_group(group_name...
""" Usage: $ python get_test_group.py group_1 test_foo.py test_bar.py::TestClass $ This is used by CI to run only a certain set of tests on a particular builder. See ``test_groups.yaml`` for details. """ import yaml from pathlib import Path from typing import List import click def patterns_from_group(group_name:...
Fix deprecation warning for get_query_set
from django.db import models class BasisModelManager(models.Manager): def get_query_set(self): return super(BasisModelManager, self).get_query_set().filter(deleted=False)
from django.db import models from .compat import DJANGO16 if DJANGO16: class BasisModelManager(models.Manager): def get_queryset(self): return super(BasisModelManager, self).get_queryset().filter(deleted=False) else: class BasisModelManager(models.Manager): def get_query_set(self):...
Change directory test to look for link, rather than just file name
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very ...
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very ...
Switch from () to __call__()
from abc import ( ABCMeta, abstractmethod, ) from impact.v1.helpers import ( STRING_FIELD, ) class BaseHistoryEvent(object): __metaclass__ = ABCMeta CLASS_FIELDS = { "event_type": STRING_FIELD, "datetime": STRING_FIELD, "latest_datetime": STRING_FIELD, "description...
from abc import ( ABCMeta, abstractmethod, ) from impact.v1.helpers import ( STRING_FIELD, ) class BaseHistoryEvent(object): __metaclass__ = ABCMeta CLASS_FIELDS = { "event_type": STRING_FIELD, "datetime": STRING_FIELD, "latest_datetime": STRING_FIELD, "description...
Change the url patters from python_social_auth to social_django
"""djangoTemplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('base.urls')), url('', ...
"""djangoTemplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url('', include('base.urls')), url('', ...
Update to v3 of the auth0 client for the exception handling
try: from auth0.v2.exceptions import Auth0Error except ImportError: # pragma: no cover class Auth0Error(Exception): def __init__(self, status_code, error_code, message): self.status_code = status_code self.error_code = error_code self.message = message def ...
try: from auth0.v3.exceptions import Auth0Error except ImportError: # pragma: no cover class Auth0Error(Exception): def __init__(self, status_code, error_code, message): self.status_code = status_code self.error_code = error_code self.message = message def ...
REVERT remove application id validation
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): if event['session']['new']: events.on_session_started({'requestId': event['request']['requestId']}, event['session']) request...
import handlers.events as events APPLICATION_ID = "amzn1.ask.skill.dd677950-cade-4805-b1f1-ce2e3a3569f0" def lambda_handler(event, context): # Make sure only this Alexa skill can use this function if event['session']['application']['applicationId'] != APPLICATION_ID: raise ValueError("Invalid Applica...
Rework the import finding logic
import ast def get_imported_libs(code): tree = ast.parse(code) # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second imports = [name.name.split...
import ast import os from collections import deque import sys from stdlib_list import stdlib_list conf = { 'ignore_relative_imports': True, 'ignore_builtin_modules': True, 'pyver': None, } def get_imported_libs(code): tree = ast.parse(code) imports = deque() for t in tree.body: # ast....
Return proper WWW-Authenticate header if API authentication fails
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from ...services.authentication.api import service as a...
""" byceps.blueprints.api.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from functools import wraps from typing import Optional from flask import abort, request from werkzeug.datastructures import WWWAuthenticate fro...
Remove test for deprecated createmultsig option
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_f...
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class Depr...
Fix a bug that would add updated control ip address instead of replace
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNet...
from pprint import pprint from netaddr import * def merge(dbag, ip): added = False for dev in dbag: if dev == "id": continue for address in dbag[dev]: if address['public_ip'] == ip['public_ip']: dbag[dev].remove(address) if ip['add']: ipo = IPNet...
Update minimum support boto version.
#!/usr/bin/env python from __future__ import unicode_literals from setuptools import setup, find_packages install_requires = [ "Jinja2", "boto", "flask", "httpretty>=0.6.1", "requests", "xmltodict", "six", "werkzeug", ] import sys if sys.version_info < (2, 7): # No buildint Ordere...
#!/usr/bin/env python from __future__ import unicode_literals from setuptools import setup, find_packages install_requires = [ "Jinja2", "boto>=2.20.0", "flask", "httpretty>=0.6.1", "requests", "xmltodict", "six", "werkzeug", ] import sys if sys.version_info < (2, 7): # No buildin...
Fix Attempted relative import beyond top-level package
# -*- coding: utf-8 -*- from django.contrib import admin from survey.models import Answer, Category, Question, Response, Survey from .actions import make_published class QuestionInline(admin.TabularInline): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(admin.Tabular...
# -*- coding: utf-8 -*- from django.contrib import admin from survey.actions import make_published from survey.models import Answer, Category, Question, Response, Survey class QuestionInline(admin.TabularInline): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(admin.Ta...
Update check_requires_python and describe behavior in docstring
from __future__ import absolute_import import logging import sys from pip._vendor import pkg_resources from pip._vendor.packaging import specifiers from pip._vendor.packaging import version logger = logging.getLogger(__name__) def get_metadata(dist): if (isinstance(dist, pkg_resources.DistInfoDistribution) and...
from __future__ import absolute_import import logging import sys from pip._vendor import pkg_resources from pip._vendor.packaging import specifiers from pip._vendor.packaging import version logger = logging.getLogger(__name__) def get_metadata(dist): if (isinstance(dist, pkg_resources.DistInfoDistribution) and...
Return pre-built dockerfile to user
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SciStack: the web app to build docker containers for reproducable science """ import os import flask app = flask.Flask(__name__) @app.route("/") def hello(): return "Choose a domain!" if __name__ == "__main__": app.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SciStack: the web app to build docker containers for reproducable science """ import os import flask import inspect app = flask.Flask(__name__, static_url_path='') # Home of any pre-build docker files docker_file_path = os.path.join(os.path.dirname(os.path.abspath( ...
Simplify test execution to restore coverage measurement
import unittest import sys import subprocess if __name__ == '__main__': if len(sys.argv) > 1: unittest.main(module='flask_api.tests') else: subprocess.call([sys.executable, '-m', 'unittest', 'discover'])
import unittest if __name__ == '__main__': unittest.main(module='flask_api.tests')
Add functionality to build the DMCColors set.
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): print ro...
import csv import os import color def _GetDataDirPath(): return os.path.join(os.path.dirname(__file__), 'data') def _GetCsvPath(): return os.path.join(_GetDataDirPath(), 'dmccolors.csv') def _GetCsvString(): with open(_GetCsvPath()) as f: return f.read().strip() def _CreateDmcColorFromRow(row): number =...
Remove the dependency to django-unittest-depth
"""Django page CMS test suite module""" from djangox.test.depth import alltests def suite(): return alltests(__file__, __name__)
"""Django page CMS test suite module""" import unittest def suite(): suite = unittest.TestSuite() from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link i...
Return proper results for 'test=True'
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' def __virtual__(): ''' Load only if network_win is loaded ''' return 'rdp' if 'rdp.enable' in __salt__ else False def enabled(name): ''' Enable RDP the service on the server ''' ret = {'name': name, 'res...
# -*- coding: utf-8 -*- ''' Manage RDP Service on Windows servers ''' def __virtual__(): ''' Load only if network_win is loaded ''' return 'rdp' if 'rdp.enable' in __salt__ else False def enabled(name): ''' Enable RDP the service on the server ''' ret = {'name': name, 'res...
Fix test_show test to support tuned systems
import os.path import sys from perf.tests import get_output from perf.tests import unittest class SystemTests(unittest.TestCase): def test_show(self): args = [sys.executable, '-m', 'perf', 'system', 'show'] proc = get_output(args) regex = ('(Run "%s -m perf system tune" to tune the syste...
import os.path import sys from perf.tests import get_output from perf.tests import unittest class SystemTests(unittest.TestCase): def test_show(self): args = [sys.executable, '-m', 'perf', 'system', 'show'] proc = get_output(args) regex = ('(Run "%s -m perf system tune" to tune the syste...
Fix parallel example for Python 3
import rx import concurrent.futures import time seconds = [5, 1, 2, 4, 3] def sleep(t): time.sleep(t) return t def output(result): print '%d seconds' % result with concurrent.futures.ProcessPoolExecutor(5) as executor: rx.Observable.from_(seconds).flat_map( lambda s: executor.submit(sleep,...
from __future__ import print_function import rx import concurrent.futures import time seconds = [5, 1, 2, 4, 3] def sleep(t): time.sleep(t) return t def output(result): print('%d seconds' % result) with concurrent.futures.ProcessPoolExecutor(5) as executor: rx.Observable.from_(seconds).flat_map( ...
Fix slot name in HardwareDevice
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types...
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types...
Add linecache module to skipped modules for pytest plugin
"""A pytest plugin for using pyfakefs as a fixture When pyfakefs is installed, the "fs" fixture becomes available. :Usage: def my_fakefs_test(fs): fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher ...
"""A pytest plugin for using pyfakefs as a fixture When pyfakefs is installed, the "fs" fixture becomes available. :Usage: def my_fakefs_test(fs): fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import linecache import py import pytest from pyfakefs.fake_filesystem_unittes...
Add units to Core import.
""" This package contains core modules and classes for representing structures and operations on them. """ __author__ = "Shyue Ping Ong" __date__ = "Dec 15, 2010 7:21:29 PM" from .periodic_table import * from .composition import * from .structure import * from .structure_modifier import * from .bonds import * from .l...
""" This package contains core modules and classes for representing structures and operations on them. """ __author__ = "Shyue Ping Ong" __date__ = "Dec 15, 2010 7:21:29 PM" from .periodic_table import * from .composition import * from .structure import * from .structure_modifier import * from .bonds import * from .l...
Clean - tool is not required, as tool_supported are there
# Copyright 2014-2015 0xc0170 # # 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,...
# Copyright 2014-2015 0xc0170 # # 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,...
Remove errant printout in python cone layout example.
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") reader.Update() print reader.GetOutput() view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName...
from vtk import * reader = vtkXMLTreeReader() reader.SetFileName("vtkclasses.xml") view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(reader.GetOutputPort()) view.SetVertexLabelArrayName("id") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("vertex id") view.SetColorVertices(True)...
Improve API robustness Case where no JSON is sent
#!/usr/bin/python3 from flask import Flask, jsonify, request from funds_correlations import correlations, parse_performances_from_dict import traceback app = Flask(__name__) @app.route("/correlations", methods=['POST']) def correlation_api(): req_json = request.get_json() perf_list = parse_performances_from_d...
#!/usr/bin/python3 from flask import Flask, jsonify, request from funds_correlations import correlations, parse_performances_from_dict import traceback app = Flask(__name__) @app.route("/correlations", methods=['POST']) def correlation_api(): try: req_json = request.get_json() valid_input = True ...
Revert "Implement send message functionality"
from lib.config import Config from slackclient import SlackClient class Tubey(): def __init__(self, **kwargs): ### Cache the client in memory ### self._client = None def get_client(self): ### Fetch a cached slack client or create one and return it ### if self._client is not No...
from lib.config import Config from slackclient import SlackClient class Tubey(): def __init__(self, **kwargs): # cache the client in memory self._client = None def send_message(self, message): raise NotImplemented def get_client(self): ### Fetch a cached slack client or c...
Use flask.flash instead of tg.flash
# -*- coding: utf-8 -*- """WebHelpers used in SkyLines.""" from __future__ import absolute_import import datetime import simplejson as json from urllib import urlencode from tg import flash from webhelpers import date, feedgenerator, html, number, misc, text from .string import * from .country import * from skylin...
# -*- coding: utf-8 -*- """WebHelpers used in SkyLines.""" from __future__ import absolute_import import datetime import simplejson as json from urllib import urlencode from flask import flash from webhelpers import date, feedgenerator, html, number, misc, text from .string import * from .country import * from sky...
Fix compatibility with Numpy 1.4.1
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_SCI...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from ....tests.compat import assert_allclose from ....tests.helper import pytest from ..make_kernel import make_kernel try: import scipy HAS_SCIPY = True except ImportError: HAS_SCIPY = False @pytest.mark.skipif('not HAS_...
Remove a couple useless imports
import datetime import json import logging import socket import traceback from threading import Thread from splunklib import client _client = None class SplunkFilter(logging.Filter): """ A logging filter for Splunk's debug logs on the root logger to avoid recursion """ def filter(self, record): ...
import logging import socket import traceback from threading import Thread from splunklib import client _client = None class SplunkFilter(logging.Filter): """ A logging filter for Splunk's debug logs on the root logger to avoid recursion """ def filter(self, record): return not (record.modu...
Add db_name to options for use in model.Meta class
VERSION = (0, 0, 0) __version__ = '.'.join(map(str, VERSION)) from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development')
VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) from django import template template.add_to_builtins('common.templatetags.common') template.add_to_builtins('common.templatetags.development') # Add db_name to options for use in model.Meta class import django.db.models.options as options options.DEFAULT_N...
Replace call to deprecated virtool.file.processor
import os import virtool.file import virtool.utils from virtool.handlers.utils import json_response, not_found async def find(req): db = req.app["db"] query = { "ready": True } file_type = req.query.get("type", None) if file_type: query["type"] = file_type cursor = db.file...
import os import virtool.file import virtool.utils from virtool.handlers.utils import json_response, not_found async def find(req): db = req.app["db"] query = { "ready": True } file_type = req.query.get("type", None) if file_type: query["type"] = file_type cursor = db.file...
Make sure correct type is excluded
from collections import OrderedDict def form_questions(form): d = OrderedDict() children = form['children'] for child in children: if 'pathstr' in child and 'control' not in child: d.update({child['pathstr']: ''}) elif 'children' in child: for minor in child['childr...
from collections import OrderedDict def form_questions(form): d = OrderedDict() children = form['children'] for child in children: if 'pathstr' in child and 'control' not in child and child['type'] != 'group': d.update({child['pathstr']: ''}) elif 'children' in child: ...
Use the Model constructor to generate a default value
import hashlib import random import string from ext.aboard.model import * def set_value(token): """Randomly create and return a value.""" value = str(token.user) + "_" + str(token.timestamp) len_rand = random.randint(20, 40) to_pick = string.digits + string.ascii_letters + \ "_-+^$" fo...
import hashlib import random import string from ext.aboard.model import * class Token(Model): """A token model.""" id = None user = Integer() timestamp = Integer() value = String(pkey=True) def __init__(self, user=None, timestamp=None): value = None if user and t...
Save .travis.yml into build properties
from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step whic...
from buildbot.process import buildstep from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION from buildbot.process.properties import Properties from twisted.internet import defer from ..travisyml import TravisYml class ConfigurableStep(buildstep.LoggingBuildStep): """ Base class for a step whic...
Change yield from to return to be compatible with python 3.2
from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def get_me(self): return self.telegram_api.get_me() def send_message(self, mess...
from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def get_me(self): return self.telegram_api.get_me() def send_message(self, mess...
Remove VAT number from supplier constants
# Here we define a set of hardcoded keys that we use when denormalizing data from Supplier/ContactInformation tables # into the SupplierFramework.declaration field. These are used only by the API and by the # `digitalmarketplace-scripts/scripts/generate-framework-agreement-*-pages`, which generates framework agreement ...
# Here we define a set of hardcoded keys that we use when denormalizing data from Supplier/ContactInformation tables # into the SupplierFramework.declaration field. These are used only by the API and by the # `digitalmarketplace-scripts/scripts/generate-framework-agreement-*-pages`, which generates framework agreement ...
Add a hack to overcome driver name inconsistency in libcloud.
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security from config import get_config def get_lc(profile, resource=None): if resource is None: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driv...
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security from config import get_config def get_lc(profile, resource=None): if resource is None: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driv...
Switch database connection string to pg
#!/usr/bin/env python """ See LICENSE.txt file for copyright and license details. """ import os basedir = os.path.abspath(os.path.dirname(__file__)) WTF_CSRF_ENABLED = True SECRET_KEY = '3124534675689780' # TODO: switch this to postgresql SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') ...
#!/usr/bin/env python """ See LICENSE.txt file for copyright and license details. """ import os basedir = os.path.abspath(os.path.dirname(__file__)) WTF_CSRF_ENABLED = True SECRET_KEY = '3124534675689780' dbuser = 'rockwolf' dbpass = '' dbhost = 'testdb' dbname = 'finance' SQLALCHEMY_DATABASE_URI = 'postgresql:...
Add videos dict to Games.
from datetime import datetime GAME_VIDEO_BASE_URL = "http://www.nfl.com/feeds-rs/videos/byGameCenter/{0}.json" LIVE_UPDATE_BASE_URL = "http://www.nfl.com/liveupdate/game-center/{0}/{0}_gtd.json" class Game(object): def __init__(self, id_, h, v): self.id_ = id_ self.date = self.id_[:-2] s...
from datetime import datetime GAME_VIDEO_BASE_URL = "http://www.nfl.com/feeds-rs/videos/byGameCenter/{0}.json" LIVE_UPDATE_BASE_URL = "http://www.nfl.com/liveupdate/game-center/{0}/{0}_gtd.json" class Game(object): def __init__(self, id_, h, v): self.id_ = id_ self.date = self.id_[:-2] s...
Handle a Werkzeug ClosingIterator (as exposed by the tests)
# -*- encoding: utf-8 import json from flask import Response, jsonify class ContextResponse(Response): """ This class adds the "@context" parameter to JSON responses before they're sent to the user. For an explanation of how this works/is used, read https://blog.miguelgrinberg.com/post/customiz...
# -*- encoding: utf-8 import json from flask import Response, jsonify from werkzeug.wsgi import ClosingIterator class ContextResponse(Response): """ This class adds the "@context" parameter to JSON responses before they're sent to the user. For an explanation of how this works/is used, read htt...
Fix bot not joining any channels
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
Implement more TGT Shaman cards
from ..utils import * ## # Hero Powers # Lightning Jolt class AT_050t: play = Hit(TARGET, 2) ## # Minions # Tuskarr Totemic class AT_046: play = Summon(CONTROLLER, RandomTotem()) # Draenei Totemcarver class AT_047: play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM) # Thunder Bluff Valiant class...
from ..utils import * ## # Hero Powers # Lightning Jolt class AT_050t: play = Hit(TARGET, 2) ## # Minions # Tuskarr Totemic class AT_046: play = Summon(CONTROLLER, RandomTotem()) # Draenei Totemcarver class AT_047: play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM) # Thunder Bluff Valiant class...
Set permission mask to allow read/exec for all users
#!/usr/bin/env python import subprocess from distutils.core import setup requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()] description = 'Download videos from Udemy for personal offline use' try: subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o", "README...
#!/usr/bin/env python import os import subprocess from distutils.core import setup requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()] description = 'Download videos from Udemy for personal offline use' try: subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o...
Fix a Django deprecation warning
# -*- coding: utf-8 -*- from django import template from admin_interface.models import Theme register = template.Library() @register.assignment_tag(takes_context = True) def get_admin_interface_theme(context): theme = None request = context.get('request', None) if request: theme = getattr(re...
# -*- coding: utf-8 -*- from django import template from admin_interface.models import Theme register = template.Library() @register.simple_tag(takes_context = True) def get_admin_interface_theme(context): theme = None request = context.get('request', None) if request: theme = getattr(reques...
Change biolookup test to work around service bug
from indra.databases import biolookup_client def test_lookup_curie(): curie = 'pubchem.compound:40976' res = biolookup_client.lookup_curie(curie) assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \ 'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \ 'cyclopenta[a]phenanth...
from indra.databases import biolookup_client def test_lookup_curie(): curie = 'pubchem.compound:40976' res = biolookup_client.lookup_curie(curie) assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \ 'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \ 'cyclopenta[a]phenanth...
Change to cb_story, clean up TZ handling some more
""" Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format WARNING: you must have PyXML installed as part of your python installation in order for this plugin to work Place this plugin early in your load_plugins list, so that the w3cdate will be available to subsequent plugins """ __author__ ...
""" Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format WARNING: you must have PyXML installed as part of your python installation in order for this plugin to work Place this plugin early in your load_plugins list, so that the w3cdate will be available to subsequent plugins """ __author__ ...
Include the tags module tests in the full library testsuite.
import unittest import test_primitives, test_astypes, test_helpers def get_suite(): modules = (test_primitives, test_astypes, test_helpers) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): unittest.TextTestRu...
import unittest import test_primitives, test_astypes, test_helpers, test_tags def get_suite(): modules = (test_primitives, test_astypes, test_helpers, test_tags) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): ...
Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES
import pytz from dateutil.rrule import DAILY, WEEKLY from django.utils.translation import ugettext_lazy as _ GENDER_CHOICES = ( ('M', _('Male')), ('F', _('Female')), ('X', _('Unspecified')), ) SEASON_MODE_CHOICES = ( (WEEKLY, _("Season")), (DAILY, _("Tournament")), ) WIN_LOSE = { 'W': _("Winn...
import pytz from dateutil.rrule import DAILY, WEEKLY from django.utils.translation import ugettext_lazy as _ GENDER_CHOICES = ( ('M', _('Male')), ('F', _('Female')), ('X', _('Unspecified')), ) SEASON_MODE_CHOICES = ( (WEEKLY, _("Season")), (DAILY, _("Tournament")), ) WIN_LOSE = { 'W': _("Winn...
Debug control flow and exit on errors
#! /usr/bin/python2 from os.path import expanduser,isfile from sys import argv from urllib import urlopen location_path="~/.location" def location_from_homedir(): if isfile(expanduser(location_path)): with open(expanduser(location_path)) as f: return "&".join(f.read().split("\n")) else: ...
#! /usr/bin/python2 from os.path import expanduser,isfile import sys from urllib import urlopen location_path="~/.location" def location_from_homedir(): if isfile(expanduser(location_path)): with open(expanduser(location_path)) as f: return "&".join(f.read().split("\n")) else: pri...
Remove admin prefix from url
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'helpdesk.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'helpdesk.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'', include(admin.site.urls)), )
Document module and add couple of tests
from nap.api import Api from . import HttpServerTestBase class TestNap(HttpServerTestBase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('http://localhost:8888') with self.assertRaises(AttributeError): api.resource.nonexisting()
""" Tests for nap module. These tests only focus that requests is called properly. Everything related to HTTP requests should be tested in requests' own tests. """ import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use...
Modify version to 0.72 to mark change
# -*- coding: utf-8 -*- """ File : pyhaystackTest.py (2.x) This module allow a connection to a haystack server Feautures provided allow user to fetch data from the server and eventually, to post to it. See http://www.project-haystack.org for more details Project Haystack is an open source initiative to streamline wor...
# -*- coding: utf-8 -*- """ File : pyhaystackTest.py (2.x) This module allow a connection to a haystack server Feautures provided allow user to fetch data from the server and eventually, to post to it. See http://www.project-haystack.org for more details Project Haystack is an open source initiative to streamline wor...
Remove callback url and bring uploads together
""" Predict app's urls """ # # pylint: disable=bad-whitespace # from django.conf.urls import patterns, include, url from .views import * def url_tree(regex, *urls): """Quick access to stitching url patterns""" return url(regex, include(patterns('', *urls))) urlpatterns = patterns('', url(r'^$', Datasets.as...
""" Predict app's urls """ # # pylint: disable=bad-whitespace # from django.conf.urls import patterns, include, url from .views import * def url_tree(regex, *urls): """Quick access to stitching url patterns""" return url(regex, include(patterns('', *urls))) urlpatterns = patterns('', url(r'^$', Datasets.as...
Add logging verbosity to game analysis
"""Command line module""" import argparse import pkgutil import sys import gameanalysis from gameanalysis import script def create_parser(): """Create the default parser""" modules = [imp.find_module(name).load_module(name) for imp, name, _ in pkgutil.iter_modules(script.__path__)] parser ...
"""Command line module""" import argparse import logging import pkgutil import sys import gameanalysis from gameanalysis import script def create_parser(): """Create the default parser""" modules = [imp.find_module(name).load_module(name) for imp, name, _ in pkgutil.iter_modules(script.__path_...
Make import of `patches` explicitly relative.
import os import sys extra_library_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "lib") if extra_library_path not in sys.path: sys.path.insert(1, extra_library_path) default_app_config = 'djangae.apps.DjangaeConfig' from patches import json json.patch()
import os import sys extra_library_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "lib") if extra_library_path not in sys.path: sys.path.insert(1, extra_library_path) default_app_config = 'djangae.apps.DjangaeConfig' from .patches import json json.patch()
Increase timer on automation to avoid raising suspicion
import login import time import navigate import modal def automate(username, password, tag): driver = login.login(username, password) navigate.tag(driver, tag) modal.open(driver) while True: try: modal.follow(driver) modal.next(driver) except Exception as e: print(e.__doc__) print(e.message) nav...
import login import time import navigate import modal def automate(username, password, tag): driver = login.login(username, password) navigate.tag(driver, tag) modal.open(driver) while True: try: modal.follow(driver) modal.next(driver) except Exception as e: print(e.__doc__) print(e.message) nav...
Add TODO and clean up render function
import re from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer class JSONAPIRenderer(JSONRenderer): format = "jsonapi" media_type = 'application/vnd.api+json' def render(self, data, accepted_media_type=None, renderer_context=None): stuff = super(JSONAPIRenderer, self).render(dat...
import re from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer class JSONAPIRenderer(JSONRenderer): format = "jsonapi" media_type = 'application/vnd.api+json' def render(self, data, accepted_media_type=None, renderer_context=None): # TODO: There should be a way to do this that ...
Test for URL length error
""" Level 1 file for creating Eddystone beacons """ from bluezero import tools from bluezero import broadcaster class EddystoneURL: def __init__(self, url): service_data = tools.url_to_advert(url, 0x10, 0x00) url_beacon = broadcaster.Beacon() url_beacon.add_service_data('FEAA', service_dat...
""" Level 1 file for creating Eddystone beacons """ from bluezero import tools from bluezero import broadcaster class EddystoneURL: def __init__(self, url, tx_power=0x08): """ The Eddystone-URL frame broadcasts a URL using a compressed encoding format in order to fit more within the limite...
Modify ffmpeg path heroku 3
# Retrieve file from Facebook import urllib, convert, re, os # from speech_py import speech_to_text_offline as STT_o # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./a...
# Retrieve file from Facebook import urllib, convert, re, os # from speech_py import speech_to_text_google as STT from speech_py import speech_to_text_ibm_rest as STT def transcribe(audio_url): if not os.path.isdir('./audio/retrieved_audio'): os.makedirs('./audio/retrieved_audio') reg_ex = '\w+.mp4' file_name =...
Revert "Revert "Changed back due to problems, will fix later""
from distutils.core import setup import sys import os import re PACKAGENAME = 'OpSimSummary' packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opsimsummary') versionFile = os.path.join(packageDir, 'version.py') # Obtain the package version with open(versionFile, 'r') as...
from distutils.core import setup import sys import os import re PACKAGENAME = 'OpSimSummary' packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), PACKAGENAME) versionFile = os.path.join(packageDir, 'version.py') # Obtain the package version with open(versionFile, 'r') as f:...
Add a download_url for pypi
#!/usr/bin/python import distutils from setuptools import setup, Extension long_desc = """This is a C extension module for Python which implements extended attributes manipulation. It is a wrapper on top of the attr C library - see attr(5).""" version = "0.5.1" author = "Iustin Pop" author_email = "iusty@k1024.org" m...
#!/usr/bin/python import distutils from setuptools import setup, Extension long_desc = """This is a C extension module for Python which implements extended attributes manipulation. It is a wrapper on top of the attr C library - see attr(5).""" version = "0.5.1" author = "Iustin Pop" author_email = "iusty@k1024.org" m...
Use "submission_id" instead of "instance_id" parameter to send to KPI for RESTservice
# coding: utf-8 import logging import re import requests from django.conf import settings from onadata.apps.restservice.RestServiceInterface import RestServiceInterface from onadata.apps.logger.models import Instance class ServiceDefinition(RestServiceInterface): id = 'kpi_hook' verbose_name = 'KPI Hook POST...
# coding: utf-8 import logging import re import requests from django.conf import settings from onadata.apps.restservice.RestServiceInterface import RestServiceInterface from onadata.apps.logger.models import Instance class ServiceDefinition(RestServiceInterface): id = 'kpi_hook' verbose_name = 'KPI Hook POST...
Add docstrings to all functions
#!/usr/bin/env python import csv import json import os import sys def format_entities_as_list(entities): for i, entity in enumerate(entities, 1): yield (unicode(i), json.dumps(entity["terms"])) def generate_entities(fobj): termsets_seen = set() for line in fobj: entity = json.loads(line...
#!/usr/bin/env python import csv import json import os import sys def format_entities_as_list(entities): """Format entities read from an iterator as lists. :param entities: An iterator yielding entities as dicts: eg {"terms": ["Fred"]} Yield a sequence of entites formatted as lists containin...
Use the correct Requests OAuth lib version (previously we used a patched lib).
import os try: from setuptools import setup except ImportError: from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() required = ['requests>=0.11.2', 'requests-oauth2>=0.2.1'] setup( name='basecampx', version='0.1.7', ...
import os try: from setuptools import setup except ImportError: from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() required = ['requests>=0.11.2', 'requests-oauth2>=0.2.0'] setup( name='basecampx', version='0.1.7', ...
Rename distribution avogadrolibs => avogadro
from skbuild import setup setup( name="avogadrolibs", version="0.0.8", description="", author='Kitware', license="BSD", packages=['avogadro'], cmake_args=[ '-DUSE_SPGLIB:BOOL=FALSE', '-DUSE_OPENGL:BOOL=FALSE', '-DUSE_QT:BOOL=FALSE', '-DUSE_MMTF:BOOL=FALSE', ...
from skbuild import setup setup( name="avogadro", version="0.0.8", description="", author='Kitware', license="BSD", packages=['avogadro'], cmake_args=[ '-DUSE_SPGLIB:BOOL=FALSE', '-DUSE_OPENGL:BOOL=FALSE', '-DUSE_QT:BOOL=FALSE', '-DUSE_MMTF:BOOL=FALSE', ...
Change default channel to test_bed
import httplib import urllib import json class Slack: def __init__(self, webhook_path, url='hooks.slack.com', channel='#sigbridge', username="sb-bot", icon=":satellite:"): self.web_hook_url = url self.webhook_path = webhook_path self.channel = channel self.user...
import httplib import urllib import json class Slack: def __init__(self, webhook_path, url='hooks.slack.com', channel='#test_bed', username="sb-bot", icon=":satellite:"): self.web_hook_url = url self.webhook_path = webhook_path self.channel = channel self.userna...
Update errors for other versions of Pyro
#!/usr/bin/env python import sys import Pyro import Tkinter, tkMessageBox from VisionEgg.PyroApps.UberClientGUI import client_list, AppWindow # You can add your own controllers and GUIs to client_list try: app_window = AppWindow(client_list=client_list) except Pyro.errors.ProtocolError, x: if str(x) == 'conn...
#!/usr/bin/env python import sys import Pyro import Tkinter, tkMessageBox from VisionEgg.PyroApps.UberClientGUI import client_list, AppWindow # You can add your own controllers and GUIs to client_list try: app_window = AppWindow(client_list=client_list) except Pyro.errors.PyroError, x: uber_server_error = 0 ...
Add todo to remove import of all operations/facts when loading pyinfra.
''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Trigge...
''' Welcome to pyinfra. ''' import logging # Global flag set True by `pyinfra_cli.__main__` is_cli = False # Global pyinfra logger logger = logging.getLogger('pyinfra') # Setup package level version from .version import __version__ # noqa # Trigger pseudo_* creation from . import pseudo_modules # noqa # Initia...
Fix tests in Python 3.6
from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexErro...
from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexErro...
Make sure handle all the exceptions
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import requests def check(url): try: response = requests.get( "https://isitup.org/{0}.json".format(url), headers={'User-Agent': 'https://github.com/lord63/isitup'}) except r...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import requests def check(url): try: response = requests.get( "https://isitup.org/{0}.json".format(url), headers={'User-Agent': 'https://github.com/lord63/isitup'}) except r...
Add helper function for discovering processor plugins.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. import os import imp import uuid def discover_processors(paths=None, options=None): '''Return processor plugins discovered on *paths*. If *paths* is None will try to use environment variable :env...
Support API keys on organization project list (fixes GH-1666)
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.serializers import serialize from sentry.models import Project, Team class OrganizationProjectsEndpoint(Organizati...
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationEndpoint from sentry.api.serializers import serialize from sentry.models import Project class OrganizationProjectsEndpoint(OrganizationEndp...
Add caveat about UsernamePassword already being an IUsernamePassword implementation
from axiom import attributes, item from twisted.cred import credentials class UsernamePassword(item.Item): """ A stored username and password. """ username = attributes.bytes(allowNone=False) password = attributes.bytes(allowNone=False) def instantiate(self): return credentials.Userna...
from axiom import attributes, item from twisted.cred import credentials class UsernamePassword(item.Item): """ A stored username and password. Note that although this class is an ``IUsernamePassword`` implementation, you should still use the ``instantiate`` method to get independent ``IUsernamePa...
Add check for empty tags
from .request import url class Search(object): def __init__(self, key=None, q=[], sf="created_at", sd="desc"): self._parameters = { "key": key, "q": q, "sf": sf, "sd": sd } @property def parameters(self): return self._parameters @property def url(self): return url(**...
from .request import url class Search(object): def __init__(self, key=None, q=[], sf="created_at", sd="desc"): self._parameters = { "key": key, "q": [str(tag).strip() for tag in q if tag], "sf": sf, "sd": sd } @property def parameters(self): return self._parameters @proper...
Fix latex build: make some unicode characters found in help work
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.t...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.t...
Disable sleep function when stopping
import threading import queue class Routine(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.queue = queue.Queue() self.manager = None self.no_wait = False self.is_stopping = False self.sleeper = threading.Event() def run(self): ...
import threading import queue class Routine(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.queue = queue.Queue() self.manager = None self.no_wait = False self.is_stopping = False self.sleeper = threading.Event() def run(self): ...
Make acquire_context always return some Context
"""Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry with a Placeholder to edit content""" content_placehol...
"""Placeholder model for Zinnia""" import inspect from django.template.context import Context, RequestContext from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry...
Fix - No more crash when entering an url with letter
from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', # Examples: url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>[a-zA-Z0-9-]+)/', SurveyDetail.as_view(), name='survey-detail'), url(...
from django.conf.urls import patterns, include, url from .views import IndexView, SurveyDetail, ConfirmView, SurveyCompleted urlpatterns = patterns('', url(r'^survey/$', IndexView.as_view(), name='survey-list'), url(r'^survey/(?P<id>\d+)/', SurveyDetail.as_view(), name='survey-detail'), url(r'^s...
Create the minimal class MiniMax
class Heuristic: def heuristic(self, board, color): raise NotImplementedError('Dont override this class')
class Heuristic: def heuristic(self, board, color): raise NotImplementedError('Dont override this class') class Minimax: def __init__(self, color_me, h_me, h_challenger): self.h_me = h_me self.h_challenger = h_challenger self.color_me = color_me def heuristic(self, board, color): if co...
Remove "work programme" option from quick history
from django import forms from . import widgets class HistoryDetailsForm(forms.Form): CIRCUMSTANCE_CHOICES = [ ("full_time", "Full time"), ("part_time", "Part time"), ("work_programme", "Work programme"), ("unemployed", "Unemployed"), ("sick", "Off sick"), ("trainin...
from django import forms from . import widgets class HistoryDetailsForm(forms.Form): CIRCUMSTANCE_CHOICES = [ ("full_time", "Full time"), ("part_time", "Part time"), ("unemployed", "Unemployed"), ("sick", "Off sick"), ("training", "In full time training"), ("caring...
Remove put_demographics from the permset of the background apps
""" Rules for PHAs, AccessTokens, ReqTokens """ from smart.views import * def grant(happ, permset): """ grant the permissions of an account to this permset """ def need_admin(*a,**b): return happ.admin_p permset.grant(get_first_record_tokens, None) permset.grant(get_next_record_tokens, None)...
""" Rules for PHAs, AccessTokens, ReqTokens """ from smart.views import * def grant(happ, permset): """ grant the permissions of an account to this permset """ def need_admin(*a,**b): return happ.admin_p permset.grant(get_first_record_tokens, None) permset.grant(get_next_record_tokens, None)...
Set default race and class without extra database queries
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/ind...
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/ind...
Read all images using tf itself
import time import cv2 import os import glob # path = 'by_class' path = 'test' t1 = time.time() file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]')) t2 = time.time() print('Time to list files: ', t2-t1) file_classes=[ele.split('/')[1] for ele in file_names] t3 = time.time() print('Time to list lab...
import time import os import glob import tensorflow as tf # path = 'by_class' path = 'test' t1 = time.time() file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]')) filename_queue = tf.train.string_input_producer(file_names) t2 = time.time() print('Time to list files: ', t2-t1) file_classes=[int(ele....
Remove unneeded import, fix python path and add coding
#!/usr/bin/python2.7 from Handler import Handler import urllib import urllib2 class HttpPostHandler(Handler): # Inititalize Handler with url and batch size def __init__(self, config=None): Handler.__init__(self, config) self.metrics = [] self.batch_size = int(self.config.get('batch', 100...
#!/usr/bin/env python # coding=utf-8 from Handler import Handler import urllib2 class HttpPostHandler(Handler): # Inititalize Handler with url and batch size def __init__(self, config=None): Handler.__init__(self, config) self.metrics = [] self.batch_size = int(self.config.get('batch', 1...
Allow creating and viewing stories
import datetime import json import falcon from pipeline.api import models, schemas def json_serializer(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() raise TypeError('{} is not JSON serializable'.format(type(obj))) def json_dump(data): return json.dumps(data, default=json_se...
import datetime import json import falcon from pipeline.api import models, schemas def json_serializer(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() raise TypeError('{} is not JSON serializable'.format(type(obj))) def json_dump(data): return json.dumps(data, default=json_se...
Enable spray to find sbt
import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile...
import subprocess import sys import time import os def start(args, logfile, errfile): if os.name == 'nt': subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile) else: subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=er...
Allow for initial connection lag. Helpful when waiting for an SSH proxy to connect
import datetime import redis import urlparse import beaver.transport class RedisTransport(beaver.transport.Transport): def __init__(self, file_config, beaver_config): super(RedisTransport, self).__init__(file_config, beaver_config) redis_url = beaver_config.get('redis_url') _url = urlpa...
import datetime import redis import time import urlparse import beaver.transport class RedisTransport(beaver.transport.Transport): def __init__(self, file_config, beaver_config): super(RedisTransport, self).__init__(file_config, beaver_config) redis_url = beaver_config.get('redis_url') ...
Add explicit fields in serializer
from .models import * from rest_framework import serializers class MasterWorkableSerializer(serializers.ModelSerializer): class Meta: model = MasterWorkable
from .models import * from rest_framework import serializers class MasterWorkableSerializer(serializers.ModelSerializer): class Meta: model = MasterWorkable fields = '__all__'
Change Celery RethinkDB backend config
#CELERY_RESULT_BACKEND = 'mltsp.ext.rethinkdb_backend:RethinkBackend' CELERY_RESULT_BACKEND = "amqp" #CELERY_RETHINKDB_BACKEND_SETTINGS = { # 'host': '127.0.0.1', # 'port': 28015, # 'db': 'celery_test', # 'auth_key': '', # 'timeout': 20, # 'table': 'celery_taskmeta', # 'options': {} #} CE...
#CELERY_RESULT_BACKEND = 'mltsp.ext.rethinkdb_backend:RethinkBackend' CELERY_RESULT_BACKEND = "amqp" CELERY_RETHINKDB_BACKEND_SETTINGS = { 'host': '127.0.0.1', 'port': 28015, 'db': 'celery_test', # 'auth_key': '', 'timeout': 20, 'table': 'celery_taskmeta', 'options': {} } CELERY_RESULT_SE...
Add trailing slash to forward and reverse url resolutions
# coding: utf-8 from django.utils.module_loading import import_string def _load(module): return import_string(module) if isinstance(module, str) else module class view(): def __init__(self, model, view, slug_field): self.model = _load(model) self.view = _load(view) self.slug_field = ...
# coding: utf-8 from django.utils.module_loading import import_string def _load(module): return import_string(module) if isinstance(module, str) else module class view(): def __init__(self, model, view, slug_field): self.model = _load(model) self.view = _load(view) self.slug_field = ...
Rename test class (sloppy cut n' paste job)
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest from harness import MockRouter class TestLog(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend(...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest from harness import MockRouter class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = B...