Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add a script to call for allocation result externally
#!/usr/bin/env python from django import setup setup() from service.monitoring import get_allocation_result_for from core.models import Identity, Instance, AtmosphereUser from django.utils.timezone import timedelta, datetime import pytz, sys from dateutil.parser import parse if len(sys.argv) < 3: print "Invalid # ...
Test ICDS login doesn't 500
from __future__ import absolute_import from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse class TestViews(TestCase): @override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html') def test_custom_login(self): response = self.client.get(rever...
Add test for dead code removal.
from numba import compiler, typing from numba.targets import cpu from numba import types from numba.targets.registry import cpu_target from numba import config from numba.annotations import type_annotations from numba.ir_utils import copy_propagate, apply_copy_propagate, get_name_var_table, remove_dels, remove_dead fro...
Add script for generating x25519 keys
#!/usr/bin/env python3 import base64 try: import nacl.public except ImportError: print('PyNaCl is required: "pip install pynacl" or similar') exit(1) def key_str(key): # bytes to base 32 key_bytes = bytes(key) key_b32 = base64.b32encode(key_bytes) # strip trailing ==== assert key_b32[-...
Add missing migration file for exif change.
# Generated by Django 2.2.12 on 2020-04-12 11:11 import django.contrib.postgres.fields.hstore from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pgallery', '0004_auto_20160416_2351'), ] operations = [ migrations.AlterField( model_name=...
Add tests for 01 challenge.
import unittest from solution import body_mass_index, shape_of class TestBodyMassIndex(unittest.TestCase): def test_body_mass_index(self): self.assertEqual(body_mass_index(90, 2), 22.5) self.assertEqual(body_mass_index(90, 1.88), 25.5) class TestShapeOf(unittest.TestCase): def test_shape_of_...
Add an index to compute_node_stats
# Copyright 2013 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
Add a Command to Migrate UserProfile.name_en
from __future__ import print_function from django.core.management.base import BaseCommand from django.db import connection, migrations from django.db.utils import OperationalError from student.models import UserProfile def check_name_en(): """ Check whether (name_en) exists or not. This is helpful when migra...
Add unit test for Soundcloud get_unstarted_query function
from nose.tools import * # noqa import datetime from pmg.models.soundcloud_track import SoundcloudTrack from pmg.models import db, File, Event, EventFile from tests import PMGTestCase class TestUser(PMGTestCase): def test_get_unstarted_query(self): event = Event( date=datetime.datetime.today...
Add queryset for ordering memberships by activity
from django.db import models from django.db.models import Case, When, Value, IntegerField, Sum from django.utils.timezone import now, timedelta class MembershipQuerySet(models.QuerySet): def order_by_gestalt_activity(self, gestalt): a_week_ago = now() - timedelta(days=7) a_month_ago = now() - time...
Validate the existence of `.pyi` stub files
import os from pathlib import Path import numpy as np from numpy.testing import assert_ ROOT = Path(np.__file__).parents[0] FILES = [ ROOT / "py.typed", ROOT / "__init__.pyi", ROOT / "char.pyi", ROOT / "ctypeslib.pyi", ROOT / "emath.pyi", ROOT / "rec.pyi", ROOT / "version.pyi", ROOT / ...
Initialize the geolang toolkit package
from geolang.geolang import ( __author__, __version__, KA2LAT, LAT2KA, UNI2LAT, _2KA, _2LAT, encode_slugify, GeoLangToolKit, unicode, ) # from geolang.geolang import * from .uni2lat import *
Implement simple CSV parsing utility
import csv def csv_as_list(csv_file_name, delim = ';'): with open(csv_file_name, 'rb') as csv_file: data = csv.DictReader(csv_file, delimiter = delim) csv_list = [] for item in data: csv_list.append(item) return csv_list
Add basic PyPI reading logic
# -*- coding: utf-8 -*- """ testifi.pypi ~~~~~~~~~~~~ This module contains the portions of testifi code that know how to handle interacting with PyPI. """ import treq from twisted.internet.defer import inlineCallbacks, returnValue @inlineCallbacks def certifiVersions(): """ This function determines what cer...
Add miscellaneous tests for remaining code
from flask.ext.resty import Api, GenericModelView from marshmallow import fields, Schema import pytest from sqlalchemy import Column, Integer import helpers # ----------------------------------------------------------------------------- @pytest.yield_fixture def models(db): class Widget(db.Model): __tab...
Add a very simple performance testing tool.
""" Simple peformance tests. """ import sys import time import couchdb def main(): print 'sys.version : %r' % (sys.version,) print 'sys.platform : %r' % (sys.platform,) tests = [create_doc, create_bulk_docs] if len(sys.argv) > 1: tests = [test for test in tests if test.__name__ in sys.argv...
Add migration for last commit
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Batch.last_run_failed' db.add_column('batch_processing_batch', 'last_run_failed', self.gf(...
Add data migration for email privacy field.
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-04 13:34 from __future__ import unicode_literals from django.db import migrations def migrate_privacy_email(apps, schema_editor): UserProfile = apps.get_model('users', 'UserProfile') IdpProfile = apps.get_model('users', 'IdpProfile') for i...
Install packages on android device
import os from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice def get_MainActivity(package_name): return package_name + 'MainActivity' def install_package(package_path, device): if device.installPackage(package_path): return True else: return False def install_packages(device,...
Fix typo in previous commit.
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <p...
#!/usr/bin/env python import sys import os.path import site def main(): '''\ Check if the given prefix is included in sys.path for the given python version; if not find an alternate valid prefix. Print the result to standard out. ''' if len(sys.argv) != 3: msg = 'usage: %s <prefix> <p...
Add test to cover ProgressBar and ProgressBarManager.
from bluesky.utils import ProgressBar, ProgressBarManager from bluesky.plans import mv from bluesky import RunEngine from bluesky.examples import NullStatus, SimpleStatus, Mover from collections import OrderedDict import time def test_status_without_watch(): st = NullStatus() ProgressBar([st]) def test_stat...
Add helper methods to render template blocks independently
from django.template.loader_tags import BlockNode, ExtendsNode from django.template import loader, Context, RequestContext, TextNode # Most parts of this code has been taken from this Django snippet: # http://djangosnippets.org/snippets/942/ def get_template(template): if isinstance(template, (tuple, list)): ...
Add a script to reset the return delay time.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # PyAX-12 # The MIT License # # Copyright (c) 2010,2015,2017 Jeremie DECOCK (http://www.jdhp.org) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Sof...
Add Open Sound Controller (OSC) example
import s3g import serial import time import optparse import OSC import threading """ Control an s3g device (Makerbot, etc) using osc! Requires these modules: * pySerial: http://pypi.python.org/pypi/pyserial * pyOSC: https://trac.v2.nl/wiki/pyOSC """ parser = optparse.OptionParser() parser.add_option("-s", "--serialp...
Add TIMIT dataset class for pylearn2.
import numpy as np import os from pylearn2.datasets import dense_design_matrix from pylearn2.utils import string_utils class TIMIT(dense_design_matrix.DenseDesignMatrix): def __init__(self, which_set, preprocessor=None): """ which_set can be train, test, valid or test_valid. """ if...
Add a command to transfer students from one course to another.
from optparse import make_option from django.core.management.base import BaseCommand from django.contrib.auth.models import User from student.models import CourseEnrollment from shoppingcart.models import CertificateItem class Command(BaseCommand): help = """ This command takes two course ids as input and tra...
Add utility functions for tests
import numpy as np def overwrite_labels(y): classes = np.unique(y) y[y==classes[0]] = -1 y[y==classes[1]] = 1 return y
Add a utility for generating simple output file maps
#!/usr/bin/env python from __future__ import print_function import argparse import json import os import sys def fatal(msg): print(msg, file=sys.stderr) sys.exit(1) def find_swift_files(path): for parent, dirs, files in os.walk(path, topdown=True): for filename in files: if not fil...
Add script to wait for puppet run to finish on non-build-nodes
# # Copyright 2012 Cisco Systems, Inc. # # Author: Soren Hansen <sorhanse@cisco.com> # # 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...
Move quiet_logs to separate module
def quiet_logs(sc): logger = sc._jvm.org.apache.log4j logger.LogManager.getLogger("org").setLevel(logger.Level.ERROR) logger.LogManager.getLogger("akka").setLevel(logger.Level.ERROR)
Create test for plot_zipcode to compare generated graphs.
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Tests for Final Project """ import clean_data as cd import pandas def get_data(): """ Retrieve data from csv file to test. """ data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_To...
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Tests for Final Project """ import clean_data as cd import matplotlib.pyplot as plt import pandas import pytest def get_data(): """ Retrieve data from csv file to test. """ data = pandas.read_cs...
Add a fix FixAddMigrateFrom to solve a specific Migrate Problem
from datetime import datetime from bson import ObjectId from flask import current_app from pydash import filter_ from pydash import map_ from ereuse_devicehub.resources.device.component.settings import Component from ereuse_devicehub.resources.device.domain import DeviceDomain from ereuse_devicehub.resources.event.de...
Add utilities for working with URLs
import time from urllib import urlencode from urllib2 import build_opener, Request, urlopen, URLError from urlparse import urlparse class URLResponse(object): def __init__(self, body, domain): self.body = body self.domain = domain def fetchURL(url, extraHeaders=None): headers = [( "User-agent"...
Print the location of the APHLA library
# Load the machine import pkg_resources pkg_resources.require('aphla') import aphla as ap # Import caget and caput from cothread.catools import caget, caput # Load the machine ap.machines.load('SRI21') print ap.__file__
Add test for downloading a public file
import unittest import hashlib from .. import Session class TestSession(unittest.TestCase): def setUp(self): self.sess = Session() def test_public_file_download(self): url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E' sha256 = '9431103cb989f2913cbc503767015ca22c0ae40942932186c...
Improve member_id field (We need the possibility of meber_id = NULL)
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-12-16 12:23 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('server', '0028_auto_20181211_1333'), ] oper...
Copy labels from edx-platform to all the other repos
#!/usr/bin/env python """Copy tags from one repo to others.""" from __future__ import print_function import json import requests import yaml from helpers import paginated_get LABELS_URL = "https://api.github.com/repos/{owner_repo}/labels" def get_labels(owner_repo): url = LABELS_URL.format(owner_repo=owner_r...
Add test for invalid expression command args
import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.decorators import * class InvalidArgsExpressionTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) @no_debug_info_test def test_invalid_lang(self): self.expect("expres...
Add initial Statement and context extraction
import re from indra.statements import BioContext, RefContext from indra.preassembler.grounding_mapper.standardize import \ standardize_db_refs, name_from_grounding class HypothesisProcessor: def __init__(self, annotations, reader=None, grounder=None): self.annotations = annotations self.state...
Add script to generate input data for the visualization assignment
"""Create data set for visualization assignment The data set consists of: <sentence id>\t<label>\t<tagged words> Usage: python folia2visualizaton.py <file in> <output dir> Or: ./batch_do_python.sh folia2visualizaton.py <dir in> <output dir> (for a directory containing folia files) """ from lxml import etree from bs4 i...
Add first version of a random search optimizer
# -*- coding: utf-8 -*- # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # First Party from metaopt.core.arg.util.creator import ArgsCreator from metaopt.core.stoppable.util.exception import StoppedError from metaopt.optimizer.optimizer import Optimizer ...
Migrate sort order of datapoints
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('dive_log', '0002_datapoint'), ] operations = [ migrations.AlterModelOptions( name='datapoint', optio...
Add tests suite for electronic NOT tag.
""" SkCode electronic tag test code. """ import unittest from skcode import (parse_skcode, render_to_html, render_to_text, render_to_skcode) from skcode.tags import (NotNotationTagOptions, DEFAULT_RECOGNIZED_TAGS) class NotNotation...
Add tests for geometry module
from gaphas.geometry import ( distance_rectangle_point, intersect_line_line, point_on_rectangle, ) def test_distance_rectangle_point(): assert distance_rectangle_point((2, 0, 2, 2), (0, 0)) == 2 def test_distance_point_in_rectangle(): assert distance_rectangle_point((0, 0, 2, 2), (1, 1)) == 0 ...
Remove payable mixin - db migrations
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('openstack', '0018_replace_security_group'), ] operations = [ migrations.RemoveField( model_name='instance', ...
Add a conversion from the Hamiltonian cycle problem to SAT
#!/usr/bin/python """ Conversion of the Hamiltonian cycle problem to SAT. """ from boolean import * def hamiltonian_cycle(l): """ Convert a directed graph to an instance of SAT that is satisfiable precisely when the graph has a Hamiltonian cycle. The graph is given as a list of ordered tuples repres...
Add SPDU build and parse functions related to HTTP.
import struct from .spdy import * from .vle import spdy_add_vle_string, spdy_read_vle_string def build_syn_stream_frame(frame, stream_id, host, method, path): hdr_len = struct.calcsize('!HH4BIIBB') assert((frame.position + hdr_len) <= frame.capacity) struct.pack_into('!HH4BIIBB', frame.data, frame.position, CN...
Add solution for problem 27
#!/usr/bin/python """ I don't have found a clever solution, this is a brute force analysis """ from math import sqrt, ceil prime_list = [0] * 20000 def isPrime(x): if x < 0: return 0 if x % 2 == 0: return 0 if prime_list[x]: return 1 for i in range(3, ceil(sqrt(x)), 2): ...
Add py solution for 373. Find K Pairs with Smallest Sums
import heapq class Solution(object): def kSmallestPairs(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]] """ l1, l2 = len(nums1), len(nums2) if l1 * l2 <= k: return sorted([[n1, ...
Add OCS jlab testbed file
from fabric.api import env #Management ip addresses of hosts in the cluster host1 = 'root@172.21.0.10' host2 = 'root@172.21.0.13' host3 = 'root@172.21.0.14' host4 = 'root@172.21.1.12' host5 = 'root@172.21.1.13' #External routers if any #for eg. #ext_routers = [('mx1', '10.204.216.253')] ext_routers = [] #Autonomous...
Bump version: 0.0.6 -> 0.0.7
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.6" class ToolingCMakeUtilConan(ConanFile): name = "tooling-cmake-util" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmak...
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.7" class ToolingCMakeUtilConan(ConanFile): name = "tooling-cmake-util" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmak...
Fix tests for udata/datagouvfr backend
import json from six.moves.urllib_parse import urlencode from .oauth import OAuth2Test class DatagouvfrOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.udata.DatagouvfrOAuth2' user_data_url = 'https://www.data.gouv.fr/api/1/me/' expected_username = 'foobar' access_token_body = json.dumps...
import json from six.moves.urllib_parse import urlencode from .oauth import OAuth2Test class DatagouvfrOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.udata.DatagouvfrOAuth2' user_data_url = 'https://www.data.gouv.fr/api/1/me/' expected_username = 'foobar' access_token_body = json.dumps...
Fix up deprecated lazy import
# Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify,...
# Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify,...
Use a filter field lookup
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) ...
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) ...
Attach custom result popup menu to widget
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def creat...
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def creat...
Fix error where book id wasn't cast to string
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): ...
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): ...
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
Use context management with `FTP`
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP...
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP...
Add show on image function
import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(...
import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def p...
Fix unescaped content in training progress description templatetag
from django import template from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progress.discarded: additional_label = 'default' ...
from django import template from django.template.defaultfilters import escape from django.utils.safestring import mark_safe from workshops.models import TrainingProgress register = template.Library() @register.simple_tag def progress_label(progress): assert isinstance(progress, TrainingProgress) if progres...
Add period at end of description
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import LocalFileOutputDevicePlugin from UM.i18n import i18nCatalog catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Local File Out...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import LocalFileOutputDevicePlugin from UM.i18n import i18nCatalog catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": catalog.i18nc("@label", "Local File Out...
Allow navigationgroup to be blank
""" Page navigation groups allow assigning pages to differing navigation lists such as header, footer and what else. """ from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(exten...
""" Page navigation groups allow assigning pages to differing navigation lists such as header, footer and what else. """ from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(exten...
Fix up the Django Admin a little bit
from form_builder.models import Form, Field, FormResponse, FieldResponse from django.contrib import admin class FieldInline(admin.StackedInline): model = Field extra = 1 class FormAdmin(admin.ModelAdmin): inlines = [FieldInline] class FieldResponseInline(admin.StackedInline): model = FieldResponse...
from form_builder.models import Form, Field, FormResponse, FieldResponse from django.contrib import admin class FieldInline(admin.StackedInline): model = Field extra = 1 class FormAdmin(admin.ModelAdmin): inlines = [FieldInline] list_display = ['title', 'date_created', 'end_date'] search_fields ...
Add colorama as a dependency
#!/usr/bin/env python import os.path from setuptools import find_packages, setup setup( name = 'technic-solder-client', version = '1.0', description = 'Python implementation of a Technic Solder client', author = 'Cadyyan', url = 'https://github.com/cadyyan/technic...
#!/usr/bin/env python import os.path from setuptools import find_packages, setup setup( name = 'technic-solder-client', version = '1.0', description = 'Python implementation of a Technic Solder client', author = 'Cadyyan', url = 'https://github.com/cadyyan/technic...
Add py3.6 to supported version
import esipy import io from setuptools import setup # install requirements install_requirements = [ "requests", "pyswagger", "six", "pytz", ] # test requirements test_requirements = [ "coverage", "coveralls", "httmock", "nose", "mock", "future", "pytho...
import esipy import io from setuptools import setup # install requirements install_requirements = [ "requests", "pyswagger", "six", "pytz", ] # test requirements test_requirements = [ "coverage", "coveralls", "httmock", "nose", "mock", "future", "pytho...
Add content type for proper PyPI rendering
# -*- coding: utf-8 -*- import codecs import re import sys from setuptools import setup def get_version(): return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version') setup(name = "aiodns", version = get_ve...
# -*- coding: utf-8 -*- import codecs import re import sys from setuptools import setup def get_version(): return re.search(r"""__version__\s+=\s+(?P<quote>['"])(?P<version>.+?)(?P=quote)""", open('aiodns/__init__.py').read()).group('version') setup(name = "aiodns", version = get_ve...
Update e-mail address; remove obsolete web page
# setup.py file for texlib from distutils.core import setup setup(name = 'texlib', version = '0.01', description = ("A package of Python modules for dealing with " "various TeX-related file formats."), author = 'A.M. Kuchling', author_email = 'akuchlin@mems-exchange.org', ...
# setup.py file for texlib from distutils.core import setup setup(name = 'texlib', version = '0.01', description = ("A package of Python modules for dealing with " "various TeX-related file formats."), author = 'A.M. Kuchling', author_email = 'amk@amk.ca', packages = ['t...
Rename the package name to junit-xml-output.
#!/usr/bin/env python from setuptools import setup, find_packages import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='junit_xml_output', author = 'David Black', author_email = 'dblack@atlassian.com', url = 'https://bitbucket.org/db_atlass/python-junit-xml-out...
#!/usr/bin/env python from setuptools import setup, find_packages import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='junit-xml-output', author = 'David Black', author_email = 'dblack@atlassian.com', url = 'https://bitbucket.org/db_atlass/python-junit-xml-out...
Add nose to tests dependencies
#! /usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='OpenFisca-Country-Template', version='0.1.0', author='OpenFisca Team', author_email='contact@openfisca.fr', description=u'Template of a tax and benefit system for OpenFisca', keywords='ben...
#! /usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='OpenFisca-Country-Template', version='0.1.0', author='OpenFisca Team', author_email='contact@openfisca.fr', description=u'Template of a tax and benefit system for OpenFisca', keywords='ben...
Remove CLI stuff, bump version to 0.1.0
from setuptools import setup setup( name='plumbium', version='0.0.5', packages=['plumbium'], zip_safe=True, install_requires=[ 'Click', ], entry_points=''' [console_scripts] plumbium=plumbium.cli:cli ''', author='Jon Stutters', author_email='j.stutters@uc...
from setuptools import setup setup( name='plumbium', version='0.1.0', packages=['plumbium'], zip_safe=True, author='Jon Stutters', author_email='j.stutters@ucl.ac.uk', description='Record the inputs and outputs of scripts', url='https://github.com/jstutters/plumbium', license='MIT',...
Revert "[FIX] test_main_flows: missing dependency to run it in a browser"
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most import...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Test Main Flow', 'version': '1.0', 'category': 'Tools', 'description': """ This module will test the main workflow of Odoo. It will install some main apps and will try to execute the most import...
Fix the quantization factor for writing.
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))-1): ''' Saves samples in given sampling frequency to ...
import numpy as np from scipy.io import wavfile def normalize(samples): max_value = np.max(np.abs(samples)) return samples / max_value if max_value != 0 else samples def save_wav(samples, filename, fs=44100, should_normalize=False, factor=((2**15))): ''' Saves samples in given sampling frequency to a ...
Add twitter API functionality test
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() ...
""" Tests for TwitterSA These tests might be overkill, it's my first time messing around with unit tests. Jesse Mu """ import TwitterSA import unittest class TwitterSATestCase(unittest.TestCase): def setUp(self): TwitterSA.app.config['TESTING'] = True self.app = TwitterSA.app.test_client() ...
Use bold_reference_wf to generate reference before enhancing
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(ma...
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) tota...
Test for bigWig aggregation modes
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig') meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(filename, ['x.0.0.m...
import clodius.tiles.bigwig as hgbi import os.path as op def test_bigwig_tiles(): filename = op.join( 'data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig' ) meanval = hgbi.tiles(filename, ['x.0.0']) minval = hgbi.tiles(filename, ['x.0.0.min']) maxval = hgbi.tiles(...
Remove blank space at beginning
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER from vim_turing_machine.constants imp...
"""Encodes a json representation of the business's hours into the 5-bit binary representation used by the merge business hours turing machine. It takes input from stdin and outputs the initial tape.""" import json import sys from vim_turing_machine.constants import BITS_PER_NUMBER def encode_hours(hours, num_bits=BI...
Add type annotation to EntryAlreadyExistsError
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """...
"""errors Journal specific errors and exceptions """ class Error(Exception): """Base class for journal exceptions""" pass class EntryAlreadyExistsError(Error): """Raised when prompts are requested but an entry has already been written today @param message: a message explaining the error """...
Use database to detect the duplication. But the md5 value does not match. Need to add some code here
__author__ = 'mjwtom' import sqlite3 import unittest class fp_index: def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.execute('''C...
__author__ = 'mjwtom' import sqlite3 import unittest class Fp_Index(object): def __init__(self, name): if name.endswith('.db'): self.name = name else: self.name = name + '.db' self.conn = sqlite3.connect(name) self.c = self.conn.cursor() self.c.exec...
Break line in long line of imports.
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the focus for...
# -*- coding: utf-8 -*- from .types import Environment, DiyLangError, Closure, String from .ast import is_boolean, is_atom, is_symbol, is_list, is_closure, \ is_integer, is_string from .parser import unparse """ This is the Evaluator module. The `evaluate` function below is the heart of your language, and the foc...
Use a faster parser for bs4
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if the element text is visible (in the ren...
import scrapy from bs4 import BeautifulSoup from bs4.element import Comment from fedtext.items import FedTextItem class TutorialSpider(scrapy.Spider): name = "tutorialspider" allowed_domains = ['*.gov'] start_urls = ['http://www.recreation.gov'] def visible(self, element): """ Return True if ...
Add graphite cluster discovery support using rancher
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = ...
import os import json, requests from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') elif os.getenv("RANCHER_GRAPHITE_...
Add template path and URLs.
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go....
from django.conf.urls.defaults import patterns, url, include urlpatterns = patterns('', url(r'^survey/', include('go.apps.surveys.urls', namespace='survey')), url(r'^multi_survey/', include('go.apps.multi_surveys.urls', namespace='multi_survey')), url(r'^bulk_message/', include('go....
Make cron job logs readonly for non-superuser
from django.contrib import admin from django_cron.models import CronJobLog class CronJobLogAdmin(admin.ModelAdmin): class Meta: model = CronJobLog search_fields = ('code', 'message') ordering = ('-start_time',) list_display = ('code', 'start_time', 'is_success') admin.site.register(CronJo...
from django.contrib import admin from django_cron.models import CronJobLog class CronJobLogAdmin(admin.ModelAdmin): class Meta: model = CronJobLog search_fields = ('code', 'message') ordering = ('-start_time',) list_display = ('code', 'start_time', 'is_success') def get_readonly_field...
Remove false assertion from test
from tests import PMGLiveServerTestCase from tests.fixtures import dbfixture, CallForCommentData import urllib.request, urllib.error, urllib.parse class TestCallsForCommentsPage(PMGLiveServerTestCase): def setUp(self): super(TestCallsForCommentsPage, self).setUp() self.fx = dbfixture.data(CallFor...
from tests import PMGLiveServerTestCase from tests.fixtures import dbfixture, CallForCommentData import urllib.request, urllib.error, urllib.parse class TestCallsForCommentsPage(PMGLiveServerTestCase): def setUp(self): super(TestCallsForCommentsPage, self).setUp() self.fx = dbfixture.data(CallFor...
Fix broken ConfigParser import for Python3
"""EditorConfig exception classes Licensed under PSF License (see LICENSE.txt file). """ class EditorConfigError(Exception): """Parent class of all exceptions raised by EditorConfig""" from ConfigParser import ParsingError as _ParsingError class ParsingError(_ParsingError, EditorConfigError): """Error r...
"""EditorConfig exception classes Licensed under PSF License (see LICENSE.txt file). """ class EditorConfigError(Exception): """Parent class of all exceptions raised by EditorConfig""" try: from ConfigParser import ParsingError as _ParsingError except: from configparser import ParsingError as _Parsing...
Update for latest Sendgrid webhook format
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) crea...
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) crea...
Fix argument reference in docstring.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main han...
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main han...
Migrate density example to cartopy.
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import typhon nc = Dataset('_data/test_data.nc') lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) vm...
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import matplotlib.pyplot as plt import netCDF4 import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER, LATITUDE_FORMATTER) from typhon.plots.maps import get_cfeatures_at_scale # Read air temperatur...
Add splitter with treeview/editor split.
from PySide import QtGui from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) editor = Editor() self.setCentralWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
from PySide import QtGui, QtCore from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) treeview = QtGui.QTreeView() editor = Editor() self.s...
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase....
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase....
Reduce number of entries shown on index
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') ...
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5...
Fix migration if no language exists
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language...
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language...
Allow overriding database URI from command line
from flask import Flask DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'" SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash' app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api ...
import os from flask import Flask SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash') app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
Fix problems w/ class variables and fix bug with max function on an empty set
from database import QuizDB db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz(Base): def __init__(self, id): self.id = id QUESTION_HASH = "{0}:question".format(self.id) ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hl...
from database import QuizDB import config db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz: QUESTION_HASH = '' ANSWER_HASH = '' def __init__(self, id): self.id = id self.QUESTION_HASH = "{0}:question".format(self.id) self.ANSWER_HASH = "{0}:answer".format(se...
Disable rei.com on oopif benchmarks.
# Copyright 2015 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. from telemetry.page import page from telemetry import story class OopifBasicPageSet(story.StorySet): """ Basic set of pages used to measure performance of ...
# Copyright 2015 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. from telemetry.page import page from telemetry import story class OopifBasicPageSet(story.StorySet): """ Basic set of pages used to measure performance of ...
Convert zipped list to dictionary
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM square = [x for x in range(1, 65)] grain...
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM square = [x for x in range(1, 65)] grain...
Update test for timezones & file-based sessions.
from django.conf import settings from django.core.cache import cache from django.test import TestCase from django.utils.importlib import import_module from session_cleanup.tasks import cleanup import datetime class CleanupTest(TestCase): def test_session_cleanup(self): """ Tests that sessions a...
from django.conf import settings from django.core.cache import cache from django.test import TestCase from django.test.utils import override_settings from django.utils import timezone from django.utils.importlib import import_module from session_cleanup.tasks import cleanup import datetime class CleanupTest(TestCas...
Remove no longer used extra boto file parameter
#!/usr/bin/env python # 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. """ Compile step """ from utils import shell_utils from build_step import BuildStep from slave import slave_utils import os import...
#!/usr/bin/env python # 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. """ Compile step """ from utils import shell_utils from build_step import BuildStep from slave import slave_utils import os import...
Move re compilation to the module load
# -*- coding: utf-8 -*- ''' Various user validation utilities ''' # Import python libs import re import logging log = logging.getLogger(__name__) def valid_username(user): ''' Validates a username based on the guidelines in `useradd(8)` ''' if type(user) not str: return False if len(use...
# -*- coding: utf-8 -*- ''' Various user validation utilities ''' # Import python libs import re import logging log = logging.getLogger(__name__) VALID_USERNAME= re.compile(r'[a-z_][a-z0-9_-]*[$]?', re.IGNORECASE) def valid_username(user): ''' Validates a username based on the guidelines in `useradd(8)` ...
Use dbm cache instead of file system
# Scrapy settings for pystock-crawler project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'pystock-crawler' EXPORT_FIELDS = ( # Price columns 'symbol'...
# Scrapy settings for pystock-crawler project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'pystock-crawler' EXPORT_FIELDS = ( # Price columns 'symbol'...