Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add a script to write frame changes to the executable. | #!/usr/bin/env python
import os
import sys
import json
import r2pipe
from getopt import getopt, GetoptError
r2 = None
def write_frame(frame_no, lvl_prefix):
lvl_path = os.path.join(lvl_prefix, "%d.lvl" % frame_no)
print "writing frame %d from %s..." % (frame_no, lvl_path)
lvl_frame = json.load(fp = open(... | |
Add tests for autoencoder models | import sys
import pytest
from numpy.testing import assert_equal
import torch
sys.path.append("../../../")
from pycroscopy.learn import models
@pytest.mark.parametrize("dim, size", [(1, [8]), (2, [8, 8]), (3, [8, 8, 8])])
def test_autoencoder_output(dim, size):
input_dim = (1, *size)
x = torch.randn(2, *inpu... | |
Add tests quantity from string parsing | #!/usr/bin/env python
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================
"""
Test classes and function in module openforcefield.typing.engines.smirnoff.io.
"""... | |
Use relative import to import tasks | from .interfaces.model import Model
from .interfaces.dataset import Dataset
from .trainer import Trainer
import tasks.tasks as tasks
| from .interfaces.model import Model
from .interfaces.dataset import Dataset
from .trainer import Trainer
from .tasks import tasks
|
Add demo code for later | from tilezilla.db.sqlite.tables import Base, TileSpec, Tile
if __name__ == '__main__':
from tilezilla import tilespec, products, stores
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# engine = create_engine('sqlite:///:memory:', echo=True)
engine = create_engine('sqli... | |
Add script to datamine the reports via NLTK |
from map import mapping
# walk through the os and get all files
# read each file in tern and go through line by line
# print lines that contain smell and the report name
from os import listdir
import nltk.data
import json
SMELL_WORDS = ['smell', 'stench', 'stink', 'odour', 'sniff', 'effluvium']
REPORTS_DIR = '/Users/... | |
Add migration to add extension ID to addon study recipes | # Generated by Django 2.0.13 on 2019-02-28 11:28
import json
from urllib.parse import unquote_plus
from django.db import migrations
def remove_signatures(apps, schema_editor):
Recipe = apps.get_model("recipes", "Recipe")
Action = apps.get_model("recipes", "Action")
Signature = apps.get_model("recipes",... | |
Add an experimental ssh monitoring script. | #!/usr/bin/python
import eventlet
from eventlet.green import socket
import libssh2
import time
import os
import random
def monitor(hostname, username, id):
print '%s %s %d' % (hostname, username, id)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, 22))
session = lib... | |
Structure for the Rst test | # -*- coding: utf-8 -*-
import sys
import os
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src/epicslide"))
import rst
class TestRst(object):
def test_pygments(self):
p = rst.Pygments('')
print p.__dict__
print p.run()
assert False
def html_pa... | |
Add instance generator for complete reproducible objects | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import re
import StringIO
import d1_common.xml
import d1_test.d1_test_case
import d1_test.instance_generator.identifier
import d1_test.instance_generator.system_metadata
def generate_reproducible(client, pid=None, option_dict=None):
"""Generate science o... | |
Move URLconfig around to fix Django Debug Toolbar | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import pretixcontrol.urls
import pretixpresale.urls
urlpatterns = patterns('',
url(r'^control/', include(pretixcontrol.urls, namespace='control')),
url(r'^admin/', include(admin.site.urls)),
... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import pretixcontrol.urls
import pretixpresale.urls
urlpatterns = patterns('',
url(r'^control/', include(pretixcontrol.urls, namespace='control')),
url(r'^admin/', include(admin.site.urls)),
... |
Add API for check MX | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import dns.resolver
import dns.reversename
import json
import urlparse
def resolve_mx(hostname):
response = []
for data in dns.resolver.query(hostname, 'MX'):
response.append((data.exchange.to_text(), data.preference))
return response
def resolve_ip... | |
Add script to test if documents exist | #!/bin/python
import MySQLdb
import argparse
import os
parser = argparse.ArgumentParser(description='Test documents of SugarCRM')
parser.add_argument('--remove', type=bool, default=False,
help='delete documents')
args = parser.parse_args()
HOST = "localhost"
USER = "database_user"
PASSWD = "database_password"
DB ... | |
Create script for adding/removing global mods. | #!/usr/bin/python
import sys
from redis import Redis
db = Redis()
session_id = sys.argv[2]
if sys.argv[1]=='add':
db.sadd('global-mods', session_id)
print 'Added to global mods list.'
for chat in db.smembers('session.'+session_id+'.chats'):
print 'Setting group in '+chat+' to globalmod.'
... | |
Enable automatic testing for hash sum | #!/usr/bin/env python
import os
import sys
import shutil
import unittest
import hashsum
print('hashsum: v%s' % hashsum.VERSION)
print('Python: %s' % sys.version)
shutil.copytree(os.path.join(os.environ['SRC_DIR'], 'tests'), 'tests')
from tests.test_hashsum import *
try:
unittest.main(verbosity=2)
finally:
... | |
Add tests for lib/bio module | """Testing functions in lib/bio."""
from hypothesis import given
import hypothesis.strategies as st
import lib.bio as bio
DNA = 'ACGTUWSMKRYBDHVNXacgtuwsmkrybdhvnx'
REVERSIBLE = 'ACGTWSMKRYBDHVNXacgtwsmkrybdhvnx' # 'U's removed
PROTEIN = 'EFILPQefilpq'
HAS_PROTEIN = '[{}]*[{}]+[{}]*'.format(DNA, PROTEIN, DNA)
@giv... | |
Add a test for an async item_scraped handler. | from twisted.internet import defer
from twisted.trial import unittest
from scrapy import signals, Request, Spider
from scrapy.utils.test import get_crawler
from tests.mockserver import MockServer
class ItemSpider(Spider):
name = 'itemspider'
def start_requests(self):
for _ in range(10):
... | |
Add script to extract the shape of blockgroups and aggregate them per msa | """shape_msa_blockgroup.py
Output one shapefile per MSA containing all the blockgroups it contains
"""
import os
import csv
import fiona
#
# Import MSA to blockgroup crosswalk
#
msa_to_bg = {}
with open('data/2000/crosswalks/msa_blockgroup.csv', 'r') as source:
reader = csv.reader(source, delimiter='\t')
re... | |
Fix hidden unit test dependencies | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | |
Create PSA plugin, only accessible for admins | # -*- coding: utf-8 -*-
"""
================================================
:mod:`onebot.plugins.psa` PSA
================================================
This plugin allows admins to send broadcasts
"""
from irc3 import plugin
from irc3.plugins.command import command
@plugin
class PSAPlugin(object):
"""PSA Pl... | |
Add a few tests for anonymous.json | from __future__ import print_function, unicode_literals
from aspen import json
from gittip.elsewhere.twitter import TwitterAccount
from gittip.testing import Harness
from gittip.testing.client import TestClient
class Tests(Harness):
def hit_anonymous(self, method='GET', expected_code=200):
user, ignore... | |
Add module to handle ranked items (for Condorcet-Schulze voting method). | # -*- coding: utf-8 -*-
# Suq1 -- An ad hoc Python toolbox for a web service
# By: Emmanuel Raviart <emmanuel@raviart.com>
#
# Copyright (C) 2009, 2010, 2011, 2012 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2013, 2014 Easter-eggs, Etalab & Emmanuel Raviart
# https://github.com/eraviart/suq1
#
# This file is part ... | |
Add demo connection setting to git | # This file is auto-generated by the `evennia connections` wizard.
# Don't edit manually, your changes will be overwritten.
GAME_INDEX_ENABLED = True
GAME_INDEX_LISTING = \
{ 'game_status': 'launched',
'game_website': 'https://demo.evennia.com',
'listing_contact': 'a@a.com',
'long_description': 'The Even... | |
Define casa tasks that fail with python errors |
'''
Define my own version of CASA tools that return python errors if they fail.
'''
from tasks import split, uvsub, concat, clean, rmtables
from .graceful_error_catch import catch_fail
def mysplit(**kwargs):
return catch_fail(split, **kwargs)
def myuvsub(**kwargs):
return catch_fail(uvsub, **kwargs)
de... | |
Add failing test: columnize called with very long entries. | # encoding: utf-8
"""Tests for IPython.utils.text"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.... | |
Add some extra tests for Diagram | import gaphas
import pytest
from gaphor.services.eventmanager import EventManager
from gaphor.UML import Diagram
from gaphor.UML.elementfactory import ElementFactory
from gaphor.UML.presentation import Presentation
class Example(Presentation, gaphas.Element):
def unlink(self):
self.test_unlinked = True
... | |
Move exception into common module and add unicode support | class SymbolicationError(Exception):
message = None
def __init__(self, message):
if isinstance(message, bytes):
message = message.decode('utf-8', 'replace')
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self.message.encode('u... | |
Test disabling inclusion of jQuery | from django_webtest import WebTest
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from . import factory
class AdminTestCase(WebTest):
def setUp(self):
super(AdminTestCase, self).setUp()
self.user = factory.create_superuser()
self.image = facto... | |
Add tests for adding interval setting automatically | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from i3pystatus.core.modules import IntervalModule
class IntervalModuleMetaTest(unittest.TestCase):
def test_no_settings(self):
class NoSettings(IntervalModule):
pass
self.assertEqual(NoSettings.settings, ('interval',))
... | |
Add sql user creation script | import sys
from brain.models.sqlobjects import User
from brain.helpers.sql import session_transaction
if len(sys.argv) not in (4, 5):
print("usage: {0} <username> <rmqvhost> <ftpuser> [quota]\n"
" with <username> a string\n"
" <rmqvhost> the rmqvhost used for the frontend\n"
... | |
Fix nullable constraints on EASUid and EASFoldersync state enum. | """Tighten EAS constraints and fix easfoldersync state enum.
Revision ID: 3f96e92953e1
Revises: 55f0ff54c776
Create Date: 2014-05-21 17:43:44.556716
"""
# revision identifiers, used by Alembic.
revision = '3f96e92953e1'
down_revision = '55f0ff54c776'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.ex... | |
Add unit tests for the submit_comment task | import json
import mock
import six
from celery.exceptions import Retry, MaxRetriesExceededError
from requests.exceptions import RequestException
from django.test import SimpleTestCase, override_settings
from regulations.tasks import submit_comment
@mock.patch('regulations.models.FailedCommentSubmission.objects')
@m... | |
Add simple test for McCabe checker | import unittest
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from mccabe import get_code_complexity
_GLOBAL = """\
for i in range(10):
pass
def a():
def b():
def c():
pass
c()
b()
"""
class McCabeTest(unittest.TestCase)... | |
Add placeholder for adding type hinting using the new syntax in Python. | # This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... | |
Add monitor script for taints | #!/usr/bin/env python
""" Node taints check for OpenShift V3 """
# Adding the ignore because it does not like the naming of the script
# to be different than the class name
# pylint: disable=invalid-name
# pylint: disable=wrong-import-position
# pylint: disable=broad-except
# pylint: disable=line-too-long
import arg... | |
Add management command which unlocks all lockout commands | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django_auth_policy.models import LoginAttempt
class Command(BaseCommand):
help = "Remove all locks on usernames and IP addresses"
def handle(self, *args, **options):
c = LoginAttempt.objects.filte... | |
Add tests for responsive context_processors | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from responsive.conf import settings
from responsive.context_processors import device
fro... | |
Print total byte count from db | import re
import sqlite3
def open_cloudfront_log_db():
db = sqlite3.connect('cf.db')
return db
def format_size(sz):
abbrevs = (
(1<<50, 'PB'),
(1<<40, 'TB'),
(1<<30, 'GB'),
(1<<20, 'MB'),
(1<<10, 'KB'),
(1, 'B')
)
for factor, suffix in abbrevs:
... | |
Add a convenient function to plot filter | from pathlib import Path
from keras.applications import VGG16
from keras.models import Model
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
from tools.datasets.urban_tribes import load_images
def plot_filter(image_path, layer_name, output_dir):
base_model = VGG16(weights='imagenet'... | |
Add metas information for the package | """django-livereload"""
__version__ = '0.1.dev'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-livereload'
| |
Add Edit Distance DP Algorithm | """
Author : Turfa Auliarachman
Date : October 12, 2016
This is a pure Python implementation of Dynamic Programming solution to the edit distance problem.
The problem is :
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion... | |
Add python folder with a rest-test-file | import urllib
import urllib2
url = 'http://app.dev.inowas.com/api/results.json'
params = urllib.urlencode({
'id': '1',
'propertyType': 'gwHead',
'width': 4,
'height': 4,
'upperLeftX': 0.005,
'upperLeftY': 0.005,
'scaleX': 1,
'scaleY': 1,
'skewX': 0,
'skewY': 0,
'srid': 4326,... | |
Add tests for Tafseer Views | from django.test import TestCase
from django.urls import reverse
from model_mommy import mommy
class TestTafsserViews(TestCase):
def setUp(self):
self.sura = mommy.make('quran_text.sura', name='Al-Fateha', index=1)
self.ayah = mommy.make('quran_text.ayah', number=1, sura=self.sura,
... | |
Add a viewer for the Allied Vision camera using OpenCV. | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Test application to display live images from an Allied Vision camera using OpenCV 3
#
# External dependencies
import cv2
import Vimba
# Initialize Vimba
Vimba.VmbStartup()
# Initialize the camera
camera = Vimba.VmbCamera( '50-0503323406' )
# Open the camera
camera.Op... | |
Enforce non TestCase usage under `tests/nts` | # -*- coding: utf-8 -*-
"""
tests.nts.conftest
~~~~~~~~~~~~~~~~~~
"""
import pathlib
import pytest
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase
NTS_TEST_SUITE_PATH = pathlib.Path(__file__).parent
@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_collectio... | |
Add test for verifying archive contents. | from json import load
from django_archive import __version__
from .base import BaseArchiveTestCase
from .sample.models import Sample
class ArchiveTestCase(BaseArchiveTestCase):
"""
Test that the archive command includes correct data in the archive
"""
def setUp(self):
Sample().save()
... | |
Add Xdmf Python Test that writes values to an XdmfArray | import Xdmf
from Xdmf import *
if __name__ == '__main__':
array = Xdmf.XdmfArray()
array.SetNumberType(Xdmf.XDMF_INT64_TYPE)
assert(array.GetNumberType() == Xdmf.XDMF_INT64_TYPE)
array.SetShapeFromString("3 3")
assert(array.GetShapeAsString() == "3 3")
assert(array.GetNumberOfElements() == 9... | |
Add item name gen script | '''Script to help generate item names.'''
def int_to_str(num, alphabet):
'''Convert integer to string.'''
# http://stackoverflow.com/a/1119769/1524507
if (num == 0):
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
a... | |
Add tests for the openid lister for FederationReaderServer | # -*- coding: utf-8 -*-
# Copyright 2018 New Vector 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 la... | |
Add some functions to tear first pages from a PDF | """
This file contains the necessary functions to determine whether we should tear
the first page from a PDF file, and actually tear it.
"""
import tearpages
# List of bad publishers which adds an extra useless first page, which can be
# teared. Please, submit a PR to include new ones which I may not be aware of!
BAD... | |
Remove bad data form object_people table | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Remove invalid person objects
Create Date: 2016-11-09 01:06:04.745331
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
from alembic imp... | |
Add simple test to check that we populate the root as expected | import unittest
import os
from subprocess import check_call
from sh import ls
mountpoint = '/tmp/spotifile_test_mount'
class SpotifileTestClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not os.path.exists(mountpoint):
os.mkdir(mountpoint)
@classmethod
def tearDownClass(cls):
if os.path.exis... | |
Make our own version of get_object_or_404 and get_list_or_404 | # app imports
from oweb.exceptions import OWebDoesNotExist
def get_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword argume... | |
Add test for city visitor. | import unittest
import mock
from generators.city_visitor import CityVisitor
class CityVisitorTest(unittest.TestCase):
def test_city_visitor(self):
city = mock.Mock()
visitor = CityVisitor(city)
visitor.run()
city.accept.assert_called()
| |
Add a snippet (Python physics). | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
import numpy as np
class State:
def __init__(self, ndim):
self.ndim = ndim
self.position = np.zeros(self.ndim)
self.velocity = np.zeros(self.ndim)
class Model:
def __init__(sel... | |
Add a sample gdb pretty printer for Vec<std::array> types | #
# Copyright 2015-2017 Michele "King_DuckZ" Santullo
#
# 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 appli... | |
Add source archiving to OpenSpending export (separate script) | import requests
import json
import sys
import os
def grab_source(url, output):
"""
Grab a source from a url and store it in an output file
This creates uses requests as a dependency because I'm lazy.
It probably would have taken me less time to just write it with
urllib than writing this docstrin... | |
Add a tool for linking in global python modules into our virtualenv | # Link in a module in the global Python site-packages the virtualenv that we are currently in
# Author: Luke Macken <lmacken@redhat.com>
import os
import sys
from glob import glob
from distutils.sysconfig import get_python_lib
def symlink_global_module_into_virtualenv(modulename, env):
for path in (get_python_li... | |
Add unique characters algorithm and tests | #!/Applications/anaconda/envs/Python3/bin
def main():
# Test suite
strings = [None, '', 'Young Frankenstein', 'Yodeling cat']
results = [False, True, False, True]
for i, s in enumerate(strings):
if has_unique_chars(s) == results[i]:
print('PASSED test case: {} returned {}'.format(s... | |
Add test for async Block | # -*- coding: utf-8 -*-
import aiounittest
from graphenecommon.utils import parse_time
from .fixtures_aio import fixture_data, Block, BlockHeader
class Testcases(aiounittest.AsyncTestCase):
def setUp(self):
fixture_data()
async def test_block(self):
block = await Block(1)
self.assertE... | |
Add test showing QuantilesGlobal works with categorical-only dataset | import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def gbm_quantiles_global_with_only_categorical_colums():
prostate_train = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate_train.cs... | |
Add simple code generation script | """This demonstration generates the relevant code from the Slate
expressions. Note that this is for code only; it's not solving any
particular PDE with given data.
See the main hybrid-mixed folder for an actual solution to a
mixed system using hybridization and static condensation.
"""
from firedrake import *
mesh = ... | |
Add utils to manage blueprints | from flask_restful import Api, output_json
def configure_api_from_blueprint(blueprint, route_tuples):
api = Api(blueprint, catch_all_404s=True)
api.representations = {
'application/json; charset=utf-8': output_json,
'application/json': output_json,
}
for route_tuple in route_tuples:
... | |
Add missing get token file | from keystoneauth1.identity import v3
from keystoneauth1 import session
from config import *
auth = v3.Password(auth_url=AUTH_URL,
user_domain_name='default',
username=USERNAME,
password=PASSWORD,
project_domain_name='default',
... | |
Add stub module for test suite. | # Copyright (C) 2013 by Alex Brandt <alunduil@alunduil.com>
#
# parameters is freely distributable under the terms of an MIT-style license.
# See COPYING or http://www.opensource.org/licenses/mit-license.php.
| |
Add management command to migrate tags to new_tags field | from django.core.management.base import BaseCommand
from TWLight.resources.models import Partner
class Command(BaseCommand):
help = "Migrates content from the tags column to the new_tags column"
def handle(self, *args, **options):
partners = Partner.objects.all()
for partner in partners:
... | |
Add script to patch old symbooglix results when boogie-runner classified hitting speculative paths as BOUND_HIT. This was a bad idea so this script changes those results to UNKNOWN but note we have the ``speculative_paths_nb`` attribute so that can be used to find the results where symbooglix hit speculative paths. | #!/usr/bin/env python
# vim: set sw=2 ts=2 softtabstop=2 expandtab:
"""
This script is designed to patch old symbooglix
results where hitting speculative paths was incorrect
treated as BOUND_HIT
"""
import argparse
import os
import logging
import sys
import yaml
from br_util import FinalResultType, classifyResult
try:... | |
Add data migrations for new processor place | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-09 08:20
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
PaymentMethod = apps.get_model("payment", "PaymentMethod")
for payment_method in PaymentMethod.objects.all():
... | |
Make migration file for Timetables administratorship | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-13 22:03
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | |
Add STATS type to display server uptime | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import now
from zope.interface import implements
class StatsUptime(ModuleData):
implements(IPlugin, IModuleData)
name = "StatsUptime"
def actions(self):
return [ ("statsruntype-uptime", 10, self.disp... | |
Add py solution for 529. Minesweeper | class Solution(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
r = len(board)
if r == 0:
return board
c = len(board[0])
if board[click[0]][click[1]] =... | |
Add script to convert the sporozyte data to something ilastik and our pipeline can use | import vigra
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Take two tiff files, one for the sporozite channel and one for the nucleus channel, \
and create two files needed for further processing: a 3-channel hdf5 volume and a 1-channel nucleus HDF5.',
... | |
Add Terminal class based on Qt | import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
class Terminal(QtGui.QWidget):
VSIZE = 25
HSIZE = 80
HEIGHT = 378
WIDTH = 644
def __init__(self):
super(Terminal, self).__init__()
self.buffer = []
for y in range(self.VSIZE):
self.buffe... | |
Add utility module for working with the Node type | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 ... | |
Add py solution for 690. Employee Importance | """
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordina... | |
Add test for CLI parse | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_p... | |
Test of TTLL5 page passes. |
import unittest
import runserver
class GenePageTestCase(unittest.TestCase):
def setUp(self):
runserver.app.config['TESTING'] = True
self.app = runserver.app.test_client()
def tearDown(self):
pass
# import this TODO LMTW
def login(self, username, password):
return... | |
Revert "Revert "the util to combine message"" | # -*- coding: utf-8 -*-
__author__ = 'stefanie & DJ'
'''
'''
import sys, os, re, shutil
def analyzeTopics(inputTopic):
str = inputTopic.read()
strwithoutEnter = str.replace("\n", "")
#In this case, '' should be in the beginning since it's before Topic 0
lineTopics = strwithoutEnter.split("Topic")
p... | |
Add script to monitor for containers sharing an IP | import sys
from collections import defaultdict
from paasta_tools.utils import get_docker_client
def main():
docker_client = get_docker_client()
ip_to_containers = defaultdict(list)
for container in docker_client.containers():
networks = container['NetworkSettings']['Networks']
if 'bridge... | |
Add test that tabs through and clicks the active element | from seleniumbase import BaseCase
class CycleTests(BaseCase):
def test_cycle_elements_with_tab_and_press_enter(self):
""" Test pressing the tab key to cycle through elements.
Then click on the active element and verify actions.
This can all be performed by using a single com... | |
Add a simple demo code to use the ADS1015 driver | #Demo code for the Adafruit ADS1015 board using the Raspberry Pi
#The driver can also be used with the Ready pin using a GPIO to
#be used in an interrupt mode.
import Rpi.spi as SPI
import ads1015
DEVICE_ADDRESS = 0x48
SPI_PORT = 1
spi = SPI.spi(SPI_PORT,DEVICE_ADDRESS)
adc = ads1015.ads1015(spi)
adc.setchannel(0, T... | |
Add config file for Grande Synthe France | # -*- coding: utf-8 -*-
"""Ideaxbox for Grande Synthe, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Grande-Synthe"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPOR... | |
Correct regridded mask and model |
'''
Swap the spatial axes. Swap the spectral and stokes axes.
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
hdu[0].data = hdu[0].data[:, :, ::-1, ::-1]
hdu.flush()
execfile("~/Dropbox/code_development/ewky_scripts/header_swap_axis... | |
Add protein preview generation script | ##This script takes a path with PDB files, an output path and a csv file as inputs, and creates a high quality static image
#of each uniprot in the csv file in the right orientation, coloured by secondary structure
#The CSV file contains a column with uniprot ids, a column with the pdb file that contains the best chain... | |
Add migration that removes bank_account_reviewed flag on project | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-12-07 13:35
from __future__ import unicode_literals
import bluebottle.utils.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0083_auto_20181129_1506'),
]
operations = [
... | |
Add file that was omitted from previous commit | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, User, Business, Category, Account, Transaction, AccountUser
engine = create_engine('sqlite:///bam.db')
Base.metadata.bind = engine
Base.metadata.drop_all(engine) # Drop all existing tables
Base.metadata.crea... | |
Add motion sensor python script. | import time
import RPi.GPIO as GPIO
from blink2 import Blink
GPIO.setmode(GPIO.BCM)
pir_pin = 23
GPIO.setup(pir_pin, GPIO.IN) # activate input
i = 0
while True:
if GPIO.input(pir_pin):
i += 1
print("%i PIR ALARM!" % i)
Blink(27, 3, 0.3)
GPIO.setmode(GPIO.BCM)
GPI... | |
Add class specific for IVoiSys to do DB auth. | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | |
Add skipped and addSkip() to PageTestResults, for Python < 2.7. | # 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.
import traceback
import unittest
class PageTestResults(unittest.TestResult):
def __init__(self):
super(PageTestResults, self).__init__()
self.... | # 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.
import traceback
import unittest
class PageTestResults(unittest.TestResult):
def __init__(self):
super(PageTestResults, self).__init__()
self.... |
Implement class for connect to DB | import psycopg2 as pg_driver
class DBService:
def __init__(self, user, password, host, dbname):
self.db = pg_driver.connect(user=user, password=password, host=host, dbname=dbname)
self.cur = self.db.cursor()
def __del__(self):
self.db.close()
def get_url(self):
self.cur.e... | |
Add basic unittests for _Response initialization | """Unit test some basic response rendering functionality.
These tests use the unittest.mock mechanism to provide a simple Assistant
instance for the _Response initialization.
"""
from unittest.mock import patch
from flask import Flask
from flask_assistant import Assistant
from flask_assistant.response import _Respons... | |
Add tests for ssh keys (first draft) | """Test for `maas.client.viscera.sshkeys`."""
from maas.client.viscera import Origin
from .. import sshkeys
from ...testing import TestCase
from ..testing import bind
def make_origin():
return bind(sshkeys.SSHKeys, sshkeys.SSHKey)
class TestSSHKeys(TestCase):
def test__sshkeys_read(self):
""" SSHK... | |
Add managment command clear redis computing keys | from django.core.management.base import BaseCommand
from utils.redis_store import store
class Command(BaseCommand):
help = 'Remove all computing keys stored in Redis Store. Use it as python manage.py clear_store'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
c... | |
Save users' following into file | """
instabot example
Workflow:
Save users' following into a file.
"""
import argparse
import os
import sys
from tqdm import tqdm
sys.path.append(os.path.join(sys.path[0], '../'))
from instabot import Bot
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-u', type=str, help="us... | |
Add category id filtering to subcategories | from django.shortcuts import render
from django.views.generic import TemplateView
from rest_framework import viewsets, filters
from books.models import Book, Category, SubCategory
from books.serializers import BookSerializer, CategorySerializer, SubCategorySerializer
class HomeTemplateView(TemplateView, ):
templat... | from django.shortcuts import render
from django.views.generic import TemplateView
from rest_framework import viewsets, filters
from books.models import Book, Category, SubCategory
from books.serializers import BookSerializer, CategorySerializer, SubCategorySerializer
class HomeTemplateView(TemplateView, ):
templat... |
Add test case which tests for proper deprecated output based on virtualenv version. | # -*- coding: utf-8 -*-
'''
tests.unit.modules.virtualenv_test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
'''
import sys
# I... | |
Implement a function called closest_power | # Problem 4
# 10.0 points possible (graded)
# Implement a function called closest_power that meets the specifications below.
# For example,
# closest_power(3,12) returns 2
# closest_power(4,12) returns 2
# closest_power(4,1) returns 0
def closest_power(base, num):
'''
base: base of the exponential, integer > 1
... | |
Add Tests for Changes of Certificate | """Tests for changes on certificates by Edraak"""
from django.test.utils import override_settings
from lms.djangoapps.certificates.api import get_certificate_url
from lms.djangoapps.certificates.models import CertificateTemplate
from lms.djangoapps.certificates.tests.test_webview_views import CommonCertificatesTestC... | |
Add file for Code Fights array packing problem | #!/usr/local/bin/python
# Code Fights Are Equally Strong Problem
def arrayPacking():
pass
def main():
tests = [
[],
[]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], ... | |
Add in script to track new account activity | #!/usr/bin/env python
from datetime import datetime
from pymongo import MongoClient
import re
from subprocess import call
import sys
# minutes
window = 30
if len(sys.argv) != 2:
print 'Usage: %s <logfile>' % sys.argv[0]
sys.exit(1)
now = datetime.now()
logformat = re.compile('(\d{4}-\d\d-\d\d \d\d:\d\d:\d\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.