Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Read in python dependency graph and clean up
# IPython log file import itertools as it with open('pypi-deps.txt', 'r') as fin: lines = fin.readlines() edges = [line.rstrip().split() for line in lines] packages = set(list(it.chain(*edges))) len(edges) len(packages) 'skimage' in packages import toolz as tz from toolz import curried as c dep_count...
Add functional tests for connection change
# -*- coding: utf-8 -*- from __future__ import unicode_literals from sure import scenario from pyeqs import QuerySet from tests.helpers import prepare_data, cleanup_data, add_document @scenario(prepare_data, cleanup_data) def test_simple_search_with_host_string(context): """ Connect with host string """...
Implement the custom prefixes module
from twisted.plugin import IPlugin from twisted.python import log from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements import logging class CustomPrefix(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name =...
Add management command to export TCamp lobby day participants.
from django.core.management.base import BaseCommand, CommandError from reg.models import * from optparse import make_option import cStringIO, csv from collections import defaultdict class Command(BaseCommand): help = 'Closes the specified poll for voting' option_list = BaseCommand.option_list + ( make...
Add Bluetooth support. Still buggy but works. Mostly. If you are lucky.
from time import sleep from bluetooth import * class BluetoothDataSource: def __init__(self, params): self.params = params self.socket = BluetoothSocket(RFCOMM) pass def open(self): try: self.socket.connect((self.params['device'], self.params['port'])) sleep(0.4) return True except BluetoothError...
Add script to convert (some of) hdf5 tracking data to csv
#!/usr/bin/env python from __future__ import print_function from os.path import join, splitext import glob import pandas as pd #import matplotlib.pyplot as plt import multi_tracker_analysis as mta def main(): #experiment_dir = 'choice_20210129_162648' experiment_dir = '.' def find_file_via_suffix(suf...
Add script to compare npm versions
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This script compares the npm packages version in the Luxembourg # project with the ones in ngeo. # Make sure to call "npm i" in the geoportal directory before running the script. import json with open('./geoportal/package.json') as json_file: lux_deps = json.load(...
Add trainer for fcn8s on apc2016
#!/usr/bin/env python import argparse import os import os.path as osp import chainer from chainer import cuda import fcn import datasets def main(): parser = argparse.ArgumentParser() parser.add_argument('--fcn16s', required=True) parser.add_argument('--gpu', type=int, default=0) parser.add_argume...
Add a new test for WindowDict
from allegedb.cache import WindowDict from itertools import cycle testvs = ['a', 99, ['spam', 'eggs', 'ham'], {'foo': 'bar', 0: 1, '💧': '🔑'}] testdata = [] for k, v in zip(range(100), cycle(testvs)): testdata.append((k, v)) windd = WindowDict(testdata) assert list(range(100)) == list(windd.keys()) for item i...
Add some tests for flask integration
import os import socket from webtest import TestApp from nose.tools import eq_, assert_raises from mock import MagicMock, patch from flask import Flask from bugsnag.six import Iterator from bugsnag.flask import handle_exceptions import bugsnag.notification bugsnag.configuration.api_key = '066f5ad3590596f9aa8d601ea89a...
Add common base weigher/weigher handler for filter scheduler
# Copyright 2012 Intel Inc, OpenStack LLC. # 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...
Add temporary corpus document generator - toolset need to be reworked.
import joblib path_dict = joblib.load('data/filepath_dict.txt') def tmp_gen(): for i in range(len(path_dict)): path = path_dict[i] with open(path) as document_file: yield document_file.read()
Add a test for missing migrations.
import cStringIO from django.test import TestCase from django.core.management import call_command class MissingMigrationTest(TestCase): def test_for_missing_migrations(self): out = cStringIO.StringIO() call_command('makemigrations', '--dry-run', verbocity=3, interactive=Fal...
Add backoff retry async example
import asyncio import logging import aiohttp import backoff @backoff.on_exception(backoff.expo, aiohttp.errors.ClientError, max_tries=8) async def get_url(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: ...
Add script that updates Solr configuration on ZooKeeper
#!/usr/bin/env python import argparse from mc_solr.constants import * from mc_solr.solr import update_zookeeper_solr_configuration if __name__ == "__main__": parser = argparse.ArgumentParser(description="Update Solr's configuration on ZooKeeper.", epilog="This script does not...
Add a couple of tests for lsxfel
from karabo_data import lsxfel from karabo_data import H5File def test_lsxfel_file(mock_lpd_data, capsys): with H5File(mock_lpd_data) as f: img_ds, index = lsxfel.find_image(f) assert img_ds.ndim == 4 assert index['first'].shape == (480,) lsxfel.summarise_file(mock_lpd_data) out, e...
Add script to get number of apps blocked without duplicates
#!/bin/env python # Get the number of apps blocked by each Motorola patent # and plot agains the number of citations to that patent import pandas as pd import matplotlib as plt Blocking = pd.read_csv("../data/Motorola_blocking_patents_1114.csv") MotoPatents = pd.read_csv("../data/Motorola_Patents_Blocking_Citations.c...
Add version upgrade plug-in object
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Logger import Logger from UM.PluginObject import PluginObject ## A type of plug-in that upgrades the preferences from an old file format to # a newer one. # # Each version upgrade plug-in can convert machine i...
Add tests for tshark sub-module
import mock from pyshark.tshark.tshark import ( get_tshark_display_filter_flag, get_tshark_interfaces, get_tshark_version, ) @mock.patch('pyshark.tshark.tshark.subprocess.check_output', autospec=True) def test_get_tshark_version(mock_check_output): mock_check_output.return_value = ( b'TShark 1...
Add an example of a generator->freevar->cell->generator reference-cycle that doesn't get cleaned up and thus leaks.
# This leaks since the introduction of yield-expr and the use of generators # as coroutines, trunk revision 39239. The cycle-GC doesn't seem to pick up # the cycle, or decides it can't clean it up. def leak(): def gen(): while True: yield g g = gen()
Add bitmask for subscribed events to intervention table.
from alembic import op import sqlalchemy as sa """empty message Revision ID: 91351a73e6e2 Revises: 63262fe95b9c Create Date: 2018-03-08 15:34:22.391417 """ # revision identifiers, used by Alembic. revision = '91351a73e6e2' down_revision = '63262fe95b9c' def upgrade(): # ### commands auto generated by Alembic...
Revert "Remove non-existing field from WeightBasedForm"
from django import forms from oscar.core.loading import get_model class WeightBasedForm(forms.ModelForm): class Meta: model = get_model('shipping', 'WeightBased') fields = ['description', 'default_weight', 'countries'] class WeightBandForm(forms.ModelForm): def __init__(self, method, *arg...
from django import forms from oscar.core.loading import get_model class WeightBasedForm(forms.ModelForm): class Meta: model = get_model('shipping', 'WeightBased') fields = ['name', 'description', 'default_weight', 'countries'] class WeightBandForm(forms.ModelForm): def __init__(self, meth...
Update null log handling for py26
# flake8: noqa from .extension import ExtensionManager from .enabled import EnabledExtensionManager from .named import NamedExtensionManager from .hook import HookManager from .driver import DriverManager import logging # Configure a NullHandler for our log messages in case # the app we're used from does not set up ...
# flake8: noqa __all__ = [ 'ExtensionManager', 'EnabledExtensionManager', 'NamedExtensionManager', 'HookManager', 'DriverManager', ] from .extension import ExtensionManager from .enabled import EnabledExtensionManager from .named import NamedExtensionManager from .hook import HookManager from .dri...
Add a simple single-frame data acquisition example
from pymoku import Moku, MokuException, NoDataException from pymoku.instruments import * import time, logging, traceback logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the I...
Add some tests of SecurityAnnounceParser
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from DebianChangesBot.mailparsers import SecurityAnnounceParser as p class TestMailParserSecurityAnnounce(unittest.TestCase): def setUp(self): self.h...
Add plotting of launch times
# Helper script for making run-time plots. # # Requires a Python installation with the full numeric stack (Numpy, Matplotlib) # including Seaborn (for prettier plots). # # Eli Bendersky [http://eli.thegreenplace.net] # This code is in the public domain. import numpy as np import matplotlib.pyplot as plt import seaborn ...
Create StoredMessageMapper from MessageStorageHandler code
class StoredMessageMapper: def from_api(self, message): data = message.data.copy() self.__replace_with_id_if_present(data, "from") self.__replace_with_id_if_present(data, "forward_from") self.__replace_with_id_if_present(data, "reply_to_message", "message_id") self.__delete_i...
Add tests for SA synonym
import sqlalchemy as sa from sqlalchemy.ext.hybrid import hybrid_property from wtforms_alchemy import ModelForm from tests import ModelFormTestCase class TestSynonym(ModelFormTestCase): def test_synonym_returning_column_property(self): class ModelTest(self.base): __tablename__ = 'model_test' ...
Add an example of interop with descartes and matplotlib
import logging import sys from matplotlib import pyplot from descartes import PolygonPatch from fiona import collection BLUE = '#6699cc' fig = pyplot.figure(1, figsize=(6, 6), dpi=90) ax = fig.add_subplot(111) input = collection("docs/data/test_uk.shp", "r") for f in input: patch = PolygonPatch(f['geometry'],...
ADD Network roles unit tests
def test_create_role(client): result = client.post("/roles/", data={"role": "admin"}) assert result.status_code == 200 assert result.get_json() == {"msg": "Role created succesfully!"} def test_get_all_roles(client): result = client.get("/roles/") assert result.status_code == 200 assert result....
Add a command line tool for reverse port forwarding
#!/usr/bin/env python # # Copyright (c) 2013 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. """Command line tool for forwarding ports from a device to the host. Allows an Android device to connect to services running on ...
Test cases for UrbanDict plugin
#!/usr/bin/env python ### # Copyright (c) 2004, Kevin Murphy # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # t...
Add fake params from test.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os DATASET_PATH = os.path.join( os.path.dirname(__file__), 'test_dataset', ) DATASET_SUBDIRS = [ { 'name': 'enron1', 'total_count': 5, 'ham_count': 3, 'spam_count': 2, 'path': os.path.join(DATASET_PATH, 'enron1'...
Add a Nano installer for Windows
#!/usr/bin/env python """Software Carpentry Nano Installer for Windows Installs nano and makes it the default editor in msysgit To use: 1. Install Python 2. Install msysgit http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git 3. Run swc_nano_installer.py You should be able to simply d...
Add extension to search JIRA for bug reports
import re import urllib.parse from discord.ext import commands from discord.ext.commands import Context from cogbot.cog_bot import CogBot class Jira: REPORT_PATTERN = re.compile('^(mc-)?(\d+)$', re.IGNORECASE) def __init__(self, bot: CogBot, ext: str): self.bot = bot @commands.command(pass_con...
Add basic api version test coverage
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Add testcase for pow builtin
# adapted from cython/tests/run/builtin_pow.pyx """ >>> pow3(2,3,5) 3 >>> pow3(3,3,5) 2 >>> pow3_const() 3 >>> pow2(2,3) 8 >>> pow2(3,3) 27 >>> pow2_const() 8 """ @autojit(backend='ast') def pow3(a,b,c): return pow(a,b,c) @autojit(backend='ast') def pow3_const(): return pow(2,3,5) @autojit(backend='ast')...
Add subprocess trial for webserver app
import subprocess import datetime from flask import Flask, render_template, redirect, url_for, request app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/outlet') def rf_outlet(): return render_template('rf-outlet.html') @app.route('/hello/<name>') def he...
Include script to get users from jamdb lookit
import requests import json JAMDB_AUTHORIZATION_TOKEN = 'JWT_SECRET_TOKEN' # To set this make this request # POST https://metadata.osf.io/v1/auth # # { # "data": { # "type": "users", # "attributes": { # "provider": "osf", # "access_token": "PERSONAL_ACCESS_TOKEN" # } # } # } # Fill this in ...
Add a script to generate a tinyquery table literal from data in bigquery
#!/usr/bin/env python """Use real bigquery data to create a tinyquery table. This makes it easier to generate tests for existing queries, since we don't have to construct the data by hand. Yay! We assume that you've created application default gcloud credentials, and that you have the project set to the one you want...
Add script to make cbr archive out of jpegs
#!/usr/bin/env python from __future__ import print_function from path import Path import sys import subprocess import re for d in sys.argv[1:]: filename = re.sub('\.?(/Check me|pdf|rar)$', '', d) + ".cbr" dir = Path(d) jpgs = dir.files('*.jpg') + dir.files('*.jpeg') if len(jpgs) < 10: print('n...
Add integration test for plotting utilities
"""Integration tests for plotting tools.""" from emdp import examples from emdp.gridworld import GridWorldPlotter from emdp import actions import random import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def test_plotting_integration(): mdp = examples.build_SB_example35() trajectories = ...
Add a session based source
from zope.interface import implementer from .interfaces ( IAuthSourceService, ) @implementer(IAuthSourceService) class SessionAuthSource(object): """ An authentication source that uses the current session """ vary = () value_key = 'sanity.value' def __init__(self, context, request): ...
Put in sanity-check for project scores.
from toolshed.importer import create_project from toolshed.updater import update_projects_score def test_oauth_rankings(): flask_dance = create_project(pypi_url="https://pypi.python.org/pypi/Flask-Dance", github_url="https://github.com/singingwolfboy/flask-dance") flask_oauth = create_project(pypi_url="https:...
Add generic settings-related GUI util module
# gui.py # Generic GUI crap from gi.repository import Gtk class CheckEntry(Gtk.Box): def __init__(self, labeltxt, togglef = None): Gtk.Box.__init__(self, spacing=2) self.label = Gtk.Label(labeltxt, valign=0) self.check = Gtk.CheckButton() self.pack_start(self.check, True, T...
Add new illustrative test: monkeypatching stdout
import sys import io import hacks def test_stdout_monkeypatching(): # Let's first patch stdout manually: real_stdout = sys.stdout fake_stdout = io.StringIO() sys.stdout = fake_stdout # While it is monkey-patched, other users print('Hello') # may write something else into out fake...
Create basic user agent spoofer with Mechanize
#!/usr/bin/env import mechanize def test_agent(url, user_agent): browser = mechanize.Browser() browser.addheaders = user_agent page = browser.open(url) source_code = page.read() print source_code user_agent = [('User-agent','Mozilla/5.0 (X11; U; Linux 2.4.2-2 i586; en-US; m18) Gecko/20010131 Nets...
Add script to generate lognormal fits of GIS response data.
import click import pandas from scipy.stats import lognorm @click.command() @click.argument('filename') @click.option('--column', default='Total_Trav', help='Column to identify shape, location, and scale from.') def response_time_dist(filename, column): """ Returns the lognormal distribution fit of travel time...
Add draft of wrapper script
import sys import os import subprocess import json from scipy import stats from argparse import ArgumentParser parser = ArgumentParser(description="Get Ideogram.js annotations for an SRR") parser.add_argument("--acc", required=True, help="SRR accession") args = parser.parse_args() acc = args.acc out = acc + "_counts"...
Add utility to split mirax data files
#!/usr/bin/python import struct, sys, os def rr(f): return struct.unpack("<i", f.read(4))[0] filename = sys.argv[1] f = open(filename) dir = os.path.dirname(filename) HEADER_OFFSET = 37 f.seek(HEADER_OFFSET) filesize = os.stat(sys.argv[1]).st_size num_items = (filesize - HEADER_OFFSET) / 4 # read first po...
Fix backward incompatility. This module is deprecated and will be removed in version 2.2
""" Deprecated; the PyCodeEdit class has been moved into pyqode.python.widgets. This file will be removed in the next minor version (2.2). """ from .widgets.code_edit import PyCodeEdit __all__ = [ 'PyCodeEdit' ]
Add tests for label management
import steel import unittest class FieldTests(unittest.TestCase): def test_auto_label(self): # One word field = steel.Bytes(size=1) field.set_name('byte') self.assertEqual(field.label, 'byte') # Two words field = steel.Bytes(size=1) field.set_name('two_byte...
Add example to list IAM users with service resource
# Copyright 2010-2018 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ac...
Solve Code Fights kth permutation problem
#!/usr/local/bin/python # Code Fights Kth Permutation Problem from itertools import permutations def kthPermutation(numbers, k): return list(list(permutations(numbers, len(numbers)))[k - 1]) def main(): tests = [ [[1, 2, 3, 4, 5], 4, [1, 2, 4, 5, 3]], [[1, 2], 1, [1, 2]], [[11, 22, ...
Implement a script for extracting profile data from device output
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """Parse device output to extract LLVM profile data. The profile data obtained from the device is raw. Thus, it must be indexed before it can be used...
Convert arrows notebook to importable py file
import numpy as np import plotly.graph_objs as go def p2c(r, theta, phi): """Convert polar unit vector to cartesians""" return [r * np.sin(theta) * np.cos(phi), r * np.sin(theta) * np.sin(phi), r * np.cos(theta)] class Arrow: def __init__(self, theta, phi, out, width=5, color='rgb(0,0...
Add substitution and scrape_header tests
from utils import LinkTest, main import re class SubstitutionTest(LinkTest): def testSubstititonFunction(self): text = """ <pattern> """ subs = [ (r"<pattern>", lambda m: 'Hello world!') ] expect = """ Hello world! """ self.assertS...
Create app to record Pi Sense data
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger DEVICE = "PiSense" class Handler: def __init__(self, display, logger, sensor): self.display = display self.logger = logger se...
Add a test for configuration argument
import os import subprocess PROJECT_DIR = os.getcwd() TEST_PROJECT_DIR = os.path.join(PROJECT_DIR, 'test_project') def test_configuration_argument_in_cli(): """Verify that's configuration option has been added to managements commands""" os.chdir(TEST_PROJECT_DIR) p = subprocess.Popen(['python', 'manage.p...
Add unit tests for the filter module.
#!/usr/bin/env python from numpy import all, allclose, array, float32 from .. import filter x = array([ [0, 1, 0], [1, 1, 1], [0, 1, 0], ], dtype=float32) def test_low_pass_filter(): y = filter._low_pass_filter(x.shape, 1) assert all(x == y) z = filter._high_pass_filter(x.shape, 1) ass...
Add Python implementation for problem 2
f1, f2, s, n = 0, 1, 0, 4000000 while f2 < n: f2, f1 = f1, f1 + f2 if f2 % 2 == 0: s += f2 print s
Add a new variant of WaterButlerPath
import os class WaterButlerPathPart: DECODE = lambda x: x ENCODE = lambda x: x def __init__(self, part, _id=None): self._id = _id self._part = part @property def identifier(self): return self._id @property def value(self): return self.__class__.DECODE(self...
Add a decorator for requiring a specific type
#!/usr/bin/env python class RequiresType(object): """ Checks that the first (or position given by the keyword argument 'position' argument to the function is an instance of one of the types given in the positional decorator arguments """ def __init__(self, *types, **kwargs): self.type...
Split support for suplots into a MultiGraph subclass
""" An extension of a standard cligraph for plotting graphs with subplots using gridspec """ import matplotlib import matplotlib.gridspec as gridspec from cligraph import CLIgraph class MultiGraph(CLIgraph): def __init__(self, num_plots_x, num_plots_y, **kwargs): super(MultiGraph, self).__init__(**kwar...
Add tests for diango-comment-client middleware
import string import random import collections from django.test import TestCase import comment_client import django.http import django_comment_client.middleware as middleware class AjaxExceptionTestCase(TestCase): # TODO: check whether the correct error message is produced. # The error mes...
Add function to remove duplicates from a string
''' In this module we remove duplicates in a string ''' def remove_duplicates(string): ''' Remove duplicated characters in string ''' result = [] seen = set() for char in string: if char not in seen: seen.add(char) result.append(char) return ''.join(result)
Add modeladmin entry for animals
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from bvspca.animals.models import Animal class AnimalModelAdmin(ModelAdmin): model = Animal menu_label = 'Animals' menu_icon = 'fa-paw' menu_order = 100 add_to_settings_menu = False list_display = ('title', 'petpoi...
Add test for asserting downloaded files
from seleniumbase import BaseCase class DownloadTests(BaseCase): def test_download_files(self): self.open("https://pypi.org/project/seleniumbase/#files") pkg_header = self.get_text("h1.package-header__name") pkg_name = pkg_header.replace(" ", "-") whl_file = pkg_name + "-...
Add test for ActionsQueueConsumer class which verifies that the right BufferedDispatcher class is used.
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Remove Element -- keep streak!
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): result = len(A) start = 0 for i in xrange(len(A)): A[start] = A[i] if A[i] != elem: ...
Work on the document list view
from django.views.generic import DetailView from django.views.generic import ListView from mongonaut.sites import NautSite class IndexView(ListView): queryset = NautSite._registry.iteritems() template_name = "mongonaut/index.html" class AppListView(ListView): """ :args: <app_label> """ template_name...
import importlib from django.views.generic import DetailView from django.views.generic import ListView from mongonaut.sites import NautSite class IndexView(ListView): queryset = NautSite._registry.iteritems() template_name = "mongonaut/index.html" class AppListView(ListView): """ :args: <app_label> """ ...
Add initial EPSFBuilder and EPSFFitter classes
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tools to build an ePSF. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from astropy.modeling.fitting import LevMarLSQFitter from astropy.stats import SigmaClip __all__ = ['EPSFFitter...
Add simple tests for MessagePacket
from cactusbot.packets import MessagePacket def _split(text, *args, **kwargs): return [ component.text for component in MessagePacket(text).split(*args, **kwargs) ] def test_split(): assert _split("0 1 2 3") == ['0', '1', '2', '3'] assert _split("0 1 2 3", "2") == ['0 1 ', ...
Test install numpy and biopython for RTD
from setuptools import setup setup(name='', version='0.1', description='', url='', author='', author_email='', packages=[''], install_requires=[ 'numpy', 'biopython' ], zip_safe=False)
Create test class for merge function
import unittest, pyPdf, sys, os.path from mock import Mock SRC = os.path.join(os.path.dirname(__file__), '..', 'src') sys.path.append(SRC) import merge class MockPdfReader: def __init__(self): self.pages = [None] * 3 def getNumPages(self): return len(self.pages) def getPage(self, page_num): pass clas...
Add super-simple automatic AndroidManifest.xml updater.
#!/usr/bin/env python import os import re repo = os.path.dirname(os.path.realpath(__file__)) code = 'android:versionCode="%s"' name = 'android:versionName="%s"' in_code = code % r'(\d+)' in_name = name % r'([^"]+)' new_code = None new_name = None for dirpath, dirnames, filenames in os.walk(repo): for filename i...
Put up a structure to extraction library.
""" ### CODE OWNERS: Shea Parkes ### OBJECTIVE: Extraction methods for relevant items. ### DEVELOPER NOTES: <none> """ import typing from collections import OrderedDict from fhirclient.client import FHIRClient # ============================================================================= # LIBRARIES, LOCATION...
Add python utility to adjust timelines
#!/usr/bin/python from __future__ import print_function import argparse import re time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"") first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)") def adjust_lines(lines, adjust): for line in lines: match = re.match(time_re, line) if match: time = float...
Add new command line tool for injesting from YAML description to NetCDF
import click import os import os.path import yaml from create_tiles import calc_target_names, create_tiles from geotiff_to_netcdf import create_or_replace from pprint import pprint def read_yaml(filename): with open(filename) as f: data = yaml.load(f) return data def get_input_files(input_file,...
Remove the only remaining reference to `u'` string prefix
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.t...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(os.getcwd())))) sys.path.insert(0, os.path.abspath(os.getcwd())) extensions = ['powerline_autodoc', 'sphinx.ext.t...
Change style for each execution of the experiment
#!/usr/bin/env python3 import subprocess import os img_dir = 'samples/' out_dir = 'outputs/' ext = '.jpg' sem_ext = '.png' c_images = ['arthur', 'matheus', 'sergio', 'morgan'] s_image = 'morgan' content_weight = 15 style_weight = 10 iterations = 200 ### Create outputs' folder if it doesn't exist if not os.path.exist...
Add test for random number generators.
""" Random and quasi-random generator tests. """ from __future__ import division from __future__ import absolute_import from __future__ import print_function import numpy.testing as nt from mwhutils.random import rstate from mwhutils.random import uniform, latin, sobol def test_rstate(): """Test the rstate hel...
Add multiline echo server example script
#!/usr/bin/env python from gaidaros import * server = Gaidaros(end_request = lambda x: '\n\n' in x, split_request = lambda x: return(x[:x.find('\n\n') + 1], x[x.find('\n\n') + 1:])) server.serve()
Add a few fizz buzz attempts
#!/usr/bin/env python # pylint: disable=C0111 # pylint: disable=C0103 # pylint: disable=C0330 MAX = 31 def simple(): print ('--- SIMPLE -----') for i in range(1, MAX): output = '' if i % 3 == 0: output += 'Fizz' if i % 5 == 0: output += 'Buzz' if not out...
Add custom time picker control
"""Custom time picker that allows us control of the control's color.""" from wx.lib.masked import TimeCtrl from ... util import rgba import wx class TimePickerCtrl(TimeCtrl): """Time picker that we can force proper colors on.""" def __init__(self, parent, *args, **kwargs): """ Initialize. ...
Add Kivy version of live audio stream
''' kivy requires some library installation ''' import matplotlib matplotlib.use('module://kivy.garden.matplotlib.backend_kivy') import matplotlib.pyplot as plt import kivy kivy.require('1.10.0') # replace with your current kivy version ! from kivy.app import App from kivy.uix.button import Button from kivy.uix.box...
Add a single-line code golf example
print (reduce(lambda string, tup: string + tup[0] + ' - ' + str(tup[1]) + '\n', sorted( filter(lambda tup: tup[0] not in open('../stop_words.txt').read().lower().split(','), reduce(lambda word_dict, word: word_dict if (word_dict.__setitem__(word, word_dict.get(word, 0) + 1) if True else None) else word_dict, filter(la...
Add an example to compare Gamma and Spline
""" This test file is meant for developing purposes. Providing an easy method to test the functioning of Pastas during development. """ import pandas as pd import pastas as ps ps.set_log_level("ERROR") # read observations and create the time series model obs = pd.read_csv("data/head_nb1.csv", index_col=0, parse_dat...
Add script to generate wiki command documentation
# Script to generate contents of https://github.com/Duke-GCB/DukeDSClient/wiki/All-Commands from ddsc.ddsclient import DDSClient from ddsc.versioncheck import get_internal_version_str from argparse import SUPPRESS import sys # Fix argparse to have ddsclient instead of generatedocs.py as the command sys.argv[0] = 'ddsc...
Add nb-NO to bb-NO macro(Created by Karel)
""" nb-NO to nn-NO Metadata Macro will perform the following changes to current content item: - change the byline to "(NPK-NTB)" - change the body footer to "(©NPK)" - NB: copyrightsign, not @ - change the service to "NPKSisteNytt" """ def nb_NO_to_nn_NO_metadata_macro(item, **kwargs): it...
Test for adding products to the quote list
import time import unittest from selenium import webdriver from selenium.webdriver.common.by import By class TestAddproduct(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("http://localhost:9761/pricing_quote") time.sleep(1) def tearDown(self): ...
Add n9k IP iptables block
def start(context, log, args): import time duration = args['duration'] period = 20 n9k1_ip, n9k2_ip, _, _ = context.n9k_creds() log.info('Blocking N9K IPs ({0},{1}) on controllers ...'.format(n9k1_ip, n9k2_ip)) start_time = time.time() for controller in context.controllers(): cont...
Add migration file for metadata descriptor
"""empty message Revision ID: a65bdadbae2f Revises: e1ef93f40d3d Create Date: 2019-01-15 12:19:59.813805 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import postgresql import sqlalchemy_utils import uuid # revision identifiers, used by Alembic. revision = 'a65bd...
Test for multithreading with twisted framework
""" This file implements testing ing langcodes module for multithreaded env Problem is still there if you try to acccess that module from multiple places at once """ import threading from twisted.internet import reactor from tag_parser import parse_tag def parseMe(i, tag): print i, parse_tag(tag) def startPro...
Add a test to check if an optical mouse can be used as a course sensor
from pymouse import PyMouse import time # This script demonstrates the possibility to use a mouse as an unbound sensor. # To do that the cursor position is brought back to the middle of the screen at each step, and the distance moved by the mouse are integrated # This script is intended to be used with a second externa...
Add conf file for BabyLab KoomBook
# -*- coding: utf-8 -*- """KoomBook conf""" from .kb import * # noqa from django.utils.translation import ugettext_lazy as _ LANGUAGE_CODE = 'fr' IDEASCUBE_NAME = 'BabyLab' HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'mediacenter', }, { 'id': 'bsfcampus', ...
Add test file for COPY client
import os import pytest import time from carto.exceptions import CartoException from carto.sql import SQLClient, BatchSQLClient, CopySQLClient SETUP_QUERIES = [ 'DROP TABLE IF EXISTS carto_python_sdk_copy_test', """ CREATE TABLE carto_python_sdk_copy_test ( the_geom geometry(Geometry,4326), n...
Add two new letter logos
"""empty message Revision ID: 0225_another_letter_org Revises: 0224_returned_letter_status """ # revision identifiers, used by Alembic. revision = '0225_another_letter_org' down_revision = '0224_returned_letter_status' from alembic import op NEW_ORGANISATIONS = [ ('512', 'Vale of Glamorgan'), ('513', 'Rot...
Add a sinus utilities for the servo module.
from __future__ import division from threading import Thread from time import time, sleep from math import sin, pi class Sinus(object): update_frequency = 25.0 def __init__(self, motor, frequency, amplitude, offset, phase): self.motor = motor self.frequency = frequency self.amplitud...
Add task to upload a dir to S3
import os import boto from boto.utils import compute_md5 from fabric.decorators import task from fabric.utils import puts def upload_file(bucket, key_name, file_path, policy='public-read'): key = bucket.new_key(key_name) fd = open(file_path) md5 = compute_md5(fd) fd.close() key.set_metadata('fabi...