Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add python interface around C implementation of levinson.
#! /usr/bin/env python # Last Change: Sun Sep 14 03:00 PM 2008 J import numpy as np from c_lpc import levinson as c_levinson def levinson(r, order, axis = -1): """Levinson-Durbin recursion, to efficiently solve symmetric linear systems with toeplitz structure. Arguments --------- r : array-...
Support setting default modes in channels
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from txircd.utils import ModeType from zope.interface import implements class DefaultModes(ModuleData): implements(IPlugin, IModuleData) name = "DefaultModes" core = True def hookIRCd(self, ircd): ...
Fix atomdetails failure column size
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
Test ability to download from lbrynet
import xmlrpclib import json from datetime import datetime from time import sleep from slackclient import SlackClient def get_conf(): f = open('testbot.conf', 'r') token = f.readline().replace('\n', '') channel = f.readline().replace('\n', '') f.close() return token, channel def test_lbrynet(lbry,...
Create a management command to output a given template
from django.core.management.base import LabelCommand from django.template.loader import render_to_string from django.template import RequestContext from django.http import HttpRequest class Command(LabelCommand): help = 'Render a template to STDOUT' args = '<template path>' def handle_label(self, template...
Use find_packages to deal with vendoring
import multiprocessing # noqa # stop tests breaking tox from setuptools import setup import tvrenamr setup( name=tvrenamr.__title__, version=tvrenamr.__version__, description='Rename tv show files using online databases', long_description=open('README.rst').read() + '\n\n' + open('CHANGELOG.rst'...
import multiprocessing # noqa # stop tests breaking tox from setuptools import find_packages, setup import tvrenamr setup( name=tvrenamr.__title__, version=tvrenamr.__version__, description='Rename tv show files using online databases', long_description=open('README.rst').read() + '\n\n' + open(...
Return 'Hello World' by wsgiref
def app(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] if __name__ == '__main__': try: from wsgiref.simple_server import make_server httpd = make_server('', 8080, app) print('Serving on port 8080...') httpd.serve_foreve...
Add first unit tests for sqlite db
''' Module for testing the SQLite DB. Fairly similar to the test_api tests... ''' import os import sys import json import unittest CWD = os.path.dirname(os.path.abspath(__file__)) MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Allow import of sqlite_driver if os.path.join(MS_WD, 'storage') not ...
Add script to generate report on scraper tests
import os import json import saulify.sitespec as sitespec SPEC_DIRECTORY = "sitespecs" if __name__ == "__main__": for fname in os.listdir(SPEC_DIRECTORY): fpath = os.path.join(SPEC_DIRECTORY, fname) test_cases = sitespec.load_testcases(fpath) for test_case in test_cases: resu...
Add the expand2 benchmark using Sage
from timeit import default_timer as clock from sage.all import var var("x y z w") e = (x+y+z+w)**15 f = e*(e+w) print f t1 = clock() g = f.expand() t2 = clock() print "Total time:", t2-t1, "s"
Add some tests for comparison expressions: and, or, and order of operations.
import pytest from stix2matcher.matcher import match _observations = [ { "type": "observed-data", "number_observed": 1, "first_observed": "2004-11-26T11:42:29Z", "objects": { "0": { "type": u"person", "name": u"alice", "a...
Add basic binary card resource
"""Module for generating Binary Cards resource.""" from PIL import Image def resource_image(get_request, resource): """Create a image for Binary Cards resource. Args: get_request: HTTP request object resource: Object of resource data. Returns: A Pillow image object. """ ...
Add tool for printing channel IDs
from flow import Flow from config import BOTNAME, BOTPW, ORG_ID try: flow = Flow(BOTNAME) except flow.FlowError as e: flow = Flow() flow.create_device(BOTNAME, BOTPW) print('Device for bot {} created'.format(BOTNAME)) def print_channels(): print('\033[1mYour bot "{}" has access to these channels:...
Initialize USGSResource object model to be similar to cuahsi
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from apps.bigcz.models import Resource class USGSResource(Resource): def __init__(self, id, description, author, links, title, ...
Add a test for getting the homepage
from .conftest import load class TestStatic: def test_get_index(self, client): response = client.get("/") assert response.status_code == 200 assert 'href="/api"' in load(response, as_json=False)
Add separate test file for javascript
import glob import json import os import pytest from helpers import solutions_dir # NOTE: If we make solution_files a fixture instead of a normal attr/function, # then we can't use it in pytest's parametrize solution_files = glob.glob(os.path.join(solutions_dir("javascript"), "*.js")) @pytest.mark.javascript def ...
Implement running average action history
import theano from sft import Size from sft.Actions import Actions from sft.agent.ah.ActionHistory import ActionHistory import numpy as np class RunningAvg(ActionHistory): def __init__(self, logger, n, factor): self.logger = logger self.n = n self.factor = factor def get_size(self): return Size(self.n, s...
Add script to add a simulation to the yaml file.
import os import yaml import yt import sys data_dir = '/mnt/data/renaissance' rsl_page_root = os.environ.get( 'RSL_PAGE_ROOT', '/home/britton/rensimlab.github.io') simyaml = os.path.join(rsl_page_root, '_data', 'simulations.yaml') simulation_data = yaml.load(open(simyaml, 'r')) if len(sys.argv) < 2: sys.exi...
Add another balltree benchmark, this time with plot interface.
from scikits.learn.BallTree import BallTree, knn_brute import numpy as np from time import time from scipy.spatial import cKDTree import sys import pylab as pl def compare_nbrs(nbrs1,nbrs2): assert nbrs1.shape == nbrs2.shape if(nbrs1.ndim == 2): N,k = nbrs1.shape for i in range(N): ...
Add test for conditional compilation
from tests.compiler import compile_snippet, STATIC_START, internal_call from thinglang.compiler.opcodes import OpcodePushStatic, OpcodeJumpConditional, OpcodeJump PREFIX = [ OpcodePushStatic(STATIC_START), OpcodePushStatic(STATIC_START + 1), internal_call('text.__equals__'), ] def test_simple_conditional(...
Add DN's tool for XDS.INP parsing
#!/usr/bin/env python import json import sys class INP2DICT(object): def __init__(self, xdsinp, xdsdict): self.xdsinp = xdsinp self.xdsdict = xdsdict self.run() def run(self): temp = open(self.xdsinp, 'r').readlines() inp=[] for line in temp: inp.a...
Add ticketed features test file
"""A growing set of tests designed to ensure when isort implements a feature described in a ticket it fully works as defined in the associated ticket. """ import isort def test_semicolon_ignored_for_dynamic_lines_after_import_issue_1178(): """Test to ensure even if a semicolon is in the decorator in the line foll...
Add function to run a local or remote query
# gaia_tools.query: some helper functions for querying the Gaia database import numpy from astropy.table import Table from astroquery.gaia import Gaia import psycopg2 def query(sql_query,local=False,dbname='catalogs',user='postgres'): """ NAME: query PURPOSE: perform a query, either on a loca...
Add missing migration file for `per_page` field.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('people', '0003_people_standfirst'), ] operations = [ migrations.AddField( model_name='people', name=...
Add script for generating docs.
#!/usr/bin/env python from __future__ import print_function from contextlib import contextmanager from glob import glob from path import path import os from os.path import abspath, basename, dirname, exists, isfile from shutil import move, rmtree from subprocess import check_call HERE = dirname(abspath(__file__)) ZIPL...
Add an analysis file for 10x10 simulations
# -*- coding:utf-8 -*- from pylab import * import tables """ TODO - Faire tous les MPS - Faire tous les STS - Faire le déphasage """ DB = tables.openFile('db.h5') # Get data DATA = [] for g in DB.walkGroups(): try: pset = g.paramset._v_attrs res = g.results._v_attrs except tables.NoSuchNode...
Add set background resolution and bit depth example
"""Sets all Backgrounds in the currently active comp to 1920x1080 (32 bit). This example shows how to list tool of a specific type and set some of its inputs. Additionally this shows off how `fusionless` is able to automatically interpret an enum value (like "float32" for image depth) to the corresponding float value ...
Add initial URL history importer
#!/usr/bin/env python # Copyright 2009 Google Inc. 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 required...
Add skeleton of all 2D solver classes
from FEMur import * import sympy as sy import numpy as np import scipy as sc import matplotlib.pyplot as plt import matplotlib.tri as tri import scipy.interpolate from math import ceil class Solver(object): ''' 2-dimensional solver top class. Provides common initialization to all child solver classes. ...
Add test for hashable objects
from butter.eventfd import Eventfd from butter.fanotify import Fanotify from butter.inotify import Inotify from butter.signalfd import Signalfd from butter.timerfd import Timerfd import pytest @pytest.fixture(params=[Eventfd, Fanotify, Inotify, Signalfd, Timerfd]) def obj(Obj): o = Obj.__new__(Obj) retur...
Implement management command to import orders for existing resources.
from django.core.management.base import BaseCommand from waldur_core.core.models import User from waldur_mastermind.marketplace.models import Order, OrderItem, Resource class Command(BaseCommand): help = """Create marketplace order for each resource if it does not yet exist.""" def handle(self, *args, **opt...
Add arc distance for theano.
# Authors: Frederic Bastien # License: MIT import theano import theano.tensor as tensor def arc_distance_theano_alloc_prepare(dtype='float64'): """ Calculates the pairwise arc distance between all points in vector a and b. """ a = tensor.matrix(dtype=str(dtype)) b = tensor.matrix(dtype=str(dtype))...
Add test for decorated kwargs to decorated function
from fastats.core.decorator import fs def square(x): return x * x @fs def cube(x): return x * x * x @fs def func(x): a = square(x) return a / 2 def test_fs_decorated_functions_as_kwargs_to_another(): assert square(2) == 4.0 assert square(3) == 9.0 assert cube(3) == 27.0 assert cub...
Add test for case properties changed function
from __future__ import absolute_import import uuid from django.test import TestCase, override_settings from casexml.apps.case.mock import CaseBlock from corehq.apps.domain.shortcuts import create_domain from corehq.apps.hqcase.utils import submit_case_blocks from corehq.form_processor.interfaces.dbaccessors import C...
Fix build: missed a file
# Copyright (c) 2006-2008 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. """Compares the image output of a test to the expected image output using fuzzy matching. """ import errno import logging import os import shutil i...
Add migration files for ProblemQuestion
# Generated by Django 2.0.7 on 2018-07-11 07:51 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('problem', '0006_auto_201...
Add 5 test cases for maximumSubarray problem.
import unittest from maximumSubarray import Solution class TestMaximumSubarrayEdgeCases(unittest.TestCase): def setUp(self): self.solution = Solution() def testEmptyArrayReturnsZero(self): self.assertRaises(ValueError, self.solution.maxSubArray, []) def testArrayWithSingleEntryReturnsEntr...
Add test cases for runner container service.
try: import simplejson as json except ImportError: import json import os from oslo.config import cfg import unittest2 from st2actions.container.service import RunnerContainerService class RunnerContainerServiceTest(unittest2.TestCase): def test_get_entry_point_absolute_path(self): service = Ru...
Add a test case to see that we are using cryptography from the right source
def test_cryptography_path(): """ Checks that an imported version of cryptography is actually from the dist/cext folder. We can allow other versions, but for now, we want tests to fail until we identify the right way to do this. """ try: import cryptography assert "dist/cext" i...
Return `OrderItemTuple`s rather than order item database entities from service
""" byceps.services.shop.order.ordered_articles_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from collections import Counter from typing import Dict, Sequence from ....database import db from ..article.mod...
""" byceps.services.shop.order.ordered_articles_service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from collections import Counter from typing import Dict, Sequence from ....database import db from ..article.mod...
Add migration for methods, realtimeurl
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-11 17:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('breach', '0014_auto_20160504_1753'), ] operations = [ migrations.AddField( ...
Create UserProfile model for NurseConnect
from django.db import models from molo.profiles.models import UserProfile as MoloUserProfile class UserProfile(MoloUserProfile): """ NurseConnect requires a few modifications to the standard way Profiles are handled by molo.profiles. This model serves to implement these. """ clinic_code = models....
Add td agent restarts tep
# -*- coding: utf-8 -*- import logging from util import full_stack from util import exec_remote_command from dbaas_cloudstack.models import HostAttr as CS_HostAttr from workflow.steps.util.base import BaseStep from workflow.steps.util import test_bash_script_error from workflow.steps.util import td_agent_script from wo...
Add blob metadata migration check
# -*- coding: utf-8 -*- # Generated by Django 1.11.14 on 2019-01-05 00:21 from __future__ import unicode_literals from __future__ import absolute_import from __future__ import print_function import sys import traceback from django.core.management import call_command from django.db import connections, migrations from...
Add some tests for the injector registry
import pytest from fanstatic import Library, Resource, NeededResources from fanstatic.injector import InjectorPlugin from fanstatic.registry import InjectorRegistry from fanstatic import make_injector from fanstatic import ConfigurationError from fanstatic.injector import TopBottomInjector class TopInjector(Injector...
Add unit test for train.py
""" A unit test for the train.py script """ import os import pylearn2 from pylearn2.scripts.train import train def test_train_cmd(): """ Calls the train.py script with a short YAML file to see if it trains without error """ train(os.path.join(pylearn2.__path__[0], "scripts/...
Use from demoapp import tasks instead
# Create your views here. from tasks import add from django.http import HttpResponse def foo(request): r = add.delay(2, 2) return HttpResponse(r.task_id)
# Create your views here. from demoapp import tasks from django.http import HttpResponse def foo(request): r = tasks.add.delay(2, 2) return HttpResponse(r.task_id)
Add Key, Value, ErrorCode classes.
""" util.py ~~~~~~~~~~~~ contains utility functions. """ import hashlib from datetime import datetime # Classes def get_timestamp(): return datetime.utcnow() class Key(object): """ A simple object for adding aditional properties to keys """ def __init__(self, key=None, node_hash=None): ...
Add tests for unicode usage in author truncation
#!/usr/bin/env python # encoding: utf-8 import unittest from ckanext.nhm.lib.helpers import dataset_author_truncate class AuthorTruncateTest(unittest.TestCase): ''' Tests for the dataset_author_truncate helper function. ''' def test_untruncated_author(self): ''' dataset_author_trunc...
Remove responses references in object_documents
# Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: goodson@google.com # Maintained By: goodson@google.com """ Remove relationships related to deleted response objects Create Date: 2016-05-10 12:25:...
# Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: goodson@google.com # Maintained By: goodson@google.com """ Remove relationships related to deleted response objects Create Date: 2016-05-10 12:25:...
Add migrations that fixes pre 1.10 behavior
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-09-16 01:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0013_auto_20161209_1447'), ] operations = [ migrations.Alte...
Add G4 and G5 frameworks to database
"""Add older G-Cloud Framewoks Revision ID: 3e6c454a6fc7 Revises: 3acf60608a7d Create Date: 2015-04-02 15:31:57.243449 """ # revision identifiers, used by Alembic. revision = '3e6c454a6fc7' down_revision = '3acf60608a7d' from alembic import op from sqlalchemy.sql import table, column from sqlalchemy import String, ...
Fix column lengths to match schema
# -*- coding: utf-8 -*- """Fix column lengths Revision ID: 530c22761e27 Revises: e2b28adfa135 Create Date: 2020-04-20 16:19:22.597712 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '530c22761e27' down_revision = 'e2b28adfa135' branch_labels = None depends_on =...
ADD Network infrastructure unit tests
def test_create_network(client): result = client.post("/networks/", data={"name": "test_network"}) assert result.status_code == 200 assert result.get_json() == {"msg": "Network created succesfully!"} def test_get_all_network(client): result = client.get("/networks/") assert result.status_code ==...
Add test for finalizer, which broke in 3.8 due to underlying change in Pool._repopulate_pool, which also manifests as a hang in long-running tests that manage to kill all the worker processes.
import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): def setUp(s...
Add very basic lexer test that passes
import unittest import sure import lexer class TestLexer(unittest.TestCase): def _lex_data(self, data): lex = lexer.Lexer() lex.input(data) token_list = list(lex) return token_list def _assert_individual_token(self, input, expected_token_type, expected_token_value): l ...
Add a script to dump out all project inter-dependencies.
import os import re from use_lldb_suite import lldb_root src_dir = os.path.join(lldb_root, "source") inc_dir = os.path.join(lldb_root, "include") src_map = {} include_regex = re.compile('#include \"(lldb(.*/)+).*\"') def scan_deps(this_dir, file): includes = set() with open(file) as f: ...
Fix existing home page URIs with migration
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): def ensure_http_prefix_contact(apps, schema_editor): Contact = apps.get_model("membership", "Contact") # Contacts with broken homepage field value ...
Add a script for doing basic maintenance on a private Docker Registry
#!/usr/bin/env python """A command-line client for the Docker registry.""" import argparse import requests def list_cmd(args): """List images""" url = args.registry + '/v2/_catalog' r = requests.get(url) data = r.json() for repo in data['repositories']: print(repo) def list_tags_cmd(a...
Replace FTS functions since the FD table definition has changed.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('firestation', '0039_auto_20170126_0857'), ] sql = """ CREATE OR REPLACE FUNCTION department_fts_document(integer) RETURNS tsvector ...
Add integration test for i19 screen using xia2 regression data
from __future__ import division, absolute_import from i19.command_line.screen import i19_screen def test_i19screen_command_line_help_does_not_crash(): i19_screen().run('') def test_i19screen(tmpdir): import os import libtbx xia2_regression = libtbx.env.under_build("xia2_regression") data_dir = os.path.joi...
Sort to-read list by publication date
#!/usr/bin/python import logging import re import subprocess import sys import os import calibre_config from calibre.library.database2 import LibraryDatabase2 from calibre.utils.config import prefs import args TODO_DIR = os.path.join(os.environ['HOME'], 'Dropbox', 'todo') ISSUE_PATTERN = re.compile('(\d+) (.*)$') ...
Add a CLI to call Eidos
""" This is a Python based command line interface to Eidos to complement the Python-Java bridge based interface. EIDOSPATH (in the INDRA config.ini or as an environmental variable) needs to be pointing to a fat JAR of the Eidos system. """ import os import glob import logging import subprocess from indra import get_con...
Implement CUSIP task in Python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math def cusip_check(cusip: str) -> bool: if len(cusip) != 9: raise ValueError('CUSIP must be 9 characters') cusip = cusip.upper() total = 0 for i in range(8): c = cusip[i] if c.isdigit(): v = int(c) eli...
Fix case in nerd tree matcher regex
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import re from powerline.bindings.vim import buffer_name NERD_TREE_RE = re.compile(b'NERD_TREE_\\d+') def nerdtree(matcher_info): name = buffer_name(matcher_info) return name and NERD_TRE...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import re from powerline.bindings.vim import buffer_name NERD_TREE_RE = re.compile(b'NERD_tree_\\d+') def nerdtree(matcher_info): name = buffer_name(matcher_info) return name and NERD_TRE...
Concatenate each line of the string
def main(): s=raw_input() a=raw_input() b=raw_input() c=raw_input() x = (a,b,c) print s.join(x) main()
Add response time distributions from GIS.
# A dictionary where the key is an fdid-state and the values are lognormal fits generated # from response time gis data. response_time_distributions = { '37140-CA': (0.20611095226322063, -4.7357748161635111, 8.6850997083002905), '02072-FL': (0.34949627393777505, -2.1718657657665021, 6.6793162966144539), '0...
Add script to move corrupt images
""" Script to move corrupt images to 'dirty' directory Reads list of images to move. Does not verify that images are corrupt - Simply moves to 'dirty' directory of appropriate data-release creating the required directory structure """ import os import argparse parser = argparse.ArgumentParser( ...
Include the migration this time :fireworks:
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('projects', '0012_proper-name-for-install-project'), ] operations = [ migrations.AddField( model_name='project', ...
Add an alembic migration script adding the `active` field to the filters table
"""Add an active field to Filter Revision ID: 2ea9623b21fa Revises: 18ebf3181f87 Create Date: 2014-09-03 09:37:39.653039 """ # revision identifiers, used by Alembic. revision = '2ea9623b21fa' down_revision = '18ebf3181f87' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column( 'f...
Add a starter script for plotting marker trajectories approaching targets.
import climate import itertools import lmj.plot import numpy as np import source as experiment import plots @climate.annotate( root='plot data from this experiment subjects', pattern=('plot data from files matching this pattern', 'option'), markers=('plot data for these mocap markers', 'option'), tar...
Add failing tests for social handles
import core.tests.utils as test_utils from core import models class WagtailCompanyPageTestCase(test_utils.WagtailTest): def test_twitter_handler(self): twitter_user = 'springloadnz' twitter_url = 'https://twitter.com/{}'.format(twitter_user) twitter_handle = '@{}'.format(twitter_user) ...
Add convenience command for finding apiupdates to execute manually
from django.core.management.base import BaseCommand, CommandError from stationspinner.accounting.models import APIUpdate, APICall from stationspinner.character.models import CharacterSheet from stationspinner.corporation.models import CorporationSheet import sys class Command(BaseCommand): args = '<character/corpor...
Add variants to clinical report script
"""Add variant report variants to a Clinical Report by ID. """ import os import requests from requests.auth import HTTPBasicAuth import sys import json import argparse # Load environment variables for request authentication parameters if "OMICIA_API_PASSWORD" not in os.environ: sys.exit("OMICIA_API_PASSWORD envir...
Add script to write CIViC VCF
from civicpy import civic from civicpy.exports import VCFWriter import argparse parser = argparse.ArgumentParser(description='Create CIViC VCF') parser.add_argument('vcf_path') args = parser.parse_args() with open(args.vcf_path, "w") as fh: writer = VCFWriter(fh) for variant in civic.get_all_variants(): ...
Add a test for the ignore-unknown-dependency command line option.
"""Test the ignore-unknown-dependency command line option. """ import pytest def test_no_ignore(ctestdir): """No command line option, e.g. ignore-unknown-dependency is not set. Explicitly select only a single test that depends on another one. Since the other test has not been run at all, the selected te...
Add some tests for event dispatcher
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from mock import Mock from testtools import TestCase from spreadflow_core.eventdispatcher import EventDispatcher class TestEvent(object): pass class OtherEvent(object): pass class EventDispatcherT...
Add utils for initalizing dataloaders
from typing import Tuple, Type, Union import torch import numpy as np def init_dataloaders(X_train: np.ndarray, y_train: np.ndarray, X_test: np.ndarray, y_test: np.ndarray, batch_size: int ) -> Tuple[Type[torch.u...
Remove redundant 'ckernel' overload match
""" Lift ckernels to their appropriate rank so they always consume the full array arguments. """ from __future__ import absolute_import, division, print_function import datashape from pykit.ir import transform, Op #------------------------------------------------------------------------ # Run #----------------------...
""" Lift ckernels to their appropriate rank so they always consume the full array arguments. """ from __future__ import absolute_import, division, print_function import datashape from pykit.ir import transform, Op #------------------------------------------------------------------------ # Run #----------------------...
Test harness for the multicast transceiver.
#!/usr/bin/python # # Basic acceptance test harness for the Multicast_sender and receiver # components. # import socket import Axon def tests(): from Axon.Scheduler import scheduler from Kamaelia.Util.ConsoleEcho import consoleEchoer from Kamaelia.Util.Chargen import Chargen from Kamaelia.Internet.Multic...
Add test for wake losses
import pandas as pd import numpy as np import pytest from pandas.util.testing import assert_series_equal from windpowerlib.wake_losses import reduce_wind_speed, get_wind_efficiency_curve, display_wind_efficiency_curves import windpowerlib.wind_turbine as wt class TestWakeLosses: def test_reduce_wind_speed(self)...
Add a simple demo for showing the features of the Component class.
from __future__ import with_statement from enthought.enable.api import Component, ComponentEditor from enthought.traits.api import HasTraits, Instance from enthought.traits.ui.api import Item, View class MyComponent(Component): def draw(self, gc, **kwargs): w,h = gc.width(), gc.height() gc.clear()...
Add migration for adding published column in project
"""Add published column to project Revision ID: 3a98a6674cb2 Revises: 35f8b948e98d Create Date: 2015-08-07 10:24:31.558995 """ # revision identifiers, used by Alembic. revision = '3a98a6674cb2' down_revision = '35f8b948e98d' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('project'...
Add a migration for object_controls -> relationships
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com """Migrate object_controls to relationships Revision ID: 29d21b3c24b4 Revises: ...
Add new message which checks whether an object exists
# stdlib from typing import Any from typing import Optional # third party from nacl.signing import VerifyKey # relative from ... import UID from ....abstract.node import AbstractNode from .simple_messages import NodeRunnableMessageWithReply class DoesObjectExistMessage(NodeRunnableMessageWithReply): __attr_all...
Add DB upgrade debugging script
""" """ import click import gevent import structlog from raiden.exceptions import InvalidDBData, RaidenDBUpgradeError from raiden.storage import serialize, sqlite from raiden.utils.upgrades import UpgradeManager log = structlog.get_logger(__name__) database_path = "" def upgrade_db(current_version: int, new_versi...
Add a common run task script for all tasks. Not supported by db_client yet
import sys import logging import logging.config import traceback import bson.objectid import config.global_configuration as global_conf import database.client import util.database_helpers as dh def main(*args): """ Run a particular task. :args: Only argument is the id of the task to run :return: ...
Move test utils to infra module
import random import string INDENT = '\n' + ' ' * 8 def generate_simple_output_program(source): return """thing Program setup{source} """.format(source=INDENT + INDENT.join([source] if isinstance(source, str) else source)) def generate_test_case_structure(dct): lst = [] for name, groups in list...
Add mgmt cmd to delete location_types from couch
from django.core.management.base import BaseCommand from dimagi.utils.couch.database import iter_docs from corehq.apps.domain.models import Domain class IterativeSaver(object): """ Bulk save docs in chunks. with IterativeSaver(db) as iter_db: for doc in iter_docs(db) iter_...
Add example script for adjusting live camera feed brightness.
from Arlo import Arlo USERNAME = 'user@example.com' PASSWORD = 'supersecretpassword' try: # Instantiating the Arlo object automatically calls Login(), which returns an oAuth token that gets cached. # Subsequent successful calls to login will update the oAuth token. arlo = Arlo(USERNAME, PASSWORD) # At this point ...
Add API test for SkewT.
import tempfile import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from metpy.plots.skewt import * # noqa # TODO: Need at some point to do image-based comparison, but that's a lot to # bite off right now class TestSkewT(object): def test_api(self):...
Hide deprecated shaders used by old OSLObject
########################################################################## # # Copyright (c) 2019, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
Add py solution for 646. Maximum Length of Pair Chain
class Solution(object): def findLongestChain(self, pairs): """ :type pairs: List[List[int]] :rtype: int """ pairs.sort() LIS = [] for p in pairs: L, U = -1, len(LIS) while L + 1 < U: mid = (L + U) / 2 if ...
Add test for species filter.
""" Unit tests for the species filter """ import unittest import numpy as np from ....system import lattice from .. import speciesFilter from .. import base ################################################################################ class TestSpeciesFilter(unittest.TestCase): """ Test species filter...
Change 'deleted' to Boolean in project_user_quotas
# Copyright 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
Add a few tests for fixtures.py.
from zerver.lib.test_classes import ZulipTestCase from analytics.lib.counts import CountStat from analytics.lib.fixtures import generate_time_series_data # A very light test suite; the code being tested is not run in production. class TestFixtures(ZulipTestCase): def test_deterministic_settings(self): # t...
Add basic Dataset. No ImgSet nor Preposcessing
__author__ = 'luigolas' from package.image_set import ImageSet import re # import numpy as np # import package.image as image # import package.evaluator as evaluator # import itertools # import cv2 class Dataset(): def __init__(self): self.id_regex = "P[1-6]_[0-9]{3}" self.probe = None s...
Add wrapper for memaslap load tester.
import sys, socket, time, logging import shlex, subprocess from kazoo.client import KazooClient from kazoo.exceptions import NodeExistsError def zkConnect(conn_str): zk = KazooClient(hosts=conn_str) zk.start() return zk def zkCreateJobDir(zk, job_name): zk.ensure_path("/napper/memaslap/%s" % (job_name)) def ...
Add management command for clearing cache
from django.core.cache import cache from django.core.management.base import BaseCommand class Command(BaseCommand): """Command to clear the entire cache.""" help = 'Clears the cache.' def handle(self, *args, **kwargs): cache.clear() self.stdout.write('Cache has been cleared.', ending="\n"...
Use old SedAAdjust in all existing NHD projects
# Generated by Django 3.2.10 on 2021-12-27 19:26 import json from django.db import migrations def override_sedaadjust_for_old_projects(apps, schema_editor): """ The default value of SedAAdjust is being changed from 1.5 to 1.25 for all new projects, which will use the high resolution "nhdhr" stream data. F...