Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add a single testcase for the tracer
import os import nose import tracer import logging l = logging.getLogger("tracer.tests.test_tracer") bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) pov_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), "povs")) test_data_location = str(os.path.di...
Add Kahn's algorithm in python
from collections import defaultdict #Class to represent a graph class Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[...
Add first draft of Google refresh-token script
#!/usr/bin/env python import os import sys import webbrowser from oauth2client.client import OAuth2WebServerFlow def get_credentials(scopes): flow = OAuth2WebServerFlow( client_id=os.environ['GOOGLE_CLIENT_ID'], client_secret=os.environ['GOOGLE_CLIENT_SECRET'], scope=' '.join(scopes), ...
Format code according to PEP8
from time import sleep from threading import Timer # Sleep Sort ;) # Complexity: O(max(input)+n) def sleep_sort(a): """ Sorts the list 'a' using Sleep sort algorithm >>> from pydsa import sleep_sort >>> a = [3, 4, 2] >>> sleep_sort(a) [2, 3, 4] """ sleep_sort.result = [] def add1...
from time import sleep from threading import Timer # Sleep Sort ;) # Complexity: O(max(input)+n) def sleep_sort(a): """ Sorts the list 'a' using Sleep sort algorithm >>> from pydsa import sleep_sort >>> a = [3, 4, 2] >>> sleep_sort(a) [2, 3, 4] """ sleep_sort.result = [] def ad...
Apply Meta changed & field default to SiteMetadata
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0005_sitemetadata'), ] operations = [ migrations.AlterModelOptions( name='sitemetadata', opti...
Migrate old comments over jobs.JobReviewComment
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import apps as global_apps from django.contrib.contenttypes.management import update_contenttypes from django.db import models, migrations from django.utils.timezone import now MARKER = '.. Migrated from django_comments_xtd.Comment model...
Add export csv template tests
# 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: miha@reciprocitylabs.com # Maintained By: miha@reciprocitylabs.com from os.path import abspath, dirname, join from flask.json import dumps from te...
Add some tests for helusers
import pytest import random from uuid import UUID from helusers.utils import uuid_to_username, username_to_uuid def test_uuid_to_username(): assert uuid_to_username('00fbac99-0bab-5e66-8e84-2e567ea4d1f6') == 'u-ad52zgilvnpgnduefzlh5jgr6y' def test_username_to_uuid(): assert username_to_uuid('u-ad52zgilvnpgn...
Add simple animation example from pygame tutorial
import sys, pygame pygame.init() size = width, height = 320, 240 speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) #ball = pygame.image.load("ball.bmp") ball = pygame.surface.Surface((100, 100)) ball.fill(pygame.Color(0, 0, 255, 255)) ballrect = ball.get_rect() clock = pygame.time.Clock() while ...
Add utility function to retrieve default price list and to create a product from a good
from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured from .models import Product, PriceList def get_default_price_list(): """ Return the default price list """ try: return PriceList.objects.get(default=True) except PriceList.DoesNotExist: ...
Add script to compute articles improved for media collection
# -*- coding: utf-8 -*- """Analysing a Glamorous report to identify articles improved.""" import sys import xml.dom.minidom def handle_node_attribute(node, tag_name, attribute_name): """Return the contents of a tag based on his given name inside of a given node.""" element = node.getElementsByTagName(tag_na...
Add migration script 22->23 (to be completed)
# -*- encoding: utf-8 -*- from storm.locals import Int, Bool, Unicode, DateTime, JSON, Reference, ReferenceSet from globaleaks.db.base_updater import TableReplacer from globaleaks.models import BaseModel, Model class InternalFile_v_22(Model): __storm_table__ = 'internalfile' internaltip_id = Unicode() na...
Add url parsing unit tests
import pytest from lib.purl import Purl from lib.purl_exc import * class TestParserFunctions(object): def test_simple_url(self): str_url = 'http://blank' url = Purl(str_url) assert str(url) == str_url str_url = 'https://blank' url = Purl(str_url) assert str(url) == str_url str_url = '...
Add a timeout attr to NavigateAction.
# Copyright 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. from telemetry.page.actions import page_action class NavigateAction(page_action.PageAction): def __init__(self, attributes=None): super(NavigateAction...
# Copyright 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. from telemetry.page.actions import page_action class NavigateAction(page_action.PageAction): def __init__(self, attributes=None): super(NavigateAction...
Add new reschedule teacher weekly poll
''' Created on Feb 21, 2013 @author: raybesiga ''' from django.core.management.base import BaseCommand from education.models import reschedule_teacher_weekly_polls from optparse import OptionParser, make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option("-g", "...
Add a test for the digitdestroyer filter
from unittest import TestCase from spicedham.digitdestroyer import DigitDestroyer class TestDigitDestroyer(TestCase): def test_classify(self): dd = DigitDestroyer() dd.filter_match = 1 dd.filter_miss = 0 match_message = ['1', '2', '3', '1', '1'] miss_message = ['a', '1...
Add eventlet db_pool use for mysql
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apach...
Add regression test for the message options bug.
import unittest from celery.messaging import MSG_OPTIONS, get_msg_options, extract_msg_options class TestMsgOptions(unittest.TestCase): def test_MSG_OPTIONS(self): self.assertTrue(MSG_OPTIONS) def test_extract_msg_options(self): testing = {"mandatory": True, "routing_key": "foo.xuzzy"} ...
Add unit test of g1.asyncs.kernels public interface
import unittest from g1.asyncs import kernels class KernelsTest(unittest.TestCase): """Test ``g1.asyncs.kernels`` public interface.""" def test_contexts(self): self.assertIsNone(kernels.get_kernel()) self.assertEqual(kernels.get_all_tasks(), []) self.assertIsNone(kernels.get_current...
Add raven SSL fix mod.
# See https://github.com/getsentry/raven-python/issues/1109 """ raven.transport.http ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import requests from raven.utils.compat import s...
Add tool to extract routing from planning debug
#!/usr/bin/env python ############################################################################### # Copyright 2017 The Apollo Authors. 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 ...
Add a redis_check management command
from __future__ import absolute_import from zephyr.models import UserProfile, get_user_profile_by_id from zephyr.lib.rate_limiter import redis_key, client, max_api_calls, max_api_window from django.core.management.base import BaseCommand from django.conf import settings from optparse import make_option import os, ti...
Update middleware syntax with "TykGateway"
from tyk.decorators import * @Pre def AddSomeHeader(request, session): # request['Body'] = 'tyk=python' request['SetHeaders']['SomeHeader'] = 'python2' return request, session def NotARealHandler(): pass
from tyk.decorators import * from tyk.gateway import TykGateway as tyk @Pre def AddSomeHeader(request, session): request['SetHeaders']['SomeHeader'] = 'python' tyk.store_data( "cool_key", "cool_value", 300 ) return request, session def NotARealHandler(): pass
Add a script for combining graphs
#!/usr/bin/env python2.7 # # Copyright 2011-2013 Colin Scott # # 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 doc fragment for new OpenStack modules
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option...
Add some tests on download.py
import os import unittest from chainer import dataset from chainer import testing class TestGetSetDatasetRoot(unittest.TestCase): def test_set_dataset_root(self): orig_root = dataset.get_dataset_root() new_root = '/tmp/dataset_root' try: dataset.set_dataset_root(new_root) ...
Add a little support for ejdb.
"""EJDB driver for Magpy. Currently does not do much except support certain command line scripts. """ import pyejdb class Database(object): """Simple database connection for use in serverside scripts etc.""" def __init__(self, database_name=None, config_file=None): se...
Add management command to populate last_modified fields
from django.core.management.base import BaseCommand from corehq.apps.commtrack.models import Product, Program from dimagi.utils.couch.database import iter_docs from datetime import datetime import json class Command(BaseCommand): help = 'Populate last_modified field for products and programs' def handle(self,...
Add sanity tests for baremetal power state commands
# Copyright (c) 2016 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...
Add Summarization API code for blog post
import indicoio import csv indicoio.config.api_key = 'YOUR_API_KEY' def clean_article(article): return article.replace("\n", " ").decode('cp1252').encode('utf-8', 'replace') def clean_articles(article_list): # data processing: clean up new lines and convert strings into utf-8 so the indico API can read the d...
Add a command prototype to list all items from a playlist
from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from django.template.defaultfilters import slugify from django.utils import translation from telemeta.models import Playlist, MediaCollection, ...
Add file to write templates to json
#!/usr/bin/env python import rethinkdb as r from optparse import OptionParser import json import os if __name__ == "__main__": parser = OptionParser() parser.add_option("-P", "--port", dest="port", type="int", help="rethinkdb port", default=30815) (options, args) = parser.parse_args(...
Add a script to "untie" tied model weights.
#!/usr/bin/env python import climate import cPickle as pickle import gzip import numpy as np logging = climate.get_logger('theanets-untie') @climate.annotate( source='load a saved network from FILE', target='save untied network weights to FILE', ) def main(source, target): opener = gzip.open if source.en...
Test float precision in json encoding.
import unittest import fedmsg.encoding from nose.tools import eq_ class TestEncoding(unittest.TestCase): def test_float_precision(self): """ Ensure that float precision is limited to 3 decimal places. """ msg = dict(some_number=1234.123456) json_str = fedmsg.encoding.dumps(msg) pr...
Add SolveTimer - print number of iterations and elapsed time to console while running ml.solve() - see docstring for usage
try: from tqdm.auto import tqdm except ModuleNotFoundError: raise ModuleNotFoundError("SolveTimer requires 'tqdm' to be installed.") class SolveTimer(tqdm): """Progress indicator for model optimization. Usage ----- Print timer and number of iterations in console while running `ml.solve()...
Add migration to backfill recipient counts
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('msgs', '0036_auto_20151103_1014'), ] def backfill_recipient_counts(apps, schema): Broadcast = apps.get_model('msgs', 'Broadc...
Add a migration for directive_sections -> 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 directive_sections to relationships Revision ID: 324d461206 Revises:...
Add a basic smoke test to check for exceptions and programming errors.
# -*- coding: utf-8 -*- import unittest import sys sys.path.insert(0, '../mafia') from game import Game from game import Player class TestMessenger: def message_all_players(self, message: str): print ('public: {message}'.format(message=message)) def message_player(self, player, message: str): ...
Correct empty lines in imported files
print('\n\n\n\n') print('Now:\n') for p in c.all_positions(): try: # Corrects empty lines around @language python\n@tabwidth -4 if p.h.startswith('@clean') and p.h.endswith('py'): # Corrects empty lines after @first if p.h == '@clean manage.py': splited = p....
Add presubmit check for run-bindings-tests
# Copyright (C) 2013 Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
Add simple lauch script without configuration options
from twisted.application import internet, service from twisted.names import dns from twisted.names import server from openvpnzone import OpenVpnStatusAuthority, extract_status_file_path def createOpenvpn2DnsService(): zones = [OpenVpnStatusAuthority(extract_status_file_path('server.conf'))] f = server.DNSSer...
Add migration for creating the Professional Certificate program type
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-12-19 19:51 from __future__ import unicode_literals from django.db import migrations PAID_SEAT_TYPES = ('credit', 'professional', 'verified',) PROGRAM_TYPE = 'Professional Certificate' def add_program_type(apps, schema_editor): SeatType = apps.get_mod...
Add a Quartz backend for the null toolkit
#------------------------------------------------------------------------------ # Copyright (c) 2011, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions describe...
Add missing specification model tests
# -*- coding: utf-8 -*- from django.test import TestCase from django.db import IntegrityError from .model_factories import ( SpecificationF, DomainF, AttributeF ) class TestModelSpecification(TestCase): def test_model_repr(self): dom = DomainF.create(id=1, name='A domain') attr = Att...
Add some basic tests around contact parsing
import aiosip def test_simple_header(): header = aiosip.Contact.from_header('<sip:pytest@127.0.0.1:7000>') assert not header['name'] assert dict(header['params']) == {} assert dict(header['uri']) == {'scheme': 'sip', 'user': 'pytest', ...
Test save, load functionality in Statespace
""" Tests of save / load / remove_data state space functionality. """ from __future__ import division, absolute_import, print_function import numpy as np import pandas as pd import os from statsmodels import datasets from statsmodels.tsa.statespace import (sarimax, structural, varmax, ...
Simplify the view as the validation logic has already moved to the model
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponseGone from django.contrib.auth import login from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() def login(request, key, redirect_invalid_to=None, red...
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='te...
Add script to perform partial upload
#!/bin/env python # -*- coding: utf8 -*- """ Triggers a partial upload process with the specified raw.xz URL. """ import argparse from fedimg.config import AWS_ACCESS_ID from fedimg.config import AWS_SECRET_KEY from fedimg.config import AWS_BASE_REGION, AWS_REGIONS from fedimg.services.ec2.ec2copy import main as ec2c...
Add (failing) tests for the dashboard
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange 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 applic...
Add initial version of bot script
import time from slackclient import SlackClient token = 'kekmao' sc = SlackClient(token) team_join_event = 'team_join' def send_welcome_message(user): user_id = user['id'] response = sc.api_call('im.open', user=user_id) try: dm_channel_id = response['channel']['id'] except (KeyError, ValueErr...
Test if points are in footprint
import unittest import pcl import numpy as np from patty_registration.conversions import loadLas, loadCsvPolygon from numpy.testing import assert_array_equal, assert_array_almost_equal from matplotlib import path class TestInPoly(unittest.TestCase): def testInPoly(self): fileLas = 'data/footprints/162.las'...
Add an example for pre signed URL
# Copyright 2016 Catalyst IT 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 applicable law or ag...
Add script to generate images from all samples
#!/usr/bin/env python import teetime import os def main(): with open('samples/sample-texts.txt') as fh: for line in fh: print line.strip() path = teetime.create_typography(line.strip(), colors=False) os.rename(path, os.path.join('samples', os.path.basename(path))) if...
Add script to batch convert a directory recursively
import os import sys import re from pathlib import Path import argparse from convert2netcdf4 import parseandconvert parser = argparse.ArgumentParser(description='Recursively batch convert Vaisala old-binary format to NetCDF files. Keeps directory structure.') parser.add_argument('--from', dest='fromdir', help='Input...
Add script for fetching metadata from audio file
#! /usr/bin/env python import os import sys import re import tempfile def getVideoDetails(filepath): tmpf = tempfile.NamedTemporaryFile() os.system("ffmpe...
Add a primitive pythonic wrapper.
import os import _xxdata_11 parameters = { 'isdimd' : 200, 'iddimd' : 40, 'itdimd' : 50, 'ndptnl' : 4, 'ndptn' : 128, 'ndptnc' : 256, 'ndcnct' : 100 } def read_scd(filename): fd = open(filename, 'r') fortran_filename = 'fort.%d' % fd.fileno() os.symlink(filename, fortran_filen...
Add guess phred encoding script
""" awk 'NR % 4 == 0' your.fastq | python %prog [options] guess the encoding of a stream of qual lines. """ import sys import optparse RANGES = { 'Sanger': (33, 93), 'Solexa': (59, 104), 'Illumina-1.3': (64, 104), 'Illumina-1.5': (67, 104) } def get_qual_range(qual_str): """ >>> get_qual_...
Add a bot message to display TeamCity test results
""" Post the comment like the following to the PR: ``` :robot: TeamCity test results bot :robot: <Logs from pytest> ``` """ from github import Github import os import sys # Check if this is a pull request or not based on the environment variable try: pr_id = int(os.environ["GITHUB_PR_NUMBER"].split("/")[-1]) exc...
Add script for train/test split
import os import shutil import argparse import random random.seed(47297) parser = argparse.ArgumentParser(description='Split data into train and test sets.') parser.add_argument('subjects_root_path', type=str, help='Directory containing subject sub-directories.') args, _ = parser.parse_known_args() def move_to_part...
Create class to interpolate values between indexes
class Interpolator: def __init__(self): self.data = [] def addIndexValue(self, index, value): self.data.append((index, value)) def valueAtIndex(self, target_index): if target_index < self.data[0][0]: return None elif self.data[-1][0] < target_index: ...
Add missing file on last merge
import logging import datetime from sqlalchemy import ( Column, Unicode, DateTime, Boolean, ForeignKey) from sqlalchemy.orm import relationship from goodtablesio.models.base import Base, BaseModelMixin, make_uuid log = logging.getLogger(__name__) class Subscription(Base, BaseModelMixin): __tablename__ = ...
Add some tests for the tokens
from flask import current_app from itsdangerous import TimedJSONWebSignatureSerializer from flaskbb.utils.tokens import make_token, get_token_status def test_make_token(user): token = make_token(user, "test") s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) unpacked_token = s.loads(to...
Add common migration (unrelated to branch)
# Generated by Django 2.2.12 on 2020-05-29 05:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('common', '0009_upload_hosting'), ] operations = [ migrations.AlterField( model_name='upload', name='destination', ...
Add dead letter SQS queue example
# Copyright 2010-2016 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...
Add eventlet backdoor to facilitate troubleshooting.
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 Openstack, LLC. # Administrator of the National Aeronautics and Space Administration. # 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 ...
Add a test-case for lit xunit output
# Check xunit output # RUN: %{lit} --xunit-xml-output %t.xunit.xml %{inputs}/test-data # RUN: FileCheck < %t.xunit.xml %s # CHECK: <?xml version="1.0" encoding="UTF-8" ?> # CHECK: <testsuites> # CHECK: <testsuite name='test-data' tests='1' failures='0'> # CHECK: <testcase classname='test-data.' name='metrics.ini' time...
Add py solution for 384. Shuffle an Array
from random import randint class Solution(object): def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums def reset(self): """ Resets the array to its original configuration and return it. :rtype: List[int] """ return se...
Add test to check if elements have at least one owner
""" For all relevant model elements, check if there is at least one "owner" ("owner" is a derived union). This is needed to display all elements in the tree view. """ import itertools import pytest import gaphor.SysML.diagramitems import gaphor.UML.diagramitems from gaphor import UML from gaphor.core.modeling impor...
Add outputter to display overstate stages
''' Display clean output of an overstate stage ''' #[{'group2': {'match': ['fedora17-2', 'fedora17-3'], # 'require': ['group1'], # 'sls': ['nginx', 'edit']} # } # ] # Import Salt libs import salt.utils def output(data): ''' Format the data for printing stage ...
Add the IPython version helper
from __future__ import (division, print_function, absolute_import, unicode_literals) from IPython import version_info def ipython_version_as_string(): """ The IPython version is a tuple (major, minor, patch, vendor). We only need major, minor, patch. """ return ''.join([st...
Add new users to all deployments
from core.models import * def handle(user): deployments = Deployment.objects.all() site_deployments = SiteDeployments.objects.all() site_deploy_lookup = defaultdict(list) for site_deployment in site_deployments: site_deploy_lookup[site_deployment.site].append(site_deployment.deployment) user_deploy_lookup = de...
Add a small tool to answer questions like "Why does target A depend on target B".
#!/usr/bin/env python # Copyright (c) 2011 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. """Prints paths between gyp targets. """ import json import os import sys import time from collections import deque def usage():...
Add a test that fails if using an old version of chromedriver
from seleniumbase import BaseCase class ChromedriverTests(BaseCase): def test_fail_if_using_an_old_chromedriver(self): if self.browser != "chrome": print("\n This test is only for Chrome!") print(" (Run with: '--browser=chrome')") self.skip("This test is only for Chr...
Add small python script which calculates how much disk space we save by using CAS
import os import pymongo from collections import Counter db_uri = os.getenv('SCITRAN_PERSISTENT_DB_URI', 'localhost:9001') db = pymongo.MongoClient(db_uri).get_database('scitran') COLLECTIONS = ['projects', 'acquisitions', 'analyses'] COLLECTIONS_WITH_EMBEDDED = [('sessions', 'subject')] def files_of_collection(col...
Add a tool script to print errors statistics in output JSON files.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Make statistics on score files (stored in JSON files). """ import argparse import json import numpy as np def parse_json_file(json_file_path): with open(json_file_path, "r") as fd: json_data = json.load(fd) return json_data def extract_data_list(j...
Add script to normalize image using Ops
# @Dataset data # @OpService ops # @OUTPUT Img normalized # Create normalized image to the [0, 1] range. # # Stefan Helfrich (University of Konstanz), 03/10/2016 from net.imglib2.type.numeric.real import FloatType from net.imglib2.type.numeric.integer import ByteType from net.imagej.ops import Ops normalized = ops.c...
Add WmataError class and start of Wmata class.
import datetime import urllib import json class WmataError(Exception): pass class Wmata(object): base_url = 'http://api.wmata.com/%(svc)s.svc/json/%(endpoint)s' # By default, we'll use the WMATA demonstration key api_key = 'kfgpmgvfgacx98de9q3xazww' def __init__(self, api_key=None): if ...
Add skeleton for new python scripts.
#!/usr/bin/python """Usage: <SCRIPT_NAME> [--log-level=<log-level>] -h --help Show this message. -v --version Show version. --log-level=<log-level> Set logging level (one of {log_level_vals}) [default: info]. """ import docopt import ordutils.log as log import ordutils.options as opt import schema im...
Add back a filesystem backend for testing and development
import os import json from scrapi.processing.base import BaseProcessor class StorageProcessor(BaseProcessor): NAME = 'storage' def process_raw(self, raw): filename = 'archive/{}/{}/raw.{}'.format(raw['source'], raw['docID'], raw['filetype']) if not os.path.exists(os.path.dirname(filename)): ...
Implement simple gaussian process regression.
import csv import sys import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.gaussian_process.kernels kernel = (sklearn.gaussian_process.kernels.ConstantKernel() + sklearn.gaussian_process.kernels.Matern(length_scale=2, nu=3/2) + sklearn.gaussian_process.kernels.WhiteKer...
Move working view.cwl script to doc folder
#!/usr/bin/env python import fnmatch import requests import time import os import glob # You can alternatively define these in travis.yml as env vars or arguments BASE_URL = 'https://view.commonwl.org/workflows' #get the cwl in l7g/cwl-version matches = [] for root, dirnames, filenames in os.walk('cwl-version'): ...
Add one liner to add ability to print a normal distribution with mean zero and varience one
#!/usr/bin/env python3 #Copyright 2015 BRendan Perrine import random random.seed() print (random.gauss(0,1), "Is a normal distribution with mean zero and standard deviation and varience of one")
Add missing django_libs test requirement
import os from setuptools import setup, find_packages import calendarium def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return '' setup( name="django-calendarium", version=calendarium.__version__, description=read('DESCRIP...
import os from setuptools import setup, find_packages import calendarium def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return '' setup( name="django-calendarium", version=calendarium.__version__, description=read('DESCRIP...
Solve Code Fights count visitors problem
#!/usr/local/bin/python # Code Fights Count Visitors Problem class Counter(object): def __init__(self, value): self.value = value def inc(self): self.value += 1 def get(self): return self.value def countVisitors(beta, k, visitors): counter = Counter(beta) for visitor in...
Add a management command to create realm administrators.
from __future__ import absolute_import import sys from optparse import make_option from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ValidationError from django.db.utils import IntegrityError from django.core import validators from guardian.shortcuts import assign_p...
Create a folder in a datacenter if not exists
#!/usr/bin/env python """ Written by Chinmaya Bharadwaj Github: https://github.com/chinmayb/ Email: acbharadwaj@gmail.com Create a folder in a datacenter """ from __future__ import print_function from pyVmomi import vim from pyVim.connect import SmartConnect, Disconnect import argparse import atexit import getpass ...
Add script for generate events.
#!/usr/bin/python3 from random import randint output = "" filename = "data" class Generator: def gen_date(self): return str(randint(2013, 2015)) + "-" \ + str(randint(1, 12)) + "-" \ + str(randint(1, 31)) def gen_price(self): return str(10 * randint(10, 100)) d...
Add script to convexify the energies of a conservation tracking JSON model
import sys import commentjson as json import os import argparse import numpy as np def listify(l): return [[e] for e in l] def convexify(l): features = np.array(l) if features.shape[1] != 1: raise InvalidArgumentException('This script can only convexify feature vectors with one feature per state!') bestStat...
Fix cascades for RecurringEventOverride table
"""fix recurring override cascade Revision ID: 6e5b154d917 Revises: 41f957b595fc Create Date: 2015-05-25 16:23:40.563050 """ # revision identifiers, used by Alembic. revision = '6e5b154d917' down_revision = '4ef055945390' from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade()...
Test threading in app server rather than in serverTest.
import _10gen import ed.appserver.AppContext import ed.lang.python.Python import java.io.File # FIXME: this test produces a lot of output _10gen.__instance__ = ed.lang.python.Python.toPython(ed.appserver.AppContext(java.io.File('.'))) import test.test_thread import test.test_threading
Test template for the Damage class
import unittest from damage import Damage class DamageTests(unittest.TestCase): def test_init(self): dmg = Damage(phys_dmg=1.34, magic_dmg=1.49391) expected_phys_dmg = 1.3 expected_m_dmg = 1.5 expected_absorbed = 0 # it should round the magic/phys dmg to 1 point after the ...
Add tests for user utilities sum_ and prod_
"""Tests for user utility functions.""" from drudge import Vec, sum_, prod_ from drudge.term import parse_terms def test_sum_prod_utility(): """Test the summation and product utility.""" v = Vec('v') vecs = [v[i] for i in range(3)] v0, v1, v2 = vecs # The proxy object cannot be directly compare...
Add example of slide-hold-slide test
import numpy as np import matplotlib.pyplot as plt import rsf model = rsf.RateState() # Set model initial conditions model.mu0 = 0.6 # Friction initial (at the reference velocity) model.a = 0.005 # Empirical coefficient for the direct effect model.b = 0.01 # Empirical coefficient for the evolution effect model.dc = 1...
Create a placeholder for pyauto test scripts.
#!/usr/bin/python # Copyright (c) 2010 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. import unittest from pyauto import PyUITest class SimpleTest(PyUITest): def testCanOpenGoogle(self): self.NavigateToURL("http...
Migrate in domain model changes
from sqlalchemy import * from migrate import * meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine dataset = Table('dataset', meta, autoload=True) serp_title = Column('serp_title', Unicode()) serp_title.create(dataset) serp_teaser = Column('serp_teaser', Unicode()) serp...
Add organisation values for the Enterprise Europe Network.
"""empty message Revision ID: 0101_een_logo Revises: 0100_notification_created_by Create Date: 2017-06-26 11:43:30.374723 """ from alembic import op revision = '0101_een_logo' down_revision = '0100_notification_created_by' ENTERPRISE_EUROPE_NETWORK_ID = '89ce468b-fb29-4d5d-bd3f-d468fb6f7c36' def upgrade(): ...
Add a first small file watcher that counts words
import os import sys import time import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from watchdog.events import FileModifiedEvent class GamificationHandler(FileSystemEventHandler): def __init__(self, filename): FileSystemEventHandler.__init__(self) self.fi...
Add VSYNC GPIO output example.
# VSYNC GPIO output example. # # This example shows how to toggle the IR LED pin on VSYNC interrupt. import sensor, image, time from pyb import Pin sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesiz...
Add python tests for cosine squared angles
# -*- coding: iso-8859-1 -*- # Maintainer: joaander from hoomd import * from hoomd import md context.initialize() import unittest import os import numpy # tests md.angle.cosinesq class angle_cosinesq_tests (unittest.TestCase): def setUp(self): print snap = data.make_snapshot(N=40, ...
Add a script to graph problem reports over time by transport mode
#!/usr/bin/python # A script to draw graphs showing the number of reports by transport # type each month. This script expects to find a file called # 'problems.csv' in the current directory which should be generated # by: # DIR=`pwd` rake data:create_problem_spreadsheet import csv import datetime from collecti...