Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Delete sub folders in log directory
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import os import logging logger = logging.getLogger(__name__) def create_directory(path): """ Creates a directory if it doesn't already exist. """ # Check if path is a file_path or a dir_path. Di...
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import logging import os import shutil logger = logging.getLogger(__name__) def create_directory(path): """ Creates a directory if it doesn't already exist. """ # Check if path is a file_path or a...
Move token handling from tag function to CSSAssetTagNode
from __future__ import absolute_import from django.template import Node, Library, TemplateSyntaxError from gears.assets import build_asset from ..settings import environment, GEARS_URL, GEARS_DEBUG register = Library() class CSSAssetTagNode(Node): template = u'<link rel="stylesheet" href="%s%%s">' % GEARS_URL ...
from __future__ import absolute_import from django.template import Node, Library, TemplateSyntaxError from gears.assets import build_asset from ..settings import environment, GEARS_URL, GEARS_DEBUG register = Library() class CSSAssetTagNode(Node): template = u'<link rel="stylesheet" href="%s%%s">' % GEARS_URL ...
Change confirm delete url. /v2/nodes/{pk}/pointers was being read as /v2/nodes/{pk}/{token} and returning 'Incorrect token' instead of pointers list.
from django.conf.urls import url from api.nodes import views urlpatterns = [ # Examples: # url(r'^$', 'api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.NodeList.as_view(), name='node-list'), url(r'^(?P<pk>\w+)/$', views.NodeDetail.as_view(), name='node-detail'...
from django.conf.urls import url from api.nodes import views urlpatterns = [ # Examples: # url(r'^$', 'api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.NodeList.as_view(), name='node-list'), url(r'^(?P<pk>\w+)/$', views.NodeDetail.as_view(), name='node-detail'...
Add get_variant_url method to content node.
from .. import api_utils class ContentNode(object): def __init__(self, document, _isChildrenPopulated=False): self.document = document self._isChildrenPopulated = _isChildrenPopulated def get_url(self): return api_utils.generate_url("/api/delivery" + self.document.get("path")) def get_children(sel...
import urllib from .. import api_utils class ContentNode(object): def __init__(self, document, _isChildrenPopulated=False): self.document = document self._isChildrenPopulated = _isChildrenPopulated def get_url(self): return api_utils.generate_url("/api/delivery" + self.document.get("path")) def g...
Make sure urllib2 is installed
#!/usr/bin/env python2 from distutils.core import setup import codecs import os.path as path cwd = path.dirname(__file__) version = '0.0.0' with codecs.open(path.join(cwd, 'mlbgame/version.py'), 'r', 'ascii') as f: exec(f.read()) version = __version__ assert version != '0.0.0' setup( name='mlbgame', ...
#!/usr/bin/env python2 from distutils.core import setup import codecs import os.path as path cwd = path.dirname(__file__) version = '0.0.0' with codecs.open(path.join(cwd, 'mlbgame/version.py'), 'r', 'ascii') as f: exec(f.read()) version = __version__ assert version != '0.0.0' install_requires = [] try: ...
Add English natural language classifier
from setuptools import setup, find_packages setup( name='pysummarize', version='0.5.0', description='Simple Python and NLTK-based implementation of text summarization', url='https://github.com/despawnerer/summarize', author='Aleksei Voronov', author_email='despawn@gmail.com', license='MIT',...
from setuptools import setup, find_packages setup( name='pysummarize', version='0.5.0', description='Simple Python and NLTK-based implementation of text summarization', url='https://github.com/despawnerer/summarize', author='Aleksei Voronov', author_email='despawn@gmail.com', license='MIT',...
Deal with the compass.rb -> config.rb change
# Copyright 2013 Donald Stufft # # 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, so...
# Copyright 2013 Donald Stufft # # 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, so...
Set window size to something a little bigger.
import os from urlparse import urljoin from django.conf import settings from splinter.browser import Browser from inthe_am.taskmanager import models TEST_COUNTERS = {} def before_all(context): context.browser = Browser('phantomjs') def after_all(context): context.browser.quit() context.browser = No...
import os from urlparse import urljoin from django.conf import settings from splinter.browser import Browser from inthe_am.taskmanager import models TEST_COUNTERS = {} def before_all(context): context.browser = Browser('phantomjs') def after_all(context): context.browser.quit() context.browser = No...
Remove out_dir from the drill task's list of arguments
import redis from celery import Celery from .driller import Driller app = Celery('tasks', broker='amqp://guest@localhost//', backend='redis://localhost') redis_pool = redis.ConnectionPool(host='localhost', port=6379, db=1) @app.task def drill(binary, input, out_dir, fuzz_bitmap, qemu_dir): redis_inst = redis.Red...
import redis from celery import Celery from .driller import Driller app = Celery('tasks', broker='amqp://guest@localhost//', backend='redis://localhost') redis_pool = redis.ConnectionPool(host='localhost', port=6379, db=1) @app.task def drill(binary, input, fuzz_bitmap, qemu_dir): redis_inst = redis.Redis(connec...
Add a function to write a sequence of nodes into a file
from graph import Graph class Writer: ''' Write a graph into file. ''' def write_blossom_iv(self, graph, file_location): ''' Write a graph to a file, use the blossom IV format @type: graph: graph @param: graph: graph that should be written to file @type: file_l...
from graph import Graph class Writer: ''' Write a graph or a list of nodes into a file. ''' def write_blossom_iv(self, graph, file_location): ''' Write a graph to a file, use the blossom IV format @type: graph: graph @param: graph: graph that should be written to file ...
Raise not Found on schema item_type error.
from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): # Random processid so etags are invalidated after restart. config.registry['encoded.processid'] = randint(0, 2 ** 32) config.add_route('schema', '/profiles/{ite...
from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from random import randint from ..contentbase import ( Root, location_root, ) def includeme(config): # Random processid so etags are invalidated after restart. config.registry['encoded.processid'] = randint(0, 2 ** 32...
Add function that gets presigned url for video.
import sys import boto3 BUCKET_NAME = 'mitLookit' def get_all_study_attachments(study_uuid): s3 = boto3.resource('s3') bucket = s3.Bucket(BUCKET_NAME) return bucket.objects.filter(Prefix=f'videoStream_{study_uuid}') if __name__ == '__main__': study_uuid = sys.argv[1] get_study_keys(study_uuid)
import sys import boto3 import botocore BUCKET_NAME = 'mitLookit' def get_all_study_attachments(study_uuid): """ Get all video responses to a study by fetching all objects in the bucket with key name videoStream_<study_uuid> """ s3 = boto3.resource('s3') bucket = s3.Bucket(BUCKET_NAME) ret...
Add missing docstring on remove_punctuation
from bs4 import BeautifulSoup def html_to_text(html_text): """Receive pure html and convert to text without tags""" soup = BeautifulSoup(html_text, "html.parser") clean_html = ' '.join(soup.find_all(text=True)) return clean_html def remove_punctuation(text): translate_table = {ord(c): "" ...
from bs4 import BeautifulSoup def html_to_text(html_text): """Receive pure html and convert to text without tags""" soup = BeautifulSoup(html_text, "html.parser") clean_html = ' '.join(soup.find_all(text=True)) return clean_html def remove_punctuation(text): """Receive text and remove punctuatio...
Fix bug to make template optional
""" Mixin fragment/html behavior into XBlocks """ from __future__ import absolute_import from django.template.context import Context from xblock.fragment import Fragment class XBlockFragmentBuilderMixin(object): """ Create a default XBlock fragment builder """ def build_fragment( self, ...
""" Mixin fragment/html behavior into XBlocks """ from __future__ import absolute_import from django.template.context import Context from xblock.fragment import Fragment class XBlockFragmentBuilderMixin(object): """ Create a default XBlock fragment builder """ def build_fragment( self, ...
Rewrite unicode join test to work with py25
# -*- coding: utf-8 -*- import paver.path import sys import os.path def test_join_on_unicode_path(): merged = b'something/\xc3\xb6'.decode('utf-8') # there is ö after something if not os.path.supports_unicode_filenames and sys.version_info[0] < 3: merged = merged.encode('utf-8') assert merged == o...
# -*- coding: utf-8 -*- import paver.path import sys import os.path def test_join_on_unicode_path(): # This is why we should drop 2.5 asap :] # b'' strings are not supported in 2.5, while u'' string are not supported in 3.2 # -- even syntactically, so if will not help you here if sys.version_info[0] <...
Add a blank line in the end
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-11-30 # Python 3.4 """ 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), 使用 Python 如何生成 200 个激活码(或者优惠券)? """ import uuid def generate_key(): key_list = [] for i in range(200): uuid_key = uuid.uuid3(uui...
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-11-30 # Python 3.4 """ 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), 使用 Python 如何生成 200 个激活码(或者优惠券)? """ import uuid def generate_key(): key_list = [] for i in range(200): uuid_key = uuid.uuid3(uui...
Make default logging level ERROR
""" Angr module """ # pylint: disable=wildcard-import import logging logging.getLogger("angr").addHandler(logging.NullHandler()) from .project import * from .functionmanager import * from .variableseekr import * from .regmap import * from .path import * from .errors import * from .surveyor import * from .service impo...
""" Angr module """ # pylint: disable=wildcard-import import logging logging.getLogger("angr").addHandler(logging.NullHandler()) from .project import * from .functionmanager import * from .variableseekr import * from .regmap import * from .path import * from .errors import * from .surveyor import * from .service impo...
Add sqs to submit view
from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import DBSession, PathAndRow_Model, SceneList_Model @view_config(route_name='index', renderer='templates/index.jinja2') def index(request): '''Index page.''' lat = float(request.params...
from pyramid.response import Response from pyramid.view import view_config from sqlalchemy.exc import DBAPIError from .models import DBSession, PathAndRow_Model, SceneList_Model from sqs import * import os @view_config(route_name='index', renderer='templates/index.jinja2') def index(request): '''Index page.''' ...
Fix failing tests on py3k.
import gzip import json import unittest from opensimplex import OpenSimplex class TestOpensimplex(unittest.TestCase): def load_samples(self): for line in gzip.open("tests/samples.json.gz"): yield json.loads(line) def test_samples(self): simplex = OpenSimplex(seed=0) for s...
import gzip import json import unittest from opensimplex import OpenSimplex class TestOpensimplex(unittest.TestCase): def load_samples(self): for line in gzip.open("tests/samples.json.gz"): # Python3: need to decode the line as it's a bytes object and json # will only work on strin...
Clean up un-needed commented line after jkrzywon fixed subprocess bad behaviour
__version__ = "4.0b1" __build__ = "GIT_COMMIT" try: import logging import subprocess import os import platform FNULL = open(os.devnull, 'w') if platform.system() == "Windows": args = ['git', 'describe', '--tags'] else: args = ['git describe --tags'] git_revision = subproc...
__version__ = "4.0b1" __build__ = "GIT_COMMIT" try: import logging import subprocess import os import platform FNULL = open(os.devnull, 'w') if platform.system() == "Windows": args = ['git', 'describe', '--tags'] else: args = ['git describe --tags'] git_revision = subproc...
Make it so that source_counts is only executed on purpose
from sharepa.search import ShareSearch, basic_search # noqa from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
from sharepa.search import ShareSearch, basic_search # noqa from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa def source_counts(): return bucket_to_dataframe( 'total_source_counts', basic_search.execute().aggregations.sourceAgg.buckets )
Make +s actually definitely clear the cdata dictionary
from txircd.modbase import Mode class SecretMode(Mode): def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: data["cdata"] = {} # other +s stuff is hiding in other modules. cla...
from txircd.modbase import Mode class SecretMode(Mode): def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: data["cdata"].clear() # other +s stuff is hiding in other modules. ...
Add functools wraps to report_time decorator
import time # for development/debugging def report_time(f): def wrap(*args, **kwargs): t = time.time() r = f(*args, **kwargs) print '%s.%s: %.4f' % (f.__module__, f.func_name, time.time()-t) return r return wrap
from functools import wraps import time # for development/debugging def report_time(f): @wraps(f) def wrap(*args, **kwargs): t = time.time() r = f(*args, **kwargs) print '%s.%s: %.4f' % (f.__module__, f.func_name, time.time()-t) return r return wrap
Move requirements read code info function
from setuptools import setup, find_packages # Dynamically calculate the version version = __import__('device_inventory').get_version() # Collect installation requirements with open('requirements.txt') as reqf: import re dep_re = re.compile(r'^([^\s#]+)') inst_reqs = [m.group(0) for m in ...
import re from setuptools import setup, find_packages # Dynamically calculate the version version = __import__('device_inventory').get_version() # Collect installation requirements def read_requirements(path): with open(path) as reqf: dep_re = re.compile(r'^([^\s#]+)') return [m.group(0) for m i...
Bump to 0.0.2a for attr. graph feature
from setuptools import setup import os setup( name = "merky", version = "0.0.1a", author = "Ethan Rowe", author_email = "ethan@the-rowes.com", description = ("JSON-oriented merkle tree utilities"), license = "MIT", url = "https://github.com/ethanrowe/python-merky", packages = ["merky", ...
from setuptools import setup import os setup( name = "merky", version = "0.0.2a", author = "Ethan Rowe", author_email = "ethan@the-rowes.com", description = ("JSON-oriented merkle tree utilities"), license = "MIT", url = "https://github.com/ethanrowe/python-merky", packages = ["merky", ...
Change path to kafka-patch-review source
import codecs import os from setuptools import setup, find_packages HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open, See: # https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690 return codecs.open(os.path.join(HER...
import codecs import os from setuptools import setup, find_packages HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open, See: # https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690 return codecs.open(os.path.join(HER...
Add python 3 dependency, bump minor
from setuptools import setup setup(name = 'graphysio', version = '0.6', description = 'Graphical visualization of physiologic time series', url = 'https://github.com/jaj42/graphysio', author = 'Jona JOACHIM', author_email = 'jona@joachim.cc', license = 'ISC', install_requires ...
from setuptools import setup setup(name = 'graphysio', version = '0.61', description = 'Graphical visualization of physiologic time series', url = 'https://github.com/jaj42/graphysio', author = 'Jona JOACHIM', author_email = 'jona@joachim.cc', license = 'ISC', python_requires ...
Bump version number for release
from setuptools import setup with open("README.rst") as f: readme = f.read() setup( name="rply", description="A pure Python Lex/Yacc that works with RPython", long_description=readme, version="0.7.1", author="Alex Gaynor", author_email="alex.gaynor@gmail.com", packages=["rply"], )
from setuptools import setup with open("README.rst") as f: readme = f.read() setup( name="rply", description="A pure Python Lex/Yacc that works with RPython", long_description=readme, version="0.7.2", author="Alex Gaynor", author_email="alex.gaynor@gmail.com", packages=["rply"], )
Remove collecting plugins every second
import os import telegram from leonard import Leonard if __name__ == '__main__': os.chdir('../') telegram_client = telegram.Bot(os.environ['BOT_TOKEN']) bot = Leonard(telegram_client) i = 0 while True: if i % 10 == 0: bot.collect_plugins() for name, check, send in bot....
import os import time import telegram from leonard import Leonard if __name__ == '__main__': os.chdir('../') telegram_client = telegram.Bot(os.environ['BOT_TOKEN']) bot = Leonard(telegram_client) bot.collect_plugins() while True: for name, check, send in bot.subscriptions: sen...
Create dir before data downloading
import bz2 import urllib.request OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 def download_and_unbzip(url, dest_file): source = urllib.request.urlopen(url) decompressor ...
import bz2 import urllib.request import os import os.path DATA_DIR = 'data' OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2' OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml' CHUNK = 16 * 1024 def download_and_unbzip(url, dest_file): source = ...
Update the tests for query_pricing
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 <> # # Distributed under terms of the MIT license. # Python modules from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 <> # # Distributed under terms of the MIT license. # Python modules from __future__ import unicode_literals # Third-party modules import pytest # Project modules from fnapy.exceptions import FnapyPricingError from tests import make...
Apply revert to the draft page.
# -*- coding: utf-8 -*- from cms.management.commands.subcommands.base import SubcommandsCommand from cms.models import CMSPlugin from cms.models.pagemodel import Page from django.core.management.base import NoArgsCommand class ModeratorOnCommand(NoArgsCommand): help = 'Turn moderation on, run AFTER upgrading to 2...
# -*- coding: utf-8 -*- from cms.management.commands.subcommands.base import SubcommandsCommand from cms.models import CMSPlugin from cms.models.pagemodel import Page from django.core.management.base import NoArgsCommand class ModeratorOnCommand(NoArgsCommand): help = 'Turn moderation on, run AFTER upgrading to 2...
Remove image name dependency on object ID
import os from django.db import models # ------------------------------------------------------------------------------ # General utilities # ------------------------------------------------------------------------------ def image_filename(instance, filename): """ Make S3 image filenames """ return 'ima...
import os import uuid from django.db import models # ------------------------------------------------------------------------------ # General utilities # ------------------------------------------------------------------------------ def image_filename(instance, filename): """ Make image filenames """ re...
Add recv_keys and add_repo to apt
import os from subprocess import call from functools import partial #TODO: stop using sudo or ensure it exists #TODOE: specify user to run as #TODO: utilize functools partial to handle some of the above functionality class Config: APT_GET = ['sudo', '-E', 'apt-get'] ENV = os.environ.copy() ENV['DEBIAN_FRO...
import os from subprocess import call from functools import partial #TODO: stop using sudo or ensure it exists #TODOE: specify user to run as #TODO: utilize functools partial to handle some of the above functionality class Config: APT_GET = ['sudo', '-E', 'apt-get'] ENV = os.environ.copy() ENV['DEBIAN_FRO...
Add /api endpoint and basic HTML
from flask import Flask application = Flask(__name__) @application.route('/') def hello_world(): return 'Hello, World!' if __name__ == "__main__": application.debug = True application.run()
from flask import Flask application = Flask(__name__) @application.route('/') def hello_world(): return 'Please use /api to use the DataNorth API.' @application.route('/api') def api_intro(): intro = \ """ <h2> Welcome to the DataNorth API! </h2> <h4> The following endpoints are available: </h...
Fix java VM starting when there is not classpath set
"""Handles all imports from jnius to prevent conflicts resulting from attempts to set JVM options while the VM is already running.""" import os import warnings import jnius_config if '-Xmx4g' not in jnius_config.get_options(): if not jnius_config.vm_running: jnius_config.add_options('-Xmx4g') else: ...
"""Handles all imports from jnius to prevent conflicts resulting from attempts to set JVM options while the VM is already running.""" import os import warnings import jnius_config if '-Xmx4g' not in jnius_config.get_options(): if not jnius_config.vm_running: jnius_config.add_options('-Xmx4g') else: ...
Raise exception if faulty definition of classes inserted
# -*- coding: utf-8 -*- """common.py Contains basic functions that are shared thoughout the module """ def compute_totals(distribution, classes): "Compute the number of individuals per class, per unit and in total" N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution} N_class...
# -*- coding: utf-8 -*- """common.py Contains basic functions that are shared throughout the module """ def compute_totals(distribution, classes): "Compute the number of individuals per class, per unit and in total" N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution} N_clas...
Stop grabbing password when there is no username
"""Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username password = os.getenv("OSF_PA...
"""Command line interface to the OSF""" import os from .api import OSF CHUNK_SIZE = int(5e6) def _setup_osf(args): # command line argument overrides environment variable username = os.getenv("OSF_USERNAME") if args.username is not None: username = args.username password = None if usern...
Use our own code, when possible.
from django.shortcuts import get_object_or_404 from django.utils.decorators import available_attrs from django.utils.http import urlquote from django.http import HttpResponse from django.template import loader, RequestContext from functools import wraps def singleton(cls): instances = {} def getinstance(): ...
from django.shortcuts import get_object_or_404 from django.utils.decorators import available_attrs from comrade.views.simple import direct_to_template from functools import wraps def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() ...
Add more details to py35 EoL changes
import os import sys from contextlib import contextmanager def is_buffer(obj, mode): return ("r" in mode and hasattr(obj, "read")) or ( "w" in mode and hasattr(obj, "write") ) @contextmanager def open_file(path_or_buf, mode="r"): if is_buffer(path_or_buf, mode): yield path_or_buf eli...
import os import sys from contextlib import contextmanager def is_buffer(obj, mode): return ("r" in mode and hasattr(obj, "read")) or ( "w" in mode and hasattr(obj, "write") ) @contextmanager def open_file(path_or_buf, mode="r"): if is_buffer(path_or_buf, mode): yield path_or_buf eli...
Use the file's storage to determine whether the file exists or not. The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage
from posixpath import exists from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ from filer.fields.file import FilerFileField from cmsplugin_filer_utils import FilerPluginManager class FilerFile(CMSPlugin): """ Plugin for storing any type of ...
from cms.models import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as _ from filer.fields.file import FilerFileField from cmsplugin_filer_utils import FilerPluginManager class FilerFile(CMSPlugin): """ Plugin for storing any type of file. Default template di...
Add an explanation of how to set up a namespace package
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
""" The PyBIDS extension namespace package ``bids.ext`` is reserved as a namespace for extensions to install into. To write such an extension, the following things are needed: 1) Create a new package with the following structure (assuming setuptools):: package/ bids/ ext/ __init__.py ...
Add a run method for the entry point
import sys from labonneboite.importer import util as import_util from labonneboite.importer import settings if __name__ == "__main__": filename = import_util.detect_runnable_file("etablissements") if filename: with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f: f.write("LBB_ETAB...
import sys from labonneboite.importer import util as import_util from labonneboite.importer import settings def run(): filename = import_util.detect_runnable_file("etablissements") if filename: with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f: f.write("LBB_ETABLISSEMENT_INPUT_...
Make YAML handler safe by default
# -*- coding: utf8 -*- """ kaptan.handlers.yaml_handler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by the authors and contributors (See AUTHORS file). :license: BSD, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import yaml from . import BaseHandler...
# -*- coding: utf8 -*- """ kaptan.handlers.yaml_handler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by the authors and contributors (See AUTHORS file). :license: BSD, see LICENSE for more details. """ from __future__ import print_function, unicode_literals import yaml from . import BaseHandler...
Remove unused code + follow only specific user status
import time import os from tweepy import API from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener from credentials import * class listener(StreamListener): def __init__(self, api, start_time, time_limit=60): self.time = start_time self.limit = time...
from time import ctime from tweepy import API from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener from credentials import * from tweepy.utils import import_simplejson json = import_simplejson() class listener(StreamListener): def __init__(self, api, followed_user...
Send more print message to sys.stderr
# -*- coding: utf-8 -*- from __future__ import absolute_import import os try: print "Trying import local.py settings..." from .local import * except ImportError: print "Trying import development.py settings..." from .development import *
# -*- coding: utf-8 -*- from __future__ import ( absolute_import, print_function ) import os, sys try: print("Trying import local.py settings...", file=sys.stderr) from .local import * except ImportError: print("Trying import development.py settings...", file=sys.stderr) from .development impor...
Move the APIKey bits out to the init
from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = L...
from pupa.scrape import Legislator from .base import OpenstatesBaseScraper class OpenstatesPersonScraper(OpenstatesBaseScraper): def scrape_legislator(self, legislator_id): old = self.api('legislators/' + legislator_id + '?') old.pop('country', None) old.pop('level', None) new = L...
Remove `error_stream`; Add `on_stderr` to make it works
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an ...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Edwards # Copyright (c) 2015 Ben Edwards # # License: MIT # """This module exports the PugLint plugin class.""" from SublimeLinter.lint import NodeLinter, WARNING class PugLint(NodeLinter): """Provides an ...
Document the reason msvc requires SSE2 on 32 bit platforms.
import os import distutils.msvccompiler from distutils.msvccompiler import * from .system_info import platform_bits class MSVCCompiler(distutils.msvccompiler.MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): distutils.msvccompiler.MSVCCompiler.__init__(self, verbose, dry_run, force) ...
import os import distutils.msvccompiler from distutils.msvccompiler import * from .system_info import platform_bits class MSVCCompiler(distutils.msvccompiler.MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): distutils.msvccompiler.MSVCCompiler.__init__(self, verbose, dry_run, force) ...
Remove old way of sorting
from app.notify_client import NotifyAdminAPIClient, cache class EmailBrandingClient(NotifyAdminAPIClient): @cache.set("email_branding-{branding_id}") def get_email_branding(self, branding_id): return self.get(url="/email-branding/{}".format(branding_id)) @cache.set("email_branding") def get_a...
from app.notify_client import NotifyAdminAPIClient, cache class EmailBrandingClient(NotifyAdminAPIClient): @cache.set("email_branding-{branding_id}") def get_email_branding(self, branding_id): return self.get(url="/email-branding/{}".format(branding_id)) @cache.set("email_branding") def get_a...
Set default encoding to utf-8
import os from utils import Reader import code if __name__ == '__main__': working_directory = os.getcwd() files = Reader.read_directory(working_directory) print '{} available data files'.format(len(files)) code.interact(local=dict(globals(), **locals()))
import os from utils import Reader import code import sys if __name__ == '__main__': # coding=utf-8 reload(sys) sys.setdefaultencoding('utf-8') working_directory = os.getcwd() files = Reader.read_directory(working_directory) print '{} available data files'.format(len(files)) code.interact(...
Revert "This should break the flakes8 check on Travis"
import random, datetime from hamper.interfaces import ChatCommandPlugin, Command class Roulette(ChatCommandPlugin): """Feeling lucky? !roulette to see how lucky""" name = 'roulette' priority = 0 class Roulette(Command): '''Try not to die''' regex = r'^roulette$' name = 'ro...
import random from hamper.interfaces import ChatCommandPlugin, Command class Roulette(ChatCommandPlugin): """Feeling lucky? !roulette to see how lucky""" name = 'roulette' priority = 0 class Roulette(Command): '''Try not to die''' regex = r'^roulette$' name = 'roulette' ...
Add a clip to the frameless example
""" =============================== Plotting a Map without any Axes =============================== This examples shows you how to plot a Map without any annotations at all, i.e. to save as an image. """ ############################################################################## # Start by importing the necessary m...
""" =============================== Plotting a Map without any Axes =============================== This examples shows you how to plot a Map without any annotations at all, i.e. to save as an image. """ ############################################################################## # Start by importing the necessary m...
Add audience field to Document resource
from __future__ import unicode_literals from ..base import Resource class Document(Resource): _resource_name = 'documents' _is_listable = False _as_is_fields = ['id', 'href', 'mime_type', 'content', 'type'] _date_time_fields_utc = ['date_created'] _resource_fields = [ ('booking', 'Bookin...
from __future__ import unicode_literals from ..base import Resource class Document(Resource): _resource_name = 'documents' _is_listable = False _as_is_fields = ['id', 'href', 'mime_type', 'content', 'type', 'audience'] _date_time_fields_utc = ['date_created'] _resource_fields = [ ('booki...
Use more specific PyJWT version pin
# This file is part of the Indico plugins. # Copyright (C) 2020 CERN and ENEA # # The Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; # see the LICENSE file for more details. from __future__ import unicode_literals from setuptools import setup # X...
# This file is part of the Indico plugins. # Copyright (C) 2020 CERN and ENEA # # The Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; # see the LICENSE file for more details. from __future__ import unicode_literals from setuptools import setup # X...
Fix PermsError.suppress() doing the exact opposite...
class PermsError: val = False @classmethod def suppress(cls): cls.val = True def __bool__(self): return self.val
class PermsError: val = True @classmethod def suppress(cls): cls.val = False def __bool__(self): return self.val
Increase SG last sync for more overlap
import graphene import arrow from django.db.models import Q from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.F...
import graphene import arrow from django.db.models import Q from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Fi...
Check N-D with N>2 raises in utils
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), (ValueError, np.zeros((1, 2,), dtype=bool), np.zer...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import pytest import numpy as np import dask_distance._utils @pytest.mark.parametrize("et, u, v", [ (ValueError, np.zeros((2,), dtype=bool), np.zeros((3,), dtype=bool)), (ValueError, np.zeros((1, 2, 1,), dtype=bool), np....
Fix kwargs usage to work with other auth backends.
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.db.models import Q from django.utils.http import base36_to_int class MezzanineBackend(ModelBackend): """ Extends Django's ``ModelBackend...
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from django.contrib.auth.tokens import default_token_generator from django.db.models import Q from django.utils.http import base36_to_int class MezzanineBackend(ModelBackend): """ Extends Django's ``ModelBackend...
Swap db and rds set up
#!/usr/bin/env python # a script to delete an rds instance # import the sys and boto3 libraries import sys import boto3 # create an rds client rds = boto3.client('rds') # use the first argument to the script as the name # of the instance to be deleted db = sys.argv[1] try: # delete the instance and catch the re...
#!/usr/bin/env python # a script to delete an rds instance # import the sys and boto3 libraries import sys import boto3 # use the first argument to the script as the name # of the instance to be deleted db = sys.argv[1] # create an rds client rds = boto3.client('rds') try: # delete the instance and catch the re...
Fix plugin not taking into account opening of unsaved buffers and some refactoring
import sublime_plugin from editorconfig import get_properties, EditorConfigError LINE_ENDINGS = { 'lf': 'Unix', 'crlf': 'Windows', 'cr': 'CR' } class EditorConfig(sublime_plugin.EventListener): def on_load(self, view): try: config = get_properties(view.file_name()) except EditorConfigError: print 'Err...
import sublime_plugin from editorconfig import get_properties, EditorConfigError LINE_ENDINGS = { 'lf': 'Unix', 'crlf': 'Windows', 'cr': 'CR' } class EditorConfig(sublime_plugin.EventListener): def on_load(self, view): path = view.file_name() if not path: return try: config = get_properties(path) ...
Fix test failures on py3.
# vim: set ts=4 sw=4 et: coding=UTF-8 import string from rpmsection import Section class RpmInstall(Section): ''' Remove commands that wipe out the build root. Replace %makeinstall (suse-ism). ''' def add(self, line): install_command = 'make DESTDIR=%{buildroot} install %{?_smp_...
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmInstall(Section): ''' Remove commands that wipe out the build root. Replace %makeinstall (suse-ism). ''' def add(self, line): install_command = 'make DESTDIR=%{buildroot} install %{?_smp_mflags}' ...
Add ability to set test ini via env variable
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our t...
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() # we need to pull the right ini for the test we want to run # by default pullup test.ini, but we might want to test mysql, pgsql, etc test_ini = os.en...
Work around `AttributeError: 'module' object has no attribute 'BufferedIOBase'` on Python 2.7+, Windows
"""Image Processing SciKit (Toolbox for SciPy)""" import os.path as _osp data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data')) from version import version as __version__ def _setup_test(): import functools basedir = _osp.dirname(_osp.join(__file__, '../')) args = ['', '--exe', '-w', '%s' ...
"""Image Processing SciKit (Toolbox for SciPy)""" import os.path as _osp data_dir = _osp.abspath(_osp.join(_osp.dirname(__file__), 'data')) from version import version as __version__ def _setup_test(): import gzip import functools basedir = _osp.dirname(_osp.join(__file__, '../')) args = ['', '--e...
Set Bambou package version to 0.0.2
from setuptools import setup setup( name='bambou', version='0.0.1', url='http://www.nuagenetworks.net/', author='Christophe Serafin', author_email='christophe.serafin@alcatel-lucent.com', packages=['bambou', 'bambou.utils'], description='REST Library for Nuage Networks', long_descripti...
from setuptools import setup setup( name='bambou', version='0.0.2', url='http://www.nuagenetworks.net/', author='Christophe Serafin', author_email='christophe.serafin@alcatel-lucent.com', packages=['bambou', 'bambou.utils'], description='REST Library for Nuage Networks', long_descripti...
Use pypandoc to convert README.md to RST for long_description
from setuptools import setup, find_packages setup( name='rq-retry-scheduler', version='0.1.0b1', url='https://github.com/mikemill/rq_retry_scheduler', description='RQ Retry and Scheduler', long_description=open('README.rst').read(), author='Michael Miller', author_email='mikemill@gmail.com...
from setuptools import setup, find_packages try: import pypandoc def long_description(): return pypandoc.convert_file('README.md', 'rst') except ImportError: def long_description(): return '' setup( name='rq-retry-scheduler', version='0.1.0b1', url='https://github.com/mikemi...
Rename pypi package and change author
from setuptools import setup, find_packages from plotbitrate import __version__ with open("README.md", "r") as fh: long_description = fh.read() setup( name='rezun-plotbitrate', version=__version__, packages=find_packages(), description='A simple bitrate plotter for media files', long_descr...
from setuptools import setup, find_packages from plotbitrate import __version__ with open("README.md", "r") as fh: long_description = fh.read() setup( name='plotbitrate', version=__version__, packages=find_packages(), description='A simple bitrate plotter for media files', long_description...
Fix bug in unit test
#!/usr/bin/env python #------------------------------------------------------------------------ # Copyright (c) 2015 SGW # # Distributed under the terms of the New BSD License. # # The full License is in the file LICENSE #------------------------------------------------------------------------ import unittest import ...
#!/usr/bin/env python #------------------------------------------------------------------------ # Copyright (c) 2015 SGW # # Distributed under the terms of the New BSD License. # # The full License is in the file LICENSE #------------------------------------------------------------------------ import unittest import ...
Write access to new output file
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): ...
import os import sys import re import subprocess def lemmatize( text ): text = text.encode('utf8') text = re.sub( '[\.,?!:;]' , '' , text ) out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True) lemma = '' for line in out.split('\n'): ...
Update database backends analyzer to target 1.5
import ast from .base import BaseAnalyzer, Result class DB_BackendsVisitor(ast.NodeVisitor): def __init__(self): self.found = [] deprecated_items = { 'django.db.backends.postgresql': 'django.db.backends.postgresql_psycopg2', } def visit_Str(self, node): if node...
import ast from .base import BaseAnalyzer, Result class DB_BackendsVisitor(ast.NodeVisitor): def __init__(self): self.found = [] removed_items = { 'django.db.backends.postgresql': 'django.db.backends.postgresql_psycopg2', } def visit_Str(self, node): if node.s ...
Fix reference to wall factory
from django.contrib.auth import get_user_model from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, PostGeneration, SubFactory from yunity.base.factories import Wall from yunity.utils.tests.fake import faker class User(DjangoModelFactory): class Meta: model = get_user_model() s...
from django.contrib.auth import get_user_model from factory import DjangoModelFactory, CREATE_STRATEGY, LazyAttribute, PostGeneration, SubFactory from yunity.walls.factories import Wall from yunity.utils.tests.fake import faker class User(DjangoModelFactory): class Meta: model = get_user_model() ...
Add timeout to downloading custom background images
import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, UnicodeError, ...
import asyncio import aiofiles import aiohttp import aiohttp.client_exceptions from aiopath import AsyncPath from sanic.log import logger EXCEPTIONS = ( aiohttp.client_exceptions.ClientConnectionError, aiohttp.client_exceptions.InvalidURL, aiohttp.client_exceptions.TooManyRedirects, AssertionError, ...
Update User class to match Telegram API
from collections import namedtuple class User: def __init__(self, id_, first_name, last_name='', username=''): self.id = id_ self.first_name = first_name self.last_name = last_name self.username = username @classmethod def from_database(cls, user): return cls(*user...
from collections import namedtuple class User: def __init__(self, id_, first_name, last_name='', username='', language_code=''): self.id = id_ self.first_name = first_name self.last_name = last_name self.username = username @classmethod def from_database(cls, u...
Consolidate some behavior and re-use 'set' comparison for less strict unordered comparisons.
import unittest import importlib_resources as resources from . import data01 from . import util class ContentsTests: @property def contents(self): return sorted( [el for el in list(resources.contents(self.data)) if el != '__pycache__'] ) class ContentsDiskTests(ContentsTests, un...
import unittest import importlib_resources as resources from . import data01 from . import util class ContentsTests: expected = { '__init__.py', 'binary.file', 'subdirectory', 'utf-16.file', 'utf-8.file', } def test_contents(self): assert self.expected <= ...
Fix pep8 in init file
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Albert SHENOUDA <albert.shenouda@efrei.net> # # The licence is in the fi...
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Albert SHENOUDA <albert.shenouda@efrei.net> # # The licence is in the fi...
Switch off the output file generation.
#!/usr/bin/env python3 # coding: utf-8 """ ================================================ Optimization Benchmark: Plot the Sphere Function ================================================ This example show how to plot the *Sphere function*. """ ######################################################################...
#!/usr/bin/env python3 # coding: utf-8 """ ================================================ Optimization Benchmark: Plot the Sphere Function ================================================ This example show how to plot the *Sphere function*. """ ######################################################################...
Enable logstash formatter for console logs
from cla_public.config.common import * DEBUG = os.environ.get('SET_DEBUG', False) == 'True' SECRET_KEY = os.environ['SECRET_KEY'] SESSION_COOKIE_SECURE = os.environ.get('CLA_ENV', '') in ['prod', 'staging'] HOST_NAME = os.environ.get('HOST_NAME') or os.environ.get('HOSTNAME') BACKEND_BASE_URI = os.environ['BACKEN...
from cla_public.config.common import * DEBUG = os.environ.get('SET_DEBUG', False) == 'True' SECRET_KEY = os.environ['SECRET_KEY'] SESSION_COOKIE_SECURE = os.environ.get('CLA_ENV', '') in ['prod', 'staging'] HOST_NAME = os.environ.get('HOST_NAME') or os.environ.get('HOSTNAME') BACKEND_BASE_URI = os.environ['BACKEN...
Fix conversion of PNG "palette" or "P" mode images to JPEG. "P" mode images need to be converted to 'RGB' if target image format is not PNG or GIF.
import tempfile import types from django.utils.functional import wraps from imagekit.lib import Image def img_to_fobj(img, format, **kwargs): tmp = tempfile.TemporaryFile() # Preserve transparency if the image is in Pallette (P) mode. if img.mode == 'P': kwargs['transparency'] = len(img.split()...
import tempfile import types from django.utils.functional import wraps from imagekit.lib import Image def img_to_fobj(img, format, **kwargs): tmp = tempfile.TemporaryFile() # Preserve transparency if the image is in Pallette (P) mode. transparency_formats = ('PNG', 'GIF', ) if img.mode == 'P' and f...
Test correct encoding for trivia answer
import unittest from units.trivia import check_answer class TestCheckAnswer(unittest.TestCase): def test_correct_answer(self): self.assertTrue(check_answer("correct", "correct")) def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) def test_large_num...
import unittest from units.trivia import check_answer class TestCheckAnswer(unittest.TestCase): def test_correct_answer(self): self.assertTrue(check_answer("correct", "correct")) def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) def test_correct_e...
Add new variable to cache blacklist
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop. # The following variables are intermadiate results and do not need to be cached in those usecases. cache_blacklist = set([ 'aide_logement_loyer_retenu', 'aide_logement_charges', 'aide_logemen...
# When using openfisca for a large population, having too many variables in cache make openfisca performances drop. # The following variables are intermediate results and do not need to be cached in those usecases. cache_blacklist = set([ 'aide_logement_loyer_retenu', 'aide_logement_charges', 'aide_logemen...
Fix bug with document merger
from ofxclient.client import Client from StringIO import StringIO def combined_download(accounts, days=60): """Download OFX files and combine them into one It expects an 'accounts' list of ofxclient.Account objects as well as an optional 'days' specifier which defaults to 60 """ client = Client(...
from ofxclient.client import Client from StringIO import StringIO def combined_download(accounts, days=60): """Download OFX files and combine them into one It expects an 'accounts' list of ofxclient.Account objects as well as an optional 'days' specifier which defaults to 60 """ client = Client(...
Update Flame Leviathan to use draw script
from ..utils import * ## # Minions # Snowchugger class GVG_002: events = Damage().on( lambda self, target, amount, source: source is self and Freeze(target) ) # Goblin Blastmage class GVG_004: play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4 # Flame Leviathan class GVG_007: in_hand...
from ..utils import * ## # Minions # Snowchugger class GVG_002: events = Damage().on( lambda self, target, amount, source: source is self and Freeze(target) ) # Goblin Blastmage class GVG_004: play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4 # Flame Leviathan class GVG_007: draw = ...
Undo premature fix for dependency
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Google OpenID auth has been turned off, so any associations that users had to their Google accounts via Google OpenID are now useless. Just remove them. """ from django.db import migrations def no_op(apps, schema_editor): pass def remove_old_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Google OpenID auth has been turned off, so any associations that users had to their Google accounts via Google OpenID are now useless. Just remove them. """ from django.db import migrations def no_op(apps, schema_editor): pass def remove_old_...
Handle when an OpenSSL error doesn't contain a reason
from six import PY3, binary_type, text_type from cryptography.hazmat.bindings.openssl.binding import Binding binding = Binding() ffi = binding.ffi lib = binding.lib def exception_from_error_queue(exceptionType): def text(charp): return native(ffi.string(charp)) errors = [] while True: err...
from six import PY3, binary_type, text_type from cryptography.hazmat.bindings.openssl.binding import Binding binding = Binding() ffi = binding.ffi lib = binding.lib def exception_from_error_queue(exceptionType): def text(charp): if not charp: return "" return native(ffi.string(charp)) ...
Use SiteFeed to get a category listing
# encoding: utf-8 """ List categories and their IDs in a Discourse forum. """ import os from argparse import ArgumentParser from urllib.parse import urljoin import requests def main(): args = parse_args() params = {} if args.key is not None: params['api_key'] = args.key if args.user is not N...
# encoding: utf-8 """ List categories and their IDs in a Discourse forum. """ import os from argparse import ArgumentParser from community_mailbot.discourse import SiteFeed def main(): args = parse_args() site_feed = SiteFeed(args.url, user=args.user, key=args.key) for c_id, name in site_feed.category_n...
Implement NotNonterminalEception __init__ method and pass object
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from .GrammpyException import GrammpyException class NotNonterminalException(GrammpyException): pass
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from typing import Any from .GrammpyException import GrammpyException class NotNonterminalException(GrammpyException): def __init__(self, parameter, *args: Any) -> None: super()....
Add exception for empty db search return
""" Errors generated by this module """ class ConfigException(Exception): pass class FillValueException(Exception): """ All of a tile is "fill" values """ pass
""" Errors generated by this module """ class ConfigException(Exception): pass class FillValueException(Exception): """ All of a tile is "fill" values """ pass class ProductNotFoundException(Exception): pass
Swap hitzer inverse test to use np.testing
import numpy as np import pytest import clifford as cf class TestClosedForm: @pytest.mark.parametrize('p, q', [ (p, total_dims - p) for total_dims in [1, 2, 3, 4, 5] for p in range(total_dims + 1) ]) def test_hitzer_inverse(self, p, q): Ntests = 100 layout, blades...
import numpy as np import pytest import clifford as cf class TestClosedForm: @pytest.mark.parametrize('p, q', [ (p, total_dims - p) for total_dims in [1, 2, 3, 4, 5] for p in range(total_dims + 1) ]) def test_hitzer_inverse(self, p, q): Ntests = 100 layout, blades...
Add a random <Route> to a generated <Client>
# coding=utf-8 import factory import datetime import random from django.contrib.auth.models import User from member.models import Member, Address, Contact, Client, PAYMENT_TYPE from member.models import DELIVERY_TYPE, GENDER_CHOICES class AddressFactory (factory.DjangoModelFactory): class Meta: model = A...
# coding=utf-8 import factory import datetime import random from django.contrib.auth.models import User from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route from member.models import DELIVERY_TYPE, GENDER_CHOICES class AddressFactory (factory.DjangoModelFactory): class Meta: mo...
Change the default __getattr_ value
class Card: """ A wrapper around a Scryfall json card object. """ def __init__(self, cardData): self._data = cardData def __getattr__(self, attr): """ A hack that makes all attributes inaccessible, and instead returns the stored json values """ if at...
class Card: """ A wrapper around a Scryfall json card object. """ def __init__(self, cardData): self._data = cardData def __getattr__(self, attr): """ A hack that makes all attributes inaccessible, and instead returns the stored json values """ if at...
Make Django to find the pydoc-tool.py script tests
import unittest from django.test import TestCase class AccessTests(TestCase): """ Simple tests that check that basic pages can be accessed and they contain something sensible. """ def test_docstring_index(self): response = self.client.get('/docs/') self.failUnless('All docstri...
import unittest from django.test import TestCase class AccessTests(TestCase): """ Simple tests that check that basic pages can be accessed and they contain something sensible. """ def test_docstring_index(self): response = self.client.get('/docs/') self.failUnless('All docstri...
Switch chromium.linux slaves to buildbot 0.8.
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" import socket class ChromiumLinux(object): project_name = 'Chromium Linux' master_port = 8087 slave_port = 8187 ...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ActiveMaster definition.""" import socket class ChromiumLinux(object): project_name = 'Chromium Linux' master_port = 8087 slave_port = 8187 ...
Use 8 characters for email address rather than 10.
from google.appengine.ext import db import random import string def make_address(): """ Returns a random alphanumeric string of 10 digits. Since there are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1' for readability), this gives: 57 ** 10 = 3.62033331 x 10 ** 17 possible result...
from google.appengine.ext import db import random import string def make_address(): """ Returns a random alphanumeric string of 8 digits. Since there are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1' for readability), this gives: 57 ** 8 = 1.11429157 x 10 ** 14 possible results....
Fix dangling default in kwargs 'shell_cmd'
import sublime, sublime_plugin import os def wrapped_exec(self, *args, **kwargs): settings = sublime.load_settings("SublimeExterminal.sublime-settings") if settings.get('enabled') and kwargs.get('use_exterminal', True): wrapper = settings.get('exec_wrapper') try: she...
import sublime, sublime_plugin import os def wrapped_exec(self, *args, **kwargs): settings = sublime.load_settings("SublimeExterminal.sublime-settings") if settings.get('enabled') and kwargs.get('use_exterminal', True): wrapper = settings.get('exec_wrapper') try: she...
Read in some environment variables
from transporter import create_app application = create_app(__name__) if __name__ == '__main__': application.run(host='0.0.0.0', debug=True)
import os from transporter import create_app application = create_app(__name__) if __name__ == '__main__': host = os.environ.get('HOST', '0.0.0.0') port = int(os.environ.get('PORT', 8002)) debug = bool(os.environ.get('DEBUG', False)) application.run(host, port=port, debug=debug)
Add version for removing image
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(ve...
#!/usr/bin/env python from collections import defaultdict import subprocess import os KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4) def find_obsolete_images(images): for image_name, versions in images.items(): if len(versions) > KEEP_LAST_VERSIONS: obsolete_versions = sorted(ve...
Test for incorrect serialisation of PacketLocation
import json from nose.tools import assert_equal from encryptit.openpgp_message import PacketLocation from encryptit.dump_json import OpenPGPJsonEncoder PACKET_LOCATION = PacketLocation( header_start=10, body_start=12, body_length=8) def test_packet_location_header_length_field(): assert_equal(2, PA...
import json from nose.tools import assert_equal from encryptit.openpgp_message import PacketLocation from encryptit.dump_json import OpenPGPJsonEncoder PACKET_LOCATION = PacketLocation( header_start=10, body_start=12, body_length=8) def test_packet_location_header_length_field(): assert_equal(2, PA...
Make BGZF test a real unittest
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" ) print f.read( 10 ) print f.seek( 0 ) print f.read( 10 ) test_bgzf()
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" ) assert f.read( 10 ) == "begin 644 " print f.seek( 0 ) assert f.read( 10 ) == "begin 644 "
Fix lint in example script
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.AZURE_ARM) driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.AZURE_ARM) driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
Update test_package version number to match the package
from conans import ConanFile, CMake import os class MyTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "OpenCV/3.2.0-1@ohhi/stable" generators = "cmake", "txt" def imports(self): self.copy("*.dll", dst="bin", src="bin") def build(self): cmake = ...
from conans import ConanFile, CMake import os class MyTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "OpenCV/3.2.0-2@ohhi/stable" generators = "cmake", "txt" def imports(self): self.copy("*.dll", dst="bin", src="bin") def build(self): cmake = ...