Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add tests for treecache directly and test del_multi at the LruCache level too.
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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 applica...
Add a script to download all the fully free tracks from Jamendo (as Ogg Vorbis)
#!/usr/bin/env python # Jamendo database dumps can be fetched from: http://img.jamendo.com/data/dbdump_artistalbumtrack.xml.gz import xml.etree.cElementTree as ElementTree import sys, gzip, time, os.path, urllib class DownloadJamendo: def __init__(self, destination): if not os.path.exists(destination): os.m...
Add script for converting kanjidic2
#!/usr/bin/env python2 import json with open("kanjidic2.json", "rb") as f: raw = f.read() kanjidic2 = json.loads(raw) # Makes a dictionary where each key is a kanji, instead of a big list of objects transformed = {kanjidic2[i]["literal"]: kanjidic2[i] for i in xrange(len(kanjidic2))} with ope...
Test driver for Voronoi stream power
from landlab import VoronoiDelaunayGrid # , RasterModelGrid from landlab.components.flow_routing.route_flow_dn import FlowRouter from landlab.components.stream_power.stream_power import StreamPowerEroder import numpy as np x, y = np.random.rand(50), np.random.rand(50) mg = VoronoiDelaunayGrid(x,y) #mg = RasterModelGr...
Add python file that is triggered when saving a file
import sublime import sublime_plugin import re class LevureAppNotify(sublime_plugin.EventListener): def on_post_save(self, view): # 1. Get script only stack name. line 1: script "Name" [done] # 2. Get project key from project settings # 3. Send notification over socket with project key and ...
Write a PRNG datapoint every second
from datetime import datetime from time import sleep import random from tempodb import Client, DataPoint import tempodb from os import getenv API_KEY = getenv('API_KEY') assert API_KEY, "API_KEY is required" API_SECRET = getenv('API_SECRET') assert API_SECRET, "API_SECRET is required" SERIES_KEY = getenv('SERIES_KEY...
Add unit tests for AtomicValue methods.
# Copyright 2012 The scales Authors. # # 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 w...
Add test case for email unique validate
from account.models import EmailAddress from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.forms import ValidationError from django.test import TestCase, override_settings @override_settings(ACCOUNT_EMAIL_UNIQUE=True) class UniqueEmailAddressTestCase(TestCase): de...
Add initial version of parsing application
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from parsers.main_parser import MainParser if __name__ == '__main__': src = r"D:\nhl\official_and_json\2016-17\2017-02\2017-02-01.zip" # src = r"D:\nhl\official_and_json\2016-17\2017-02\2017-02-20" # src = r"D:\nhl\official_and_json\_2015-16\2016-...
Add script to test RF performance on gala data
# IPython log file from gala import classify datas = [] labels = [] import numpy as np list(map(np.shape, labels)) for i in range(3, 4): data, label = classify.load_training_data_from_disk('training-data-%i.h5' % i, names=['data', 'labels']) datas.append(data) labels.append(label[:, 0]) X0 = np.conca...
Add test for `tldr find {{command}}`
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import import os from os import path import unittest from click.testing import CliRunner import mock from tldr import cli class TestFind(unittest.TestCase): def setUp(self): self.runner = CliRunner() with mock.patch(...
Add sketch of script for getting images and verdict data from site
from __future__ import with_statement import urllib2, os, cStringIO from bs4 import BeautifulSoup from collections import defaultdict DATA_DIR = 'data/' IMG_DIR = 'data/images/' DATA = 'data/testdata' INTO_YOU = 'into you' NOT_INTO_YOU = 'not into you' VERDICT_STILL_OUT = 'verdict still out' verdict_map = {"He's into...
Move the basic job processor into a django management command as well.
import zmq import time import json from django.core.management.base import NoArgsCommand addr = 'tcp://127.0.0.1:5555' class Command(NoArgsCommand): help = "Run the 0MQ based job processor. Accepts jobs from the job server and processes them." def handle(self, **options): context = zmq.Context() ...
Add ResourceParameter class and subclasses to store parameter info
from lxml import etree from django.utils.translation import ugettext as _ class ResourceParameter(object): def __init__(self, name="", description=""): self.name = name self.description = description def html_element(self): legend = etree.Element('legend') legend.text = self.de...
Add missed file from previous commit
'''Some utilitary classes usually used to make working with different python versions and different environment easier: string_types - basestring for python 2 and str fot python 3 dict_keys - convert dict keys to list div_operators - operators for division with_metaclass - metaclasses ''' import sys im...
Add a unittest for spacegroup. Still very basic.
#!/usr/bin/env python ''' Created on Mar 12, 2012 ''' from __future__ import division __author__="Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyue@mit.edu" __date__ = "Mar 12, 2012" import unittest import os from pymatg...
Add script to impute name parts
""" """ from framework.auth.utils import parse_name from website.app import init_app from website import models app = init_app('website.settings', set_backends=True, routes=True) def impute_names(): for user in models.User.find(): parsed = parse_name(user.fullname) for field, value in parsed....
Add one more empty line to end of import to adjust to H306
#!/usr/bin/env python import argparse import sys import cv2 import numpy import six.moves.cPickle as pickle parser = argparse.ArgumentParser(description='Compute images mean array') parser.add_argument('dataset', help='Path to training image-label list file') parser.add_argument('--output', '-o', default='mean.npy', ...
#!/usr/bin/env python import argparse import sys import cv2 import numpy import six.moves.cPickle as pickle parser = argparse.ArgumentParser(description='Compute images mean array') parser.add_argument('dataset', help='Path to training image-label list file') parser.add_argument('--output', '-o', default='mean.npy',...
Add tool for subsetting symbols.
#!/usr/bin/python # # Copyright 2014 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 by...
Use mitmproxy to get basic information
# Run this with mitmdump -q -s morph_proxy.py def request(context, flow): # print out all the basic information to determine what request is being made # coming from which container # print flow.request.method # print flow.request.host # print flow.request.path # print flow.request.scheme # print flow.re...
Add helper to get the coin price
import json import requests def get_coin_price(coin_name): url = "https://bittrex.com/api/v1.1/public/getticker?market=USDT-{}".format(coin_name) data = requests.get(url).json() last_price = data.get("result").get("Last") data = json.dumps({ coin_name: last_price }) return data
Add module for atomic file writes and waits
import os from tempfile import mkstemp import time class atomic_write(object): """Perform an atomic write to a file. Use as:: with atomic_write('/my_file') as f: f.write('foo') """ def __init__(self, filepath): """ :type filepath: str """ self.fi...
Add autonym and synonym commands
from difflib import get_close_matches import discord from pcbot import Annotate import plugins client = plugins.client def load_wordlist(filename: str): with open("plugins/wordlib/SimpleWordlists/Thesaurus-" + filename + ".txt") as f: return {k: v.split(",") for k, v in [line.split("|") for line in f.re...
Add module for enumerating direction types and converting angles into them.
# coding=utf-8 # Copyright 2020 Google LLC # 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 ...
Add a specification for the pb_type.xml generator
#!/usr/bin/python3 import yosys_exec import lxml.etree as ET import argparse, re import os, tempfile from yosys_json import YosysJson """ Convert a Verilog simulation model to a VPR `pb_type.xml` The following Verilog attributes are allowed on instances: - (* PB_PATH="../path/to/pb_type.xml" *) : import the pb_ty...
Add browser test for admin menu
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import os import pytest from shuup.testing.browser_utils import w...
Change minimisation example mif name
def main(): from sim import Sim from mesh import Mesh from energies.exchange import Exchange from energies.demag import Demag from energies.zeeman import Zeeman from drivers import evolver # Mesh specification. lx = ly = lz = 50e-9 # x, y, and z dimensions (m) dx = dy = dz = 5e-9 #...
def main(): from sim import Sim from mesh import Mesh from energies.exchange import Exchange from energies.demag import Demag from energies.zeeman import Zeeman from drivers import evolver # Mesh specification. lx = ly = lz = 50e-9 # x, y, and z dimensions (m) dx = dy = dz = 5e-9 #...
Add script for downloading data sets
import argparse import subprocess as sp import os """ Script for downloading the data sets from Kaggle Usage: python download_data.py Run python download_data.py --help for help on the usage of command line arguments Note: Kaggle requires a user to accept the rules of a competition before they can downloa...
Add some tests for variables
import unittest from mo.runner import Variable class TestVariable(unittest.TestCase): def test_default(self): v = Variable('name', {'default': 'default'}) self.assertEqual(v.value, 'default') self.assertEqual(str(v), 'default') def test_value(self): v = Variable('name', {'def...
Add new test for android web view.
import os import glob import unittest from time import sleep from selenium import webdriver class TestAndroidWebView(unittest.TestCase): def setUp(self): app = os.path.abspath( glob.glob(os.path.join(os.path.dirname(__file__), '../../apps/WebViewDemo/target'...
Add test view for debugging
from flask.ext.restful import Resource, abort from finder.models import Card from finder import api #fields, marshal_with #gen_fields = { # 'key': fields.Raw, # 'salt': fields.Raw, # 'expiration': fields.Raw #} class Greet(Resource): #@marshal_with(gen_fields) def get(self, name): if name ...
Add conf file for Avanti KoomBook
# -*- coding: utf-8 -*- """KoomBook conf""" from .kb import * # noqa LANGUAGE_CODE = 'es' IDEASCUBE_NAME = 'Avanti' HOME_CARDS = STAFF_HOME_CARDS + [ { 'id': 'blog', }, { 'id': 'mediacenter', }, { 'id': 'gutenberg', 'lang': 'es', }, { 'id': 'wikipedi...
Add dist-utils support for gentoo ebuild
#!/usr/bin/env python """Setup script for the kconfiglib module.""" from distutils.core import setup setup (# Distribution meta-data name = "kconfiglib", version = "0.0.1", description = "A flexible Python Kconfig parser", author = "Ulfalizer Magnusson", author_email = "kconfiglib@...
Implement first version of LR classifier
import numpy as np import pylab as pl import feature_extractor as fe from sklearn import linear_model (features, targets) = fe.extract_train() (features_test, targets_test) = fe.extract_test() classifier = linear_model.LogisticRegression(C = 1e5, tol = 0.0001) classifier.fit(features, targets) target_test_hat = clas...
Add mostly empty unit tests
#!/bin/python2.7 import mock import unittest import api_calls class FakeFirebase(object): def get(self, path, item): return None def put(self, path, item, data): return None def patch(self, path, data): return None class TestApiCalls(unittest.TestCase): def setUp(self): self.db = FakeF...
Add test for atomicity of renames of non-empty directories
import errno import multiprocessing import os import tempfile from functools import partial from toil.test import ToilTest class SystemTest(ToilTest): """ Test various assumptions about the operating system's behavior """ def testAtomicityOfNonEmptyDirectoryRenames(self): for _ in range(100):...
Add marker for 104th error
"""Marks all fixed errors #104 on ruwiki's CheckWikipedia.""" import re import pywikibot from checkwiki import load_page_list, mark_error_done, log NUMBER = "104" REGEXP = r"<ref\s+name=\s*(.*?)\s*(?:group=.*?)?\s*/?>" FLAGS = re.I def main(): """Downloads list from server and marks relevant errors as d...
Add a stub fake ICE peripheral
#!/usr/bin/env python MAX_GPIO = 24 import serial s = serial.Serial('/tmp/com2', 115200) if not s.isOpen(): raise IOError, "Failed to open serial port" GPIO_INPUT = 0 GPIO_OUTPUT = 1 GPIO_TRISTATE = 2 event = 0 gpio_level = [False for x in xrange(MAX_GPIO)] gpio_dir = [GPIO_TRISTATE for x in xrange(MAX_...
Add a create page test
from django.test import TestCase from pages.models import * from django.test.client import Client class PagesTestCase(TestCase): fixtures = ['tests.json'] def test_01_add_page(self): """ Test that the add admin page could be displayed correctly """ c = Client() c.login(...
from django.test import TestCase from pages.models import * from django.test.client import Client class PagesTestCase(TestCase): fixtures = ['tests.json'] def test_01_add_page(self): """ Test that the add admin page could be displayed via the admin """ c = Client() c.l...
Add sample file with secrets (db credentials and secret_key).
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'HOST': '127.0.0.1', 'PORT': 5432...
Add script to split data into training and testing
# Copyright 2017 Rice University # # 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 writin...
Add `session` and `connection` fixtures
# Copyright (c) 2022. The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details from typing import cast import pytest from coverage.annotate import os from sqlalchemy import event from sql...
Add unit tests for udiskie.match
# encoding: utf-8 """ Tests for the udiskie.match module. These tests are intended to demonstrate and ensure the correct usage of the config file used by udiskie for custom device options. """ import unittest import tempfile import shutil import os.path import gc from udiskie.match import OptionFilter, FilterMatche...
Add tests for utl module
import os from aiodownload.util import clean_filename, make_dirs, default_url_transform def test_clean_filename(): sanitized_filename = clean_filename('français.txt') assert sanitized_filename == 'francais.txt' def test_make_dirs(tmpdir): test_path = os.path.sep.join([tmpdir.strpath, 'test', 'make',...
Return angle between 0 and 2pi
#!/usr/bin/env python import unittest from math import pi from orientation import get_angle_between_0_and_2_pi class OrientationTest(unittest.TestCase): def setUp(self): self.delta = 0.000001 def test_when_angle_is_between_0_and_2_pi_then_angle_is_returned(self): angle = 50 * pi / 180.0 ...
Remove old type of image hashes
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def delete_imageinfo(apps, schema_editor): ImageInfo = apps.get_model('core.ImageInfo') ImageInfo.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('core', '00...
Add simple test for IP regex
import unittest from pycroft.helpers import net class IpRegexTestCase(unittest.TestCase): def test_ip_regex(self): regex = net.ip_regex self.assertTrue(regex.match("141.30.228.39")) self.assertFalse(regex.match("141.3330.228.39")) self.assertFalse(regex.match("141.3330.228.39.")) ...
Add some tests for DataHandler
import sys sys.path.append('..') import unittest from datahandler import data_handler_factory from sweep import Sweep class DataHandlerTestCase(unittest.TestCase): def setUp(self): path = 'C:/Dropbox/PhD/sandbox_phd/FolderBrowser/data/2016-09-19#015' self.sweep = Sweep(path) data = self.sw...
Declare number of Networks used during testing
import pandana.network as pdna # Pandana uses global state for networks, # so we have to pre-declare here how many networks will be # created during testing. # # If you see an error that looks like: # AssertionError: Adding more networks than have been reserved # then you probably need to update this number. num_n...
Add unit tests for _compat.py
# -*- coding: utf-8 -*- ''' Unit tests for salt.config ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import sys # Import Salt Testing libs from tests.support.helpers import with_tempdir, with_tempfile, destructiveTest from tests.support.mixins import ...
Add work from exercise 21 in lpthw.
def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a -b def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a / b print "Let's do som...
Add ass3 work until question 7, Come up with both iterative and analytical growth function for the two interval problem
import numpy as np from scipy.special import comb def hoeffding_inequality_sample_size_needed(probability, error, num_hypothesis): return np.log(probability/2/num_hypothesis)/-2/error**2 def question_one_two_three(): return hoeffding_inequality_sample_size_needed(0.03, 0.05, 1), hoeffding_inequality_sample_siz...
Add script to get all memories
import argparse import os parser = argparse.ArgumentParser(description='Collect memories from a corpus') parser.add_argument('-c', '--corpus_dir', default='hp_corpus', type=str, help='Path to corpus directory') parser.add_argument('-n', '--name', default='harry potter', type=str...
Create a script for printing the chatroom topic with the next event.
import urllib import yaml from datetime import datetime from icalendar import Calendar # Load configuration data with open('config.yaml', 'r') as f: config = yaml.load(f) calendar = config['calendar'] topic_format = config['irc']['topic'] date_format = config['date_format'] def next_event(ical_url): raw_ics ...
Add first version of tests file
# -*- coding: UTF-8 -*- from expects import * import xml.dom.minidom from sii.resource import SII from dicttoxml import dicttoxml class Period(): def __init__(self, name): self.name = name class Partner(): def __init__(self, name, nif): self.name = name self.nif = nif class Invoice...
Add simple tests that the release information exists
import pytest from magnate import release def test_release_info(): assert hasattr(release, 'AUTHOR') assert hasattr(release, 'MAINTAINER') assert hasattr(release, 'PROGRAM_NAME') assert hasattr(release, 'COPYRIGHT_YEAR') assert hasattr(release, 'LICENSE') def test_version_correct(): assert ...
Add test for math functions in nopython context.
import math import numpy as np import unittest #import logging; logging.getLogger().setLevel(1) from numba import * def test_exp(a): return math.exp(a) def test_sqrt(a): return math.sqrt(a) def test_log(a): return math.log(a) class TestNoPythonMath(unittest.TestCase): def test_sqrt(self): s...
Add new class to cache killmails indefinitely, forever
# -*- coding: utf-8 -*- import sqlite3 import json from classes.sitecfg import SiteConfig class KillMailsCache: def __init__(self, siteconfig: SiteConfig): self._conn = sqlite3.connect(siteconfig.ZKB_CACHE_DIR + '/killmails.db', check_same_thread=False) self.check_tables() def check_tables(se...
Add test for `refund_order` function of `facade` module
from decimal import Decimal as D from unittest.mock import patch from django.test import TestCase from paypalhttp.http_response import construct_object from paypal.express_checkout.facade import refund_order from paypal.express_checkout.models import ExpressCheckoutTransaction from .mocked_data import REFUND_ORDER_D...
Add `submitted_at` migration to `brief_responses` table
"""brief response submitted at Revision ID: 760 Revises: 750 Create Date: 2016-10-24 14:16:29.951023 """ # revision identifiers, used by Alembic. revision = '760' down_revision = '750' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('brief_responses', sa.Column('submitted_at', sa.D...
Add back catch_error which is used for CLI errors
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 applicab...
Add tests for additional functionality provided by NameAtomFeedType.
import pytest from django.core.urlresolvers import reverse from name.models import Name, Location pytestmark = pytest.mark.django_db def test_feed_has_georss_namespace(client): response = client.get(reverse('name_feed')) assert 'xmlns:georss' in response.content def test_feed_response_is_application_xml(...
Add a project in the 'incubator'.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org) # http://en.wikipedia.org/wiki/SubRip # http://forum.doom9.org/showthread.php?p=470941#post470941 # # srt format: # Subtitle number # Start time --> End time # Text of subtitle (one or more lines) # B...
Add script to do investment generation payment order
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from erppeek import Client import configdb import datetime ''' Script que agafa les inversions en esborrany i genera les factures de cobrament i les afegeix a la remesa. python admin/genkwh_remesa_cobrament_cron.py ''' def crear_remesa_generation(O):i ...
Create Naive Bayes vectorizer and classifier pickles
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.externals import joblib print "Grabbing data..." training_text_collection_f = open("training_text_collection.pkl", "rb") training_text_collection = joblib.load(training_text_collection_f) training_te...
Add helper script to sort svmlight files by column keys.
from sys import argv from operator import itemgetter if __name__ == "__main__": if (len(argv) != 3): print("Usage: " + argv[0] + " <input.svm> <output.svm>") print("Example:") print("input.svm:") print("1 24:1 12:1 55:1") print("0 84:1 82:1 15:1") print("...") ...
Add support for MPC package
import xyz import os import shutil class Mpc(xyz.BuildProtocol): pkg_name = 'mpc' deps = ['gmp', 'mpfr'] def configure(self, builder, config): builder.host_lib_configure(config=config) rules = Mpc()
Add one script to use AWS CLI to allocate/associate/release EIP automatically.
#!/usr/bin/python import commands counter =0 while counter <=100 : #alocate new Elastic IP, and get the allocation id (stauts,output) = commands.getstatusoutput("aws ec2 allocate-address") allocation_id = output.split('\t') [0] #associate the allocated ip to indicated ec2 instance (status,output) = commands....
Insert test run results to sqlite3 database
#!/usr/bin/env python import sys import optparse import sqlite3 from datetime import datetime from os.path import abspath, exists, join from xml.etree import ElementTree def main(): parser = _get_option_parser() options = _get_validated_options(parser) xml_tree = _get_xml_tree(options, parser) root_a...
Remove footer print and make file PEP8 compliant
from flask.ext.login import current_user from viaduct.models.page import Page, PagePermission, PageRevision from viaduct import db from flask import request, url_for, render_template from viaduct.models.group import Group class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter...
from flask.ext.login import current_user from viaduct.models.page import Page, PageRevision from viaduct import db from flask import render_template class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path == path).first() if not page: return False ...
Change name of compare function in test grid
import pytest from aimaPy.grid import * compare = lambda x, y: all([elm_x == y[i] for i, elm_x in enumerate(x)]) def test_distance(): assert distance((1, 2), (5, 5)) == 5.0 def test_distance_squared(): assert distance_squared((1, 2), (5, 5)) == 25.0 def test_clip(): list_ = [clip(x, 0, 1) for x in [-...
import pytest from aimaPy.grid import * compare_list = lambda x, y: all([elm_x == y[i] for i, elm_x in enumerate(x)]) def test_distance(): assert distance((1, 2), (5, 5)) == 5.0 def test_distance_squared(): assert distance_squared((1, 2), (5, 5)) == 25.0 def test_clip(): list_ = [clip(x, 0, 1) for x ...
Add script for finding missing descriptions in KA content
#!/usr/bin/env python3 from kapi import * import utils import argparse, sys import time import json def read_cmd(): """Reading command line options.""" desc = "Program for finding KA content without descriptions." parser = argparse.ArgumentParser(description=desc) parser.add_argument('-s','--subject', dest...
Create the Game class which has the rules implemented, can go a step forward and can draw itself.
from numpy import array from time import sleep class GameOfLife(object): def __init__(self, n, starting=[]): self.game = array([[0]*n]*n) self.size = n for i, j in starting: self.game[i, j] = 1 def get_square_pos(self, i, j): im = i - 1 iM = i + 2 ...
Add script calculating the tree structure of a set of XML files
#!/usr/bin/env python3 from collections import OrderedDict try: from lxml import etree except: from xml.etree import ElementTree as etree class Node(object): def __init__(self, name=None, depth=0): self.name = name self.depth = depth self.sources = set() self.children = Ord...
Add simple Python JSON validator
#!/usr/bin/env python """A function and script for determining whether a file contains valid JSON.""" import json def is_json(json_file): """Returns True if a file is valid JSON.""" try: with open(json_file, 'r') as fp: json.load(fp) except ValueError: return False except I...
Move fixtures into data layer
import os from pytest import fixture from smif.data_layer import DatafileInterface from smif.data_layer.load import dump @fixture(scope='function') def get_handler_csv(setup_folder_structure, project_config): basefolder = setup_folder_structure project_config_path = os.path.join( str(basefolder), 'co...
Add tests for back end
import pytest import os import numpy as np import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(myPath, '..')) from DBNlogic.sets import exists, DataSet, MNIST, SmallerMNIST def test_exists_true(): """The function `exists` returns True if given the path of an existin...
Add script for generating error code handling in GLCLient
import inspect import string import sys import os globaleaks_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..') sys.path.append(globaleaks_path) from globaleaks.rest import errors def return_exception(klass): reason_string = "" arguments = inspect.getargspec(klass.__init__).args argumen...
Add an example of how to use the USB driver
""" Interrogate stick for supported capabilities. """ import sys from ant.core import driver from ant.core import node from config import * # Initialize stick = driver.USB2Driver(SERIAL, log=LOG, debug=DEBUG) antnode = node.Node(stick) antnode.start() # Interrogate stick # Note: This method will return immediatel...
Add check script for canny
from __future__ import print_function, division import imgaug as ia import imgaug.augmenters as iaa def main(): black_and_white = iaa.RandomColorsBinaryImageColorizer( color_fg=255, color_bg=0) print("alpha=1.0, black and white") image = ia.quokka_square((128, 128)) aug = iaa.Canny(alpha=1.0,...
Implement dynamic shape and raw_shape
import tensorflow as tf def shape(tt): """Returns the shape of a TensorTrain. This operation returns a 1-D integer tensor representing the shape of the input. For TT-matrices the shape would have two values, see raw_shape for the tensor shape. Args: tt: `TensorTrain` object. Returns: A `Tensor`...
Add empty module for html generation
''' Created on 06 Jan 2016 Copyright (c) 2014 Brendan Gray and Sylvermyst Technologies 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 limit...
Write the Validation class (wrapper around the DataPackage class).
"""Validate data-packages""" from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from json import dumps from datetime import datetime from future import standard_library from collections import OrderedDict from datapackag...
Add script to make json crop types look up
from __future__ import print_function import csv import json import sys def init(): with open('../data/cdl_data_grouped.csv', mode='r') as cdl_data_grouped: reader = csv.DictReader(cdl_data_grouped) crop_types = {} for row in reader: crop_group = row['Attributes'] ...
Support simplified requests for non-DB deployments
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.core.validators class Migration(migrations.Migration): dependencies = [ ('nodeconductor_paas_oracle', '0001_squashed_0007_change_support_requests'), ] operations = [ mi...
Add tests and fixtures for the Roles API wrapper
# -*- coding: utf-8 -*- """pytest Roles API wrapper tests and fixtures.""" import pytest import ciscosparkapi # Helper Functions def get_list_of_roles(api, max=None): return api.roles.list(max=max) def get_role_by_id(api, roleId): return api.roles.get(roleId) def is_valid_role(obj): return isinst...
Test for Amazon requests via a port forwarder.
import socket import sys import threading import time SERVER_THREADS = [] def start_server(local_port, remote_host, remote_port, out_file=None): t = threading.Thread(target=server, kwargs={ "local_port": local_port, "remote_host": remote_host, "remote_port": remote_port, ...
Test - Add a test for pre-commit compliance
import subprocess import unittest class TestPreCommitNormalization(unittest.TestCase): def test_normalization(self): """ We test if the code was properly formatted with pre-commit. """ pre_commit_command = ["pre-commit", "run", "--all-files"] try: subprocess.check_call(pre_comm...
Add map helpers for use in future melting pot version.
# Copyright 2022 DeepMind Technologies Limited. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
Load phosphosite data from dataset .tsv file
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import dirname, abspath, join from collections import namedtuple, defaultdict from indra.util import read_unicode_csv PhosphoSite = namedtuple('PhosphoSite', ['GENE', 'PROTEIN',...
Add utils for generating, reading and writing signing keys
from syutil.base64util import encode_base64, decode_base64 import nacl.signing NACL_ED25519 = "ed25519" def generate_singing_key(version): """Generate a new signing key Args: version (str): Identifies this key out the keys for this entity. Returns: A SigningKey object. """ key = na...
Add solution to challenge 1.
import base64 def hex_to_base64(hex_string): return base64.b64encode(base64.b16decode(hex_string, True)) if __name__ == '__main__': hex_string = raw_input("> ") print hex_to_base64(hex_string)
Read results and write to a txt file
def read(filename): f = open(filename) line = f.readline() print(line) folds_res = line.split(',') f.close() return folds_res[1:11] for i in range(1, 13): filename = 'output/psl/auc_all_all_dataset' + str(i) + '.txt' folds_res = read(filename) lines = [] write_line = '' f...
Add script to message PRs in a range
""" Command-line script message pull requests in a range """ from os import path import sys import logging import click # Add top-level module path to sys.path before importing tubular code. sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from tubular.github_api import GitHubAPI # pylint: disable...
Add example for alternate axes scale.
""" Scatter Plots with alternate Y axis scale --------------------------------- A few examples that make use of alternate Y axis scales. """ # category: simple charts import altair as alt import numpy as np import pandas as pd chart_df = pd.DataFrame( { 'x': list(range(0,20)), 'y': [2** x for x in...
Add tests for nuclear QN accessors and dummies
"""Tests for special utilities related to nuclear problems.""" import pytest from sympy import Symbol, simplify, latex from drudge import NuclearBogoliubovDrudge from drudge.nuclear import JOf, TildeOf, MOf, NOf, LOf, PiOf @pytest.fixture(scope='module') def nuclear(spark_ctx): """Set up the drudge to test.""" ...
Merge remote-tracking branch 'origin' into AC-9512
# Generated by Django 2.2.10 on 2021-11-24 16:41 import swapper from django.db import migrations def add_startup_profile_top_nav(apps, schema_editor): NavTreeItem = apps.get_model('accelerator', 'NavTreeItem') NavTree = swapper.load_model('accelerator', 'NavTree') nav_items = [ {"title": 'My Start...
Add subscriptions for all memberships
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-11-02 09:45 from __future__ import unicode_literals from django.db import migrations from django.db.transaction import atomic from django.db.utils import IntegrityError def add_subscriptions_for_memberships(apps, schema_editor): ContentType = apps.get_...
Add basic test for diffiehellman
#/usr/bin/python3 # -*- coding: utf-8 -*- # Run from Cryptchat # python3 -m cryptchat.test.test_diffiehellman import unittest from ..crypto.diffiehellman import DiffieHellman class testDiffieHellman(unittest.TestCase): def test_initiatevalid(self): alice = DiffieHellman(group=5) self.assertTrue(...
Add unit tests for test_question_section_is_empty
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...