Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add parametric map generator, good for wrinkles | #!/usr/bin/python
#import lxml.etree
#import lxml.builder
from lxml import etree
#E = lxml.builder.ElementMaker()
#KINBODY=E.KinBody
#BODY=E.Body
#GEOM=E.Geom
#EXTENTS=E.Extents
#TRANSLATION=E.Translation
#DIFUSSECOLOR=E.diffuseColor
# User variables
nX = 3
nY = 2
boxHeight = 1.0
resolution = 2.0 # Just to make s... | |
Create pldm related specific constants file. | #!/usr/bin/python
r"""
Contains PLDM-related constants.
"""
PLDM_TYPE_BASE = '00'
PLDM_TYPE_PLATFORM = '02'
PLDM_TYPE_BIOS = '03'
PLDM_TYPE_OEM = '3F'
PLDM_BASE_CMD = {
'GET_TID': '2',
'GET_PLDM_VERSION': '3',
'GET_PLDM_TYPES': '4',
'GET_PLDM_COMMANDS': '5'}
PLDM_SUCCESS = '00'
PLDM_ERROR = '01'
PL... | |
Add a check for keystone expired tokens buildup. | #!/opt/openstack/current/keystone/bin/python
#
# Copyright 2015, Jesse Keating <jlk@bluebox.net>
#
# 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... | |
Add test for input setup workflow | import os
import unittest
import cea.config
from cea.utilities import create_polygon
from cea.datamanagement import zone_helper, surroundings_helper, terrain_helper, streets_helper, data_initializer, \
archetypes_mapper
# Zug site coordinates
POLYGON_COORDINATES = [(8.513465734818856, 47.178027239429234), (8.5154... | |
Add script to fix all notions | from alignements_backend.db import DB
from alignements_backend.notion import Notion
for notion in DB.scan_iter(match='notion:*'):
n = Notion(list(DB.sscan_iter(notion)))
| |
Add a test for 'version. | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Test the version here.
#
import pytest
from pycket.test.testhelper import check_equal
EXPECTED_VERSION='6.1.1.8'
def test_version():
check_equal('(version)', '"%s"' % EXPECTED_VERSION)
# EOF
| |
Add apigateway integration test for PutIntegration | # Copyright 2015 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 accompa... | |
Clean up db script (remove articles older than two days). | from pymongo import MongoClient
from fetch_stories import get_mongo_client, close_mongo_client
from bson import ObjectId
from datetime import datetime, timedelta
def remove_old_stories():
client = get_mongo_client()
db = client.get_default_database()
article_collection = db['articles']
two_days_ag... | |
Add migration to add china region | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-06-24 21:52
from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
Region = apps.get_model('common.Region')
region_to_add = 'China'
try:
Region.objects.get(name=region_to_add)
exc... | |
Create Content Loader app to Herd/DM standards - Configure Pyinstaller | hiddenimports = [
'numpy',
'pandas._libs.tslibs.timedeltas',
'pandas._libs.tslibs.nattype',
'pandas._libs.tslibs.np_datetime',
'pandas._libs.skiplist'
]
| |
Add unit test for data integrity. | import ConfigParser
import csv
import unittest
class DataTest(unittest.TestCase):
def setUp(self):
config = ConfigParser.RawConfigParser()
config.read('../app.config')
# Load the data from the csv into an array
self.data = []
with open('../data/%s' % config.get('data', ... | |
Add eval dispatch (copied from compyle) | from keywords import *
from reg import *
from parse import parse
def evalExp():
expr = parse(fetch(EXPR)) # make dedicated fetch_expr()?
# expr = transformMacros(expr)
evalFunc = getEvalFunc(expr)
# evalFunc()
# reassign next step
def getEvalFunc(expr):
if isVar(expr):
return compVar
if isNum(expr):
retur... | |
Add Himax motion detection example. | # Himax motion detection example.
import sensor, image, time, pyb
from pyb import Pin, ExtInt
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
sensor.set_framerate(15)
sensor.ioctl(sensor.IOCTL_HIMAX_MD_THRESHOLD, 0x01)
sensor.ioctl(sensor.IOCTL_HIMAX_MD_WINDOW, (0, 0, 320, 240... | |
Add tests for internal gregorian functions. | import unittest
from calexicon.internal.gregorian import is_gregorian_leap_year
class TestGregorian(unittest.TestCase):
def test_is_gregorian_leap_year(self):
self.assertTrue(is_gregorian_leap_year(2000))
self.assertTrue(is_gregorian_leap_year(1984))
self.assertFalse(is_gregorian_leap_yea... | |
Add unit tests for bandit.core.issue | # -*- coding:utf-8 -*-
#
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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
#
# Unl... | |
Add python to make vv h5 file | import tables
vv_desc = dict(
obsid=tables.IntCol(pos=0),
revision=tables.IntCol(pos=1),
most_recent=tables.IntCol(pos=2),
slot=tables.IntCol(pos=3),
type=tables.StringCol(10,pos=4),
n_pts=tables.IntCol(pos=5),
rad_off=tables.FloatCol(pos=6),
frac_dy_big=tables.FloatCol(pos=7),
frac_dz_big=tables.FloatCol(pos=8),
frac... | |
Create Python object detection script. | '''
Created on Feb 28, 2014
@author: Vance Zuo
'''
import numpy
import cv2
class ObjectDetector(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
self.bg_img = None
self.fg_img = None
return
def load_image(self, b... | |
Add a hex dump utility class. | # This hack by: Raymond Hettinger
class hexdumper:
"""Given a byte array, turn it into a string. hex bytes to stdout."""
def __init__(self):
self.FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' \
for x in range(256)])
def dump(self, src, length=8):
result=[]
for i in xrange(0, len(src... | |
Add new test setup required for py.test/django test setup | import os
import django
os.environ['DJANGO_SETTINGS_MODULE'] = 'testsettings'
# run django setup if we are on a version of django that has it
if hasattr(django, 'setup'):
# setup doesn't like being run more than once
try:
django.setup()
except RuntimeError:
pass | |
Add unit tests for security_scan | #!/usr/bin/env python
# Copyright (c) 2017 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
# pylint: d... | |
Add new layout window command | import sublime, sublime_plugin
class NewLayoutCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
self.view.window().run_command("set_layout", args)
self.view.window().run_command("focus_group", { "group": 0 })
self.view.window().run_command("move_to_group", { "group": 1 } )
| |
Add script to generate big RUM_* files | from rum_mapping_stats import aln_iter
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--times', type=int)
parser.add_argument('--max-seq', type=int)
parser.add_argument('rum_file', type=file)
args = parser.parse_args()
alns = list(aln_iter(args.rum_file))
for t in range(args.tim... | |
Copy old script from @erinspace which added identifiers to existing preprints. | import sys
import time
import logging
from scripts import utils as script_utils
from django.db import transaction
from website.app import setup_django
from website.identifiers.utils import request_identifiers_from_ezid, parse_identifiers
setup_django()
logger = logging.getLogger(__name__)
def add_identifiers_to_pre... | |
Add unit tests for lazy strings | import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
from stringlike.lazy import LazyString, CachedLazyString
from unittest import main, TestCase
class TestLazyString(TestCase):
def test_equality(self):
self.assertEqual(LazyString(lambda: 'abc'), ... | |
Use filfinder to get the average radial width of features in the moment 0 |
from fil_finder import fil_finder_2D
from basics import BubbleFinder2D
from spectral_cube.lower_dimensional_structures import Projection
from astropy.io import fits
from radio_beam import Beam
from astropy.wcs import WCS
import astropy.units as u
import matplotlib.pyplot as p
'''
Filaments in M33? Why not?
'''
mom0_... | |
Add the model.py file declarative generated from mysql. | #autogenerated by sqlautocode
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation
engine = create_engine('mysql://monty:passwd@localhost/test_dia')
DeclarativeBase = declarative_base()
metadata = DeclarativeBase.metadata
metadata.bind = engine
class Me... | |
Add staff permissions for backup models | from nodeconductor.core.permissions import StaffPermissionLogic
PERMISSION_LOGICS = (
('backup.BackupSchedule', StaffPermissionLogic(any_permission=True)),
('backup.Backup', StaffPermissionLogic(any_permission=True)),
)
| |
Implement DispatchLoader (metapath import hook) | from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stack import Stack
from stackable.utils import StackablePickler
from stackable.network import StackableSocket, StackablePacketAssembler
from sys import modules
from types import ModuleType
class DispatchLoader(object):
d... | |
Add driver to find plate solutions | import babeldix
import sys
import operator
# Print solutions in order of increasing score
for plate in sys.argv[1:]:
solns = babeldix.Plates.get_solutions(plate)
for (soln,score) in sorted(solns.items(), key=operator.itemgetter(1)):
print '{0:s} {1:d} {2:s}'.format(plate,score,soln)
| |
Add handler for concurrently logging to a file |
'''
Utilities to assist with logging in python
'''
import logging
class ConcurrentFileHandler(logging.Handler):
"""
A handler class which writes logging records to a file. Every time it
writes a record it opens the file, writes to it, flushes the buffer, and
closes the file. Perhaps this could cre... | |
Add script that dumps the python path | #!/usr/bin/env python
import sys
# path[0], is the directory containing the script that was used to invoke the Python interpreter
for s in sorted(sys.path[1:]):
print s
| |
Create stub for 2016 NFLPool player picks |
stone = {"firstname": "chris", "lastname": "stone", "timestamp": "9/6/2016", "email": "stone@usisales.com",
"afc_east_1": "Patriots", "afc_east_2": "Jets", "afc_east_last": "Bills", "afc_north_1": "Steelers",
"afc_north_2": "Bengals", "afc_north_last": "Browns", "afc_south_1": "Colts", "afc_south_2"... | |
Create test case for tail from file | """
Tests for the tail implementation
"""
from tail import FileTail
def test_tail_from_file():
"""Tests that tail works as advertised from a file"""
from unittest.mock import mock_open, patch
# The mock_data we are using for our test
mock_data = """A
B
C
D
E
F
"""
mocked_open = mock_open(read_da... | |
Add page extension for tracking page creation and modification dates. | """
Track the modification date for pages.
"""
from datetime import datetime
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
def register(cls, admin_cls):
cls.add_to_class('creation_date', models.DateTimeField(_... | |
Add starter code for Lahman db | ################################################
# WORK IN PROGRESS: ADD LAHMAN DB TO PYBASEBALL
# TODO: Make a callable function that retrieves the Lahman db
# Considerations: users should have a way to pull just the parts they want
# within their code without having to write / save permanently. They should
# also ha... | |
Add a body to posts | from django.contrib.auth.models import User
from django.db import models
class Discussion(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=255)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Post(models.Model):
discussion = models... | from django.contrib.auth.models import User
from django.db import models
class Discussion(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=255)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Post(models.Model):
discussion = models... |
Add initial test for binheap | import pytest
from binheap import Binheap
def test_init_bh():
b = Binheap()
assert b.binlist is []
c = Binheap([1, 2])
assert c.binlist == [1, 2]
| |
Add an utility getting the free proxy from the certain site. | import json
import time
import traceback
import requests
from lxml import etree
def updateProxy():
with open('F:\liuming\Shadowsocks\gui-config.json', encoding='utf-8', mode='r') as file:
proxyInfo = json.load(file)
while 1:
requestHeaders = {
'Accept-Encoding': 'gzip, deflate, sd... | |
Add new local dependency of scripts. | """Utility functions not closely tied to other spec_tools types."""
# Copyright (c) 2018-2019 Collabora, Ltd.
# Copyright (c) 2013-2019 The Khronos Group 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... | |
Send subtitles_published signal for bulk approvals | from django.contrib.contenttypes.models import ContentType
from subtitles.models import SubtitleLanguage
from teams.signals import api_subtitles_approved
from utils.csv_parser import UnicodeReader
from videos.tasks import video_changed_tasks
def complete_approve_tasks(tasks):
lang_ct = ContentType.objects.get_for_... | from django.contrib.contenttypes.models import ContentType
from subtitles.models import SubtitleLanguage
from subtitles.signals import subtitles_published
from teams.signals import api_subtitles_approved
from utils.csv_parser import UnicodeReader
from videos.tasks import video_changed_tasks
def complete_approve_tasks(... |
Introduce fuse module to mount Registry Ellipticsbased FS | #!/usr/bin/env python
from __future__ import with_statement
import logging
import os
import sys
import stat
import yaml
from fuse import FUSE, FuseOSError, Operations, LoggingMixIn
from docker_registry.drivers.elliptics import Storage
logging.basicConfig()
log = logging.getLogger("")
log.setLevel(logging.DEBUG)
D... | |
Add script to automate plugin testing on Windows | import os, time, sys, time
from shutil import copy
watched_file = sys.argv[1]
addon_path = sys.argv[2]
os.startfile(r'C:\Program Files (x86)\Anki\anki.exe')
new_t = old_t = 0
while 1:
old_t = new_t
new_t = os.stat(watched_file)[8]
if old_t != new_t:
copy(watched_file, addon_path)
os.system("TASKKILL /F /IM an... | |
Add shot attempt item class definition | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import uuid
from db.common import Base
from db.specific_event import SpecificEvent
class ShotAttempt(Base, SpecificEvent):
__tablename__ = 'shot_attempts'
__autoload__ = True
STANDARD_ATTRS = [
"game_id", "team_id", "event_id", "player_id", "shot_at... | |
Add script to turn off all non-build nodes | #
# Copyright 2012 Cisco Systems, Inc.
#
# Author: Soren Hansen <sorhanse@cisco.com>
#
# 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... | |
Add FFmpeg module for converting video files into image sequences |
__author__ = 'Konstantin Dmitriev'
from renderchan.module import RenderChanModule
from renderchan.utils import which
import subprocess
import os
import random
class RenderChanFfmpegModule(RenderChanModule):
def __init__(self):
RenderChanModule.__init__(self)
if os.name == 'nt':
self.... | |
Add class for updating stock | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class StockUpdater:
def __init__(self, db_connection):
self.db_connection = db_connection
def set_items(self, items):
self.items = items
def set_table(self, table):
self.table = table
def set_destination_colums(self, product_code... | |
Add initial helper functions for connecting to LDAP | # Handles queries to the LDAP backend
# Reads the LDAP server configuration from a JSON file
import json
import ldap
first_connect = True
# The default config filename
config_file = 'config.json'
def load_config():
with open(config_file, 'r') as f:
config = json.load(f)
ldap_server = config['ldap_ser... | |
Add db migration for user table | """Add user model
Revision ID: 70c7d046881
Revises: 19b7fe1331be
Create Date: 2013-12-07 15:30:26.169000
"""
# revision identifiers, used by Alembic.
revision = '70c7d046881'
down_revision = '19b7fe1331be'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - p... | |
Add script to test cuda via numba | # install nvidia-cuda-toolkit into the OS
# conda install numba
# conda install cudatoolkit -- otherwise will error out
import numpy as np
from numba import vectorize
from time import perf_counter
@vectorize(['float32(float32, float32)'], target='cuda')
def add_by_gpu(a, b):
return a + b
@vectorize(['float32(flo... | |
Add a log importer for logs that need indexing. | # Copyright (c) Weasyl LLC
# See COPYING for details.
import argparse
import datetime
import os.path
import re
import elastirc
from whoosh import index
line_pattern = re.compile(
r'(?P<time>[0-9:]{8}) (?P<formatted>'
r'\(-\) (?P<actor>[^ ]+?) '
r'(?P<action>joined|parted|quit'
r'|was kick... | |
Add utility for sending commands for testing | #!/usr/bin/env python
import sys
import getmetric
def main():
output = getmetric.sshcmd(sys.argv[1], sys.argv[2])
print output
if __name__ == '__main__':
sys.exit(main())
| |
Add script for getting pf label counters | #!/usr/bin/env python
"""igcollect - FreeBSD Packet Filter
Copyright (c) 2018 InnoGames GmbH
"""
from __future__ import print_function
from argparse import ArgumentParser
from socket import gethostname
from subprocess import check_output
import re
import time
def parse_args():
parser = ArgumentParser()
pars... | |
Add db migration for adding email address field in Account Table | """Add email address in Account Table for sending mailers.
Revision ID: 8cf43589ca8b
Revises: 3828e380de20
Create Date: 2018-08-28 12:47:31.858127
"""
# revision identifiers, used by Alembic.
revision = '8cf43589ca8b'
down_revision = '3828e380de20'
from alembic import op
import sqlalchemy as sa
def upgrade():
... | |
Add initial unit tests for SortedSet. | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import pytest
from clique.sorted_set import SortedSet
@pytest.fixture
def standard_set(request):
'''Return sorted set.'''
return SortedSet([4, 5, 6, 7, 2, 1, 1])
@pytest.mark.parametrize(('item', 'expec... | |
Add test for rendering WListBox in case of non-str content. | import unittest
from picotui.widgets import WListBox
from picotui.defs import KEY_DOWN
from picotui.context import Context
class User:
def __init__(self, name, age):
self.name = name
self.age = age
class UserListBox(WListBox):
def __init__(self, width, height, items):
super().__init_... | |
Add configuration for Zaatari, Jordan. | # -*- coding: utf-8 -*-
"""Ideaxbox for Zaatari, Jordan"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Zaatari"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['SY', 'JO']
TIME_ZONE = 'Asia/Amman'
LANGUAGE_CODE = 'ar'
LOAN_DURATION = 14
MONITORING_ENTRY_EXP... | |
Add function to not verify ssl | import ssl
def fix_ssl_verify():
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
... | |
Add script for splitting an auth dump on primary field presence | #!/usr/bin/env python
from __future__ import unicode_literals, print_function
import re
from os import makedirs, path as P
find_token = re.compile(r'{"(100|110|111|130|148|150|151|155|162|180|181|182|185)":').findall
def split_auth_source(sourcefile, outdir):
name_parts = P.basename(sourcefile).split('.', 1)
... | |
Create DataApp app hook for CMS | from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
class DataApp(CMSApp):
name = 'Data App'
urls = ['cms_lab_data.urls']
app_name = 'cms_lab_data'
apphook_pool.register(DataApp)
| |
Add test cases for override_config | from django.test import TestCase
from constance import config
from constance.test import override_config
class OverrideConfigFunctionDecoratorTestCase(TestCase):
"""Test that the override_config decorator works correctly.
Test usage of override_config on test method and as context manager.
"""
def t... | |
Add first basic unittests using py.test | """
test_validators
~~~~~~~~~~~~~~
Unittests for bundled validators.
:copyright: 2007-2008 by James Crasta, Thomas Johansson.
:license: MIT, see LICENSE.txt for details.
"""
from py.test import raises
from wtforms.validators import ValidationError, length, url, not_empty, email, ip_addres... | |
Add a simple test case for LawrenceTransitProvider | import busbus
from busbus.provider.lawrenceks import LawrenceTransitProvider
import arrow
import pytest
@pytest.fixture(scope='module')
def lawrenceks_provider():
return LawrenceTransitProvider()
def test_43_to_eaton_hall(lawrenceks_provider):
stop = lawrenceks_provider.get(busbus.Stop, u'15TH_SPAHR_WB')
... | |
Add crop multi roi alternative script | # @DatasetService datasetservice
# @ImageDisplayService displayservice
# @ImageJ ij
# @AbstractLogService log
# @DefaultLegacyService legacyservice
from ij import IJ
from ij import Macro
from ij.plugin.frame import RoiManager
from io.scif.img import ImgSaver
from net.imagej import DefaultDataset
from loci.plugins im... | |
Add script to download wheels from appveyor | #!/usr/bin/env python3
import asyncio
import json
import pathlib
import sys
from tornado.httpclient import AsyncHTTPClient
BASE_URL = "https://ci.appveyor.com/api"
async def fetch_job(directory, job):
http = AsyncHTTPClient()
artifacts = await http.fetch(f"{BASE_URL}/buildjobs/{job}/artifacts")
paths = ... | |
Add command to print the syntax tree for a script | #!/usr/bin/env python
# -*- 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... | |
Test case for the failure to compile code including unicode characters. | # coding: utf-8
"""These tests have to be run separately from the main test suite (iptest),
because that sets the default encoding to utf-8, and it cannot be changed after
the interpreter is up and running. The default encoding in a Python 2.x
environment is ASCII."""
import unittest, sys
from IPython.core import com... | |
Enforce better security in sample ReST renderer. | from __future__ import unicode_literals
try:
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
parts = publish_parts(source=markup, writer_name="html4css1", settings_overrides=docutils_settings)
return parts["html_body"]
except ImportError:
pass
| from __future__ import unicode_literals
try:
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
docutils_settings.update({
'raw_enabled': False,
'file_insertion_enabled': False,
})
parts = publish_parts(
source=mar... |
Add a small script for rapidly verifyinh IGV screenshots | import os
import click
import cv2
from AppKit import NSScreen
def check_image(filename, height):
image = cv2.imread(filename)
image_name = os.path.basename(filename)
is_positive = _check(image, image_name, height)
return image_name, is_positive
def _check(image, image_name, target_height):
cv2.n... | |
Add script to parse the results | #!/usr/bin/python
# coding: utf-8
import fileinput
import sys
buffer_size = 0
threshold = 0
elapsed_time = 0.0
for line in fileinput.input():
l = line.split()
if l:
if l[0] == 'IMPORTANT:':
if l[1] == 'Maximum':
pass
elif l[1] == 'Buffer':
buffe... | |
Add migration for modified RegexValidator | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import project.teams.models
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('teams', '0007_auto_20150907_1808'),
]
operations = [
migrations.Al... | |
Update migrations to match current model | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-20 01:05
from __future__ import unicode_literals
from django.db import migrations, models
import main.models
class Migration(migrations.Migration):
dependencies = [
('main', '0008_auto_20161014_1424'),
]
operations = [
migr... | |
Add db model for TestMessage database | import uuid
from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Index
from changes.config import db
from changes.db.types.guid import GUID
class TestMessage(db.model):
"""
The message produced by a run of a test.
This is generally cap... | |
Add a put_object sample script. | #!/usr/bin/env python
import pprint
import sys
from os import environ as env
from swiftclient.client import get_auth, put_object, put_container
from swiftclient.exceptions import ClientException
auth_url = env.get('OS_AUTH_URL')
account = env.get('OS_TENANT_NAME')
user = env.get('OS_USERNAME')
key = env.get('OS_PASS... | |
Add form validation for target | from django.forms import ModelForm
from breach.models import Target
class TargetForm(ModelForm):
class Meta:
model = Target
fields = (
'name',
'endpoint',
'prefix',
'alphabet',
'secretlength',
'alignmentalphabet',
... | |
Add script for adding B/W locations | #!/usr/bin/env python2
from codecs import open
from pokedex.db import connect, identifier_from_name
from pokedex.db.tables import Language
from pokedex.db.tables import Location, LocationGameIndex
session = connect()
en = session.query(Language).filter_by(identifier='en').one() # English
ja = session.query(Language... | |
Package for Melange specific views added. | # Copyright 2013 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 applicable law or agreed to in wr... | |
Add a data migration to move more ResultEvent fields to Popolo models | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def migrate_remaining_fields_to_popolo_models(apps, schema_editor):
ResultEvent = apps.get_model('results', 'ResultEvent')
Organization = apps.get_model('popolo', 'Organization')
Post = apps.get_model('popolo... | |
Add some simple tests for file formats. | #!/usr/bin/python
import unittest
from blivet.formats import device_formats
import blivet.formats.fs as fs
class MethodsTestCase(unittest.TestCase):
"""Test some methods that do not require actual images."""
def setUp(self):
self.fs = {}
for k, v in device_formats.items():
if iss... | |
Add kubernetes.client.apis as an alias to kubernetes.client.api | from __future__ import absolute_import
import warnings
# flake8: noqa
# alias kubernetes.client.api package and print deprecation warning
from kubernetes.client.api import *
warnings.filterwarnings('default', module='kubernetes.client.apis')
warnings.warn(
"The package kubernetes.client.apis is renamed and depre... | |
Relocate dict generator for the locations. | def get_location_dict(item, location_type):
return {
'type': location_type,
'latitude': item.position.latitude,
'longitude': item.position.longitude,
'name': item.name,
'website': item.get_absolute_url(),
'category': '',
'image': '',
'content': item.na... | |
Update enabled to be simpler and match rpc-openstack. | DASHBOARD = 'rackspace'
ADD_INSTALLED_APPS = [
'rackspace',
]
ADD_ANGULAR_MODULES = ['horizon.dashboard.rackspace']
# If set to True, this dashboard will not be added to the settings.
DISABLED = False
| |
Install CMake in system dirs | #!/usr/bin/env python
# Build the project with Biicode.
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz',... | #!/usr/bin/env python
# Build the project with Biicode.
import bootstrap, glob, os, shutil
from download import Downloader
from subprocess import check_call
os_name = os.environ['TRAVIS_OS_NAME']
if os_name == 'linux':
# Install newer version of CMake.
bootstrap.install_cmake(
'cmake-3.1.1-Linux-i386.tar.gz',... |
Create migration file for accounts app | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-05-07 19:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20150629_1908'),
]
operations = [
migrations.AlterField(... | |
Add example for Top-K with Others. | """
Top-K plot with Others
----------------------
This example shows how to use aggregate, window, and calculate transfromations
to display the top-k directors by average worldwide gross while grouping the
remaining directors as 'All Others'.
"""
# category: case studies
import altair as alt
from vega_datasets import ... | |
Add bias to cosine distance for two tower models | ## @package add_bias
# Module caffe2.python.layers.add_bias
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import (
ModelLayer,
LayerPara... | |
Add inital MI feature selection code | import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import chi2, SelectKBest
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
from sklearn.model_selection import cross_val_score
data = pd.read_table("data/WebKB/... | |
Fix for display date repeat of YYYY | # -*- coding: utf-8 -*-
import re
r=re.compile(r'(\d\d\d\d)-\1')
def fix_repeated_date(doc):
dates = doc['sourceResource'].get('date', None)
if dates:
if isinstance(dates, list):
new_dates = []
for d in dates:
disp_date = d.get('displayDate', '')
... | |
Reimplement setup and teardown of TestVCSPrompt | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_vcs_prompt
---------------
"""
import os
import pytest
from cookiecutter import utils
@pytest.fixture
def clean_cookiecutter_dirs(request):
if os.path.isdir('cookiecutter-pypackage'):
utils.rmtree('cookiecutter-pypackage')
os.mkdir('cookiecutte... | |
Add crawler for 'Geek and Poke' | from comics.aggregator.crawler import BaseComicCrawler
from comics.meta.base import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Geek and Poke'
language = 'en'
url = 'http://www.geekandpoke.com/'
start_date = '2006-08-22'
history_capable_days = 32
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
... | |
Add utility to get mac address from host. | import logging
import re
import socket
from subprocess import Popen, PIPE
logger = logging.getLogger(__name__)
def get_mac_address(host):
""" Returns MAC address for a hostname. """
mac_pattern = '(([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})'
try:
host = socket.gethostbyname(host)
except socket.erro... | |
Add example for adding comments that runs against a real server | import bugsy
bz = bugsy.Bugsy("username", "password", "https://bugzilla-dev.allizom.org/rest")
bug = bugsy.Bug()
bug.summary = "I love cheese"
bug.add_comment('I do love sausages too')
bz.put(bug)
bug.add_comment('I do love eggs too')
| |
Update submission for Day 5 | #Day 5: Count Vowels
#This program counts the number of vowels in the entered string.
#For added complexity, it reports a sum of each vowel found in a long text.
inputString = raw_input("Enter the string to be evaluated:")
lowerCaseString = str.lower(inputString)
convertedListString = list(lowerCaseString)
aNum = co... | |
Add script to generate recovery time versus object size data | #!/usr/bin/env python
# Copyright (c) 2011 Stanford University
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ... | |
Add script to plot learning curve | #coding=utf-8
import sys
import argparse
import matplotlib.pyplot as plt
def parse_args():
parser = argparse.ArgumentParser('Parse Log')
parser.add_argument(
'--file_path', '-f', type=str, help='the path of the log file')
parser.add_argument(
'--sample_rate',
'-s',
type=fl... | |
Add implementation of the behave feature in steps | from behave import given, when, then
from appium import webdriver
import os
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
imp... | |
Add unit test for LpNorm | """
Test LpNorm cost
"""
import numpy
import theano
from theano import tensor as T
from nose.tools import raises
def test_shared_variables():
'''
LpNorm should handle shared variables.
'''
assert False
def test_symbolic_expressions_of_shared_variables():
'''
LpNorm should handle symbolic exp... | |
Add a basic vehicle model and garage | """
Tesla car model
"""
import uuid
import json
from random import choice
__OFF__ = 'off'
__ON__ = 'on'
__COLOR__ = ['black', 'white', 'red', 'brown', 'gold', 'pink']
JSONEncoder_old = json.JSONEncoder.default
def JSONEncoder_new(self, obj):
if isinstance(obj, uuid.UUID): return str(obj)
return JSONEncoder_o... | |
Remove end date from deed contributions | # Generated by Django 2.2.24 on 2021-12-09 15:40
from django.db import migrations
def fix_participant_dates(apps, schema_editor):
EffortContribution = apps.get_model('activities', 'EffortContribution')
EffortContribution.objects.update(end=None)
class Migration(migrations.Migration):
dependencies = [
... | |
Update migration to latest schedule work | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('schedule', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='slot',
options={'or... | |
Add basic tests for filters | import pytest
import helpers.filters as filters
class Model:
def __init__(self, value):
self.value = value
def test_select_filter():
test_objects = [
Model('a'),
Model('a'),
Model('b'),
Model('b'),
Model('c'),
]
tested_filter = filters.Filter(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.