Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Move docstring to appropriately placed comment | import textwrap
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_log... | import textwrap
def test_environ(script, tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.... |
Fix auth API usage (this is why we wait for CI) | import json
from zeus import auth
from zeus.api import client
from zeus.exceptions import ApiError
from zeus.models import Email, Identity
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(ma... | import json
from zeus import auth
from zeus.api import client
from zeus.exceptions import ApiError
from zeus.models import Email, Identity
from .base import Resource
from ..schemas import EmailSchema, IdentitySchema, UserSchema
emails_schema = EmailSchema(many=True, strict=True)
identities_schema = IdentitySchema(ma... |
Fix query extractor UTF-8 handling | #!/usr/bin/env python
"""
Script to extract and then generate random queries for fuzzy searching.
Usage:
./extract-random-queries.py <infile> <outfile>
"""
import os
from random import choice, randint, random
import string
from subprocess import call
import sys
from tempfile import mkstemp
__author__ = "Uwe L. K... | #!/usr/bin/env python
"""
Script to extract and then generate random queries for fuzzy searching.
Usage:
./extract-random-queries.py <infile> <outfile>
"""
import codecs
import os
from random import choice, randint, random
import string
from subprocess import call
import sys
from tempfile import mkstemp
__author... |
Add comment for full url with non guest user | # coding=utf-8
#
# Must be called in roche root dir
#
import os
from os import walk
from eulexistdb.db import ExistDB
#
# Timeout higher?
#
xmldb = ExistDB('http://54.220.97.75:8080/exist')
xmldb.createCollection('docker', True)
xmldb.createCollection('docker/texts', True)
os.chdir('../dublin-store')
for (dirpa... | # coding=utf-8
#
# Must be called in roche root dir
#
import os
from os import walk
from eulexistdb.db import ExistDB
#
# Timeout higher?
#
#
# http://username:password@54.220.97.75:8080/exist
#
xmldb = ExistDB('http://54.220.97.75:8080/exist')
xmldb.createCollection('docker', True)
xmldb.createCollection('docke... |
Disable mongo server for now | #!/usr/bin/python
# imports
from pprint import pprint
import urllib2
import socket
import sys
#import re
from bs4 import BeautifulSoup
from pymongo import MongoClient
# read the html content of the random pun page into a string
try:
html_content = urllib2.urlopen('http://www.punoftheday.com/cgi-bin/randompun.pl', t... | #!/usr/bin/python
# imports
from pprint import pprint
import urllib2
import socket
import sys
#import re
from bs4 import BeautifulSoup
from pymongo import MongoClient
# read the html content of the random pun page into a string
try:
html_content = urllib2.urlopen('http://www.punoftheday.com/cgi-bin/randompun.pl', t... |
Use OS-agnostic path joining operations | import yaml
import os, os.path
loc = os.path.dirname(os.path.abspath(__file__))
hosts = yaml.load(open(loc+'/hosts.yml'))
projects = yaml.load(open(loc+'/projects.yml'))
allocations = yaml.load(open(loc+'/allocations.yml'))
users = yaml.load(open(loc+'/users.yml'))
| import yaml
import os
loc = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(loc, 'hosts.yml'), 'r') as fr:
hosts = yaml.load(fr)
with open(os.path.join(loc, 'projects.yml'), 'r') as fr:
projects = yaml.load(fr)
with open(os.path.join(loc, 'allocations.yml'), 'r') as fr:
allocations = ya... |
Update preprocessor testdata to use grow.Preprocessor. | from grow import Preprocessor
from protorpc import messages
class CustomPreprocessor(Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
value = messages.StringField(1)
def run(self, **kwargs):
# To allow the test to check the result
self.pod._custom_prepr... | import grow
from protorpc import messages
class CustomPreprocessor(grow.Preprocessor):
KIND = 'custom_preprocessor'
class Config(messages.Message):
value = messages.StringField(1)
def run(self, **kwargs):
# To allow the test to check the result
self.pod._custom_preprocessor_value... |
Remove var declaration from abstract base class | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2015 Microsoft Corporation
#
# 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
#
# U... |
Add Google Webmaster verification handler. | import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(file('index.html').read())
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
| import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(file('index.html').read())
class GoogleWebmasterVerifier(webapp2.RequestHandler):
def get(self):
self.response.write(file('google7e0693b4ccda33f7.html').read())
application = webapp2.WSGIApplication([
... |
Include the requirements.txt contents in install_requires. | #!/usr/bin/env python
from setuptools import setup
version = "0.10"
setup(
name="pycoinnet",
version=version,
packages=[
"pycoinnet",
"pycoinnet.examples",
"pycoinnet.helpers",
"pycoinnet.peer",
"pycoinnet.peer.tests",
"pycoinnet.peergroup",
"pycoin... | #!/usr/bin/env python
from setuptools import setup
version = "0.19"
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setup(
name="pycoinnet",
version=version,
packages=[
"pycoinnet",
"pycoinnet.examples",
"pycoinnet.helpers",
"pycoinnet.peer",
... |
Upgrade requirements to be Django 1.2.5 | from setuptools import setup, find_packages
version = '1.2.0'
setup(name="Miro Community",
version=version,
packages=find_packages(),
author='Participatory Culture Foundation',
license='AGPLv3',
install_requires=['django==1.2.1'])
| from setuptools import setup, find_packages
version = '1.2.0'
setup(name="Miro Community",
version=version,
packages=find_packages(),
author='Participatory Culture Foundation',
license='AGPLv3',
install_requires=['django==1.2.5'])
|
Split out the dependencies of client and server. | from setuptools import setup
setup(
name="rotterdam",
version="0.3.2",
description=(
"Simple distributed job queue via redis."
),
author="William Glass",
author_email="william.glass@gmail.com",
url="http://github.com/wglass/rotterdam",
packages=["rotterdam"],
include_package... | from setuptools import setup
setup(
name="rotterdam",
version="0.3.2",
description=(
"Simple asynchronous job queue via redis."
),
author="William Glass",
author_email="william.glass@gmail.com",
url="http://github.com/wglass/rotterdam",
packages=["rotterdam"],
include_packag... |
Fix entry point for pretty printing script. | from setuptools import setup, find_packages
# Prevent "TypeError: 'NoneType' object is not callable" error
# when running python setup.py test
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
except ImportError:
pass
setup(
name='cmakelists_parsing',
ve... | from setuptools import setup, find_packages
# Prevent "TypeError: 'NoneType' object is not callable" error
# when running python setup.py test
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
except ImportError:
pass
setup(
name='cmakelists_parsing',
ve... |
Use mocking to fix the result of hashing files | """
Tests of overall functionality
"""
import pytest
import toolaudit
import yaml
def test_simple_audit(capsys):
"""
Check simple audit gives the expected output
"""
app = toolaudit.application.ToolauditApp()
try:
app.run(kitlist_file='test/example.yaml')
except SystemExit:
pa... | """
Tests of overall functionality
"""
import pytest
import toolaudit
import yaml
def test_simple_audit(capsys, monkeypatch):
"""
Check simple audit gives the expected output
"""
def mockreturn(path):
return '9c3bb3efa8095f36aafd9bf3a698efe439505021'
monkeypatch.setattr(toolaudit.readers,... |
Handle register flag; use CONN_MGR_PARAM_FLAG_REQUIRED not 1L | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name
object_path = "/org/freedesktop/Telepathy/ConnectionMana... | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
from telepathy.constants import CONN_MGR_PARAM_FLAG_REQUIRED, \
CONN_MGR_PARAM_FLAG_REGISTER
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_na... |
Test case: _check_max_active method to check both scenarios | import unittest
from liveblog.blogs.blogs import BlogService
from superdesk.errors import SuperdeskApiError
class BlogsTestCase(unittest.TestCase):
def setUp(self):
pass
def test_if_check_max_active(self):
increment = 10
"""so if check "subscription in SUBSCRIPTION_MAX_ACTIVE_BLOGS" p... | from liveblog.blogs import init_app
from superdesk.tests import TestCase
from superdesk import get_resource_service
from superdesk.errors import SuperdeskApiError
class BlogsTestCase(TestCase):
def setUp(self):
# from nose.tools import set_trace; set_trace()
init_app(self.app)
def test_if_no... |
Set the stride to scale | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=3))
model.summary()
# Data
train_set = '91-i... | """Example experiment."""
from functools import partial
from toolbox.data import load_set
from toolbox.models import compile
from toolbox.models import fsrcnn
from toolbox.experiment import FSRCNNExperiment
# Model
scale = 3
model = compile(fsrcnn(c=1, d=56, s=12, m=4, k=scale))
model.summary()
# Data
train_set = '... |
Add logic for displaying help if no args are specified. | """ A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
... | """ A simple CLI tool for quickly copying common emoticon/emoji to your
clipboard. """
import pyperclip
import json
import sys
import argparse
with open("mapping.json") as f:
emotes = json.load(f)
def main():
parser = argparse.ArgumentParser(
description=sys.modules[__name__].__doc__,
... |
Fix python 3 support for exec | import sys # Used to get rid of py2/3 differences
# Blatantly stolen from the excellent `six` library
# Allows the same calls between python2 and python3
if sys.version_info[0] == 3:
exec_ = getattr(__builtins__, "exec")
raw_input = input
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execu... | import sys # Used to get rid of py2/3 differences
# Blatantly stolen from the excellent `six` library
# Allows the same calls between python2 and python3
if sys.version_info[0] == 3:
exec_ = __builtins__["exec"]
raw_input = input
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code i... |
Fix bug in file path. | import os
import sh
from sh import docker
def setup_package():
"""
Sets up docker images and host containers for running the STs.
"""
# Pull and save each image, so we can use them inside the host containers.
print sh.bash("./build_node.sh").stdout
docker.save("--output", "calico_containers/ca... | import os
import sh
from sh import docker
def setup_package():
"""
Sets up docker images and host containers for running the STs.
"""
# Pull and save each image, so we can use them inside the host containers.
print sh.bash("./build_node.sh").stdout
docker.save("--output", "calico_containers/ca... |
Add a property to an exception class | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
class CommandError(Exception):
@property
def errno(self):
return self.__errno
def __init__(self, *args, **kwargs):
self.__errno = kwargs.pop... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
class CommandError(Exception):
@property
def cmd(self):
return self.__cmd
@property
def errno(self):
return self.__errno
def __init... |
Add the license header where it's missing. | import abc
import six
@six.add_metaclass(abc.ABCMeta)
class BaseBackend(object):
@abc.abstractmethod
def setup_instance(self):
"""Called by setUpClass to setup an instance"""
@abc.abstractmethod
def cleanup(self):
"""Needs to cleanup the resources created in ``setup_instance``"""
| # Copyright 2015 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
Update script to store the basename instead of the complete path | #!/usr/bin/env python
import click
import os
import codecs
import json
import pandas as pd
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_file', nargs=1, type=click.Path())
def nerstats(input_files, output_file):
output_dir = os.path.dirname(output_... | #!/usr/bin/env python
import click
import os
import codecs
import json
import pandas as pd
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_file', nargs=1, type=click.Path())
def nerstats(input_files, output_file):
output_dir = os.path.dirname(output_... |
Remove some route_base tests that are no longer valid with Flask 0.10 | from flask import Flask
from .view_classes import BasicView, RouteBaseView
from nose.tools import *
app = Flask('route_base')
BasicView.register(app, route_base="/rb_test/")
BasicView.register(app)
RouteBaseView.register(app, route_base="/rb_test2/")
RouteBaseView.register(app)
def test_registered_route_base():
... | from flask import Flask
from .view_classes import BasicView, RouteBaseView
from nose.tools import *
app = Flask('route_base')
RouteBaseView.register(app, route_base="/rb_test2/")
def test_route_base_override():
client = app.test_client()
resp = client.get('/rb_test2/')
eq_(b"Index", resp.data)
|
Add Vega Lite template test | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from .views import ChartsView
# Create your tests here.
class TestVegaLiteChartsView(TestCase):
def setUpTestCase(self):
self.chart_view = ChartsView()
# Set Vega Lite as template engine
self.chart_view.engine = "vegalite"
def test_vega_lite_template(s... |
Test missing content and failed navigation tests. | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..testcases import SeleniumLiveTestCase
class NavigationTestCase(SeleniumLiveTestCase):
test_templates = [
(r'^nav_1/$', 'nav_1.html'),
(r'^nav_1/nav_2/$', 'nav_2.html')
]
def test_get_page(self):
""" Test tha... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..testcases import SeleniumLiveTestCase
class NavigationTestCase(SeleniumLiveTestCase):
test_templates = [
(r'^nav_1/$', 'nav_1.html'),
(r'^nav_1/nav_2/$', 'nav_2.html')
]
def test_get_page(self):
""" Test tha... |
Migrate postage into templates_history table | """
Revision ID: 0256_set_postage_tmplt_hstr
Revises: 0255_another_letter_org
Create Date: 2019-02-05 14:51:30.808067
"""
from alembic import op
import sqlalchemy as sa
revision = '0256_set_postage_tmplt_hstr'
down_revision = '0255_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - ... | |
Add managed Endpoint unit tests | import glob
from jgo.jgo import InvalidEndpoint
import jgo
import os
import pathlib
import unittest
import shutil
import tempfile
import logging
_logger = logging.getLogger(__name__)
_logger.level = logging.INFO
SJC_VERSION = "2.87.0"
SJC_OPTIONAL_VERSION = "1.0.0"
MANAGED_ENDPOINT = (
"org.scijava:scijava-commo... | |
Create test for testcase order in output. | import shutil
import subprocess
import sys
import tempfile
import textwrap
import unittest
from robot.api import ExecutionResult
class PabotTestlevelsplitOutputTaskOrderTest(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree... | |
Add plugin shell execution script | import subprocess
def execute_cmd(parms_string, quiet=False):
r"""
Run CLI standard tool or scripts.
Description of variable:
parms_string Command to execute from the current SHELL.
quiet do not print tool error message if True
"""
result = subprocess.run([parms_st... | |
Remove usage of remove_undocumented from core parallel_for. | # Copyright 2018 The TensorFlow 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2018 The TensorFlow 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
Create command to remove duplicate submitters | import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
@transacti... | |
Add a function to test socket connections | import socket
from contextlib import closing
def test_connection(host, port):
""" Test a connection to a host/port """
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
return bool(sock.connect_ex((host, port)) == 0)
| |
Add lab 07 template for class C | def main():
matkul = #buat sebuah dictionary
while #buat agar meminta input terus :
masukkan = input(">>> ")
######
#buat agar program berhenti saat masukkan adalah "selesai"
######
masukkan_split = masukkan.split(" ")
if (masukkan_split[0] == "tamba... | |
Add a bug link field | from django.db import models
# Create your models here.
class Project(models.Model):
name = models.CharField(max_length=200)
language = models.CharField(max_length=200)
icon_url = models.URLField(max_length=200)
class Bug(models.Model):
project = models.ForeignKey(Project)
title = models.CharField... | from django.db import models
# Create your models here.
class Project(models.Model):
name = models.CharField(max_length=200)
language = models.CharField(max_length=200)
icon_url = models.URLField(max_length=200)
class Bug(models.Model):
project = models.ForeignKey(Project)
title = models.CharField... |
Add file for info dialog | ##
## patts-qt - Qt GUI client for PATTS
## Copyright (C) 2015 Delwink, LLC
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as published by
## the Free Software Foundation, version 3 only.
##
## This program is distributed i... | |
Add functional tests for telementry resource | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | |
Add Telemetry measurement for Polymer demo app | # 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.
import os
from telemetry.core import util
from telemetry.page import page_measurement
from telemetry.page import page_set
class Pica(page_measurement.PageM... | |
Add a Python solution for Hide&Seek game | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import permutations, chain
# Board
Empty = 1
Elephant = 2
Lion = 3
Zebra = 5
Gazelle = 7
Rhino = 11
# E L | G L
# Z G Z | Z E
# R L E | L R G
# -------------
# R E Z |
# G G | R L
# L R | G E Z
board = [Elephant, Empty, Lion, Zebra, Gazell... | |
Add migration for user_assignee Case field | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('cases', ... | |
Add a script to analyse ring topology simulations | import h5manager as hm
import tables
import matplotlib.pyplot as plt
import numpy as np
def main(dbfile):
# Get the simulations
db = tables.openFile(dbfile)
simus = hm.get_first_level_groups(db.root)
# Define some function to get specific result values
def get_strength(simu):
return hm.get... | |
Add "spotlight" field to article/file models | # Generated by Django 3.0.7 on 2021-01-18 18:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('museum_site', '0043_auto_20201022_0242'),
]
operations = [
migrations.AddField(
model_name='article',
name='spotligh... | |
Test ability to log in | import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class LoginTestCase(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.addCleanup(self.browser.quit)
self.browser.get('http://localhost:8080/intermine-demo/begin.do')
... | |
Add script to run all pairwise MISO comparisons for each event type. | """
this script is to do all pairwise comparisons of each class of events
called by MISO. It assumes MISO has already been run on each sample
and there is a directory structure of:
miso_dir/control-RI
miso_dir/knockdown-RI
where before the - is the samplename and after the - is the event type.
It then calculates all ... | |
Add a management command to bankrupt users. | from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zephyr.lib.actions import update_message_flags
from zephyr.models import UserProfile, Message, get_user_profile_by_email
class Command(BaseCommand):
help = """Bankrupt one or many users.
Usage: python manage.py bankr... | |
Add the missing migration in the members app. | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-01 20:07
from __future__ import unicode_literals
import annoying.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('member', '0032_relationship'),
]
operations = [
migr... | |
Add unit test for state diff method | import random
from copy import deepcopy
from raiden.transfer.state import (
ChainState,
NettingChannelEndState,
NettingChannelState,
PaymentNetworkState,
TokenNetworkState,
TransactionExecutionStatus,
)
from raiden.transfer.views import detect_balance_proof_change
def test_detect_balance_proo... | |
Convert tfrecords to csv to be used in Spark. | from subprocess import check_output
import tensorflow as tf
import csv
VIDEO_LEVEL_DATA_FODLER = "/Users/Sophie/Documents/youtube-8m-data/train/"
CSV_FILE_PATH = 'train.csv'
with open(CSV_FILE_PATH, 'w') as f:
fieldnames = ['video_id', 'mean_rgb', 'mean_audio', 'labels']
csv_writer = csv.DictWriter(f, fieldna... | |
Add str to hex utility | #!/usr/bin/python
import sys
if len(sys.argv) < 2:
print('Incorrect usage')
exit(1)
for char in sys.argv[1]:
sys.stdout.write('\\x' + char.encode('hex'))
| |
Test the RQ task as well. | # Lots of work to be done here!!!!
from unittest import mock
from django.test import TestCase
from metaci.build.tasks import check_queued_build
from metaci.conftest import (
BuildFactory,
OrgFactory,
PlanFactory,
PlanRepositoryFactory,
RepositoryFactory,
)
@mock.patch("metaci.build.tasks.reset_... | |
Add fabric configuration for deploy | from fabric.api import *
import os
import sys
import shutil
import SimpleHTTPServer
import SocketServer
# Local path configuration (can be absolute or relative to fabfile)
env.deploy_path = 'output'
DEPLOY_PATH = env.deploy_path
# Branch to push on GitHub
env.gp_branch = 'master'
env.msg = 'Update blog'
SERVER = '1... | |
Add unit tests for module cpu | # pylint: disable=C0103,C0111
import json
import unittest
import mock
import tests.mocks as mocks
from bumblebee.config import Config
from bumblebee.input import I3BarInput, LEFT_MOUSE
from bumblebee.modules.cpu import Module
class TestCPUModule(unittest.TestCase):
def setUp(self):
self._stdin, self._se... | |
Use fabric to deploy Puppet modules | from fabric.api import cd, env, local, lcd, run
PUPPET_MASTER_IP = '192.168.33.10'
def puppet():
env.hosts = [
'vagrant@' + PUPPET_MASTER_IP + ':22',
]
env.passwords = {
'vagrant@' + PUPPET_MASTER_IP + ':22': 'vagrant'
}
def test():
with lcd('puppet/modules'):
with lcd(... | |
Add a utility to induce an inventory | import pyghmi.ipmi.command as cmd
import sys
import os
# alternatively, the following ipmi raw sequence:
# 0x3a 0xc4 0x3 0x0 0x21 0x1 0x9d 0x2f 0x76 0x32 0x2f 0x69 0x62 0x6d 0x63 0x2f 0x75 0x65 0x66 0x69 0x2f 0x66 0x6f 0x72 0x63 0x65 0x2d 0x69 0x6e 0x76 0x65 0x6e 0x74 0x6f 0x72 0x79 0x11 0x1
c = cmd.Command(sys.argv[1... | |
Add dummy wrapper for correlation filters | import numpy as np
from menpofit.math.correlationfilter import mccf, imccf
# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
r"""
"""
def __init__(self, cf_callable=mccf, icf_callable=imccf):
self.cf_callable = cf_callable
self.icf_callable = icf_callable
def... | |
Add quick hack of a VTEC listing, will make JSON when time permits | #!/usr/bin/env python
"""Listing of VTEC events for a WFO and year"""
import cgi
import sys
import json
def report(wfo, year):
"""Generate a report of VTEC ETNs used for a WFO and year
Args:
wfo (str): 3 character WFO identifier
year (int): year to run for
"""
import psycopg2
pgcon... | |
Add tests for BC changes | import numpy as np
from numpy.testing import assert_array_equal
from nose.tools import with_setup, assert_true, assert_equal, assert_not_equal
from landlab import FIXED_GRADIENT_BOUNDARY, CLOSED_BOUNDARY, INACTIVE_LINK, \
FIXED_LINK
from landlab import RasterModelGrid
def setup_grid():
globals().update({
... | |
Add test for text plugin | #!/usr/bin/env python3
#-*- encoding: utf-8 -*-
import os, sys, tempfile, unittest
import lxml.etree as etree
ECMDS_INSTALL_DIR = os.path.normpath(os.path.join(
os.path.dirname(os.path.realpath(sys.argv[0])),
"..", ".."
))
sys.path.insert(1, ECMDS_INSTALL_DIR + os.sep + 'lib')
from net.ecromedos.error impor... | |
Add data migration to set correct content type of previously created navs. | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
orm.TrackedEmail.objects.filter(body__con... | |
Add depem custom filter plugin | # depem: Strip PEM headers and remove all whitespace from string
# Usage: {{ foo | depem }}
def depem(string):
import re
return re.sub(r'\s+|(-----(BEGIN|END).*-----)', '', string)
class FilterModule(object):
def filters(self):
return {
'depem': depem,
}
| |
Remove 'migrated' field from AutomaticUpdateRule | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-14 12:21
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('data_interfaces', '0020_make_migrated_nullable'),
]
... | |
Add script to delete emo's projectexps. We use this script when showing people how the importer works. | from mysite.profile.models import ProjectExp, Person
project_exps = ProjectExp.objects.filter(
person=Person.objects.get(user__username='emo'))[:19]
# Gonna limit to 20; damage mitigation just in case this query isn't right.
for exp in project_exps:
exp.delete()
| |
Add script to automate notebooks testing | # -*- coding: utf-8 -*-
'''
Checks notebook execution result.
Equal to this command + error management:
jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output executed_notebook.ipynb demo.ipynb
For jupyter configuration information, run: jupyter --path
'''
# Dependencies: nbformat, nbc... | |
Add controller super class draft via upload | import restapi
# Class for /company/companies
import connectpyse
class CWController(restapi.Client):
def __init__(self):
self.module_url = ''
super().__init__('{}/{}'.format(connectpyse.API_URL, self.module_url))
def get_companies(self, user_params={}):
json_results = sel... | |
Add some files written by PatrickY. | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import time
L1 = [i for i in range(1000000)]
print("List Length:", len(L1))
t1 = time.time()
for j in range(0, len(L1) - 1):
if L1[j] > L1[j + 1]:
L1[j], L1[j + 1] = L1[j + 1], L1[j]
else:
pass
print('Sorted List:', L1)
t2 = time.time()
print("T... | |
Test fields of core models | from django.test import TestCase
from .. import models
class TestVideo(TestCase):
def test_fields(self):
expected_fields = (
'id',
'title',
'slug',
'preview',
'length',
'recorded',
'created',
# Incoming
... | |
Add test for late-join scenario | import pytest
from hydrachain.consensus.simulation import Network, assert_heightdistance
# run this test with `tox -- -rx -k test_late_joins`
@pytest.mark.xfail
@pytest.mark.parametrize('validators', range(3, 10))
@pytest.mark.parametrize('late', range(1, 3))
@pytest.mark.parametrize('delay', [2])
def test_late_joins... | |
Add basic Python script for devices. | #
# IAS Basic device framework.
#
# Author: Joeri Hermans
#
import sys
import socket
import struct
# Global members, which are required for the communication
# with the remote IAS controller.
gDeviceIdentifier = sys.argv[1]
gControllerAddress = sys.argv[2]
gControllerPort = int(sys.argv[3])
gSocket = s... | |
Add POC script to mirror Ubuntu cloud images | #!/usr/bin/env python
from __future__ import print_function
import os
import requests
# TODO(bc): provide these via config and/or argparse
MIRROR_PATH = '/mnt/mirror.os02/ubuntu-cloud'
RELEASE_LIST = ['trusty',
'utopic']
ARCH_LIST = ['amd64']
LABEL_LIST = ['release']
ITEM_LIST = ['disk1.img']
UPSTREA... | |
Add a command to remove some bogus data key / value pairs | import sys
from candidates.popit import PopItApiMixin, popit_unwrap_pagination
from candidates.update import fix_dates
from django.core.management.base import BaseCommand
from slumber.exceptions import HttpClientError
def strip_bogus_fields(data, bogus_field_keys):
for key in bogus_field_keys:
if key i... | |
Add mergemigration for recent update with develop | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-09-13 14:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0129_merge_20180910_1926'),
('osf', '0129_merge_20180906_2006'),
]
operatio... | |
Add global count quotas calculation migration | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from uuid import uuid4
from django.db import migrations
def create_quotas(apps, schema_editor):
Project = apps.get_model('structure', 'Project')
Customer = apps.get_model('structure', 'Customer')
ProjectGroup = apps.get_model('structure', '... | |
Add management command to get couch cases non updated in ES |
import inspect
from django.core.management.base import BaseCommand
from datetime import datetime
from dimagi.utils.chunked import chunked
from casexml.apps.case.models import CommCareCase
from corehq.apps.es import CaseES
from corehq.elastic import ES_EXPORT_INSTANCE
from corehq.util.dates import iso_string_to_datet... | |
Add simple tests for pml/cs.py. | import pytest
from pml import cs
class InvalidControlSystem(cs.ControlSystem):
"""
Extends ControlSystem without implementing required methods.
"""
def __init__(self):
pass
def test_ControlSystem_throws_NotImplememtedError():
with pytest.raises(NotImplementedError):
cs.ControlSys... | |
Make sure we delete all payoutaccounts from new projects so that they will need submit a stripeaccount. | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-12-19 15:21
from __future__ import unicode_literals
from django.db import migrations
def remove_accounts(apps, schema_editor):
PayoutAccount = apps.get_model('payouts', 'PayoutAccount')
ProjectPhase = apps.get_model('bb_projects', 'ProjectPhase')
... | |
Verify Preorder Serialization of a Binary Tree | class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] ... | |
Add a dumb test, to investigate segfault [skip CI] | # -*- coding: utf-8 -*-
#/***************************************************************************
# Irmt
# A QGIS plugin
# OpenQuake Integrated Risk Modelling Toolkit
# -------------------
# begin : 2013-10-24
# copyright ... | |
Add new libvirt_type option "uml" for user-mode-linux.. This switches the libvirt URI to uml:///system and uses a different template for the libvirt xml. | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2010 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | |
Add Python script for Excel file diffs | import sys
from pptx import Presentation
for slide in Presentation(sys.argv[1]).slides:
for shape in slide.shapes:
if not shape.has_text_frame:
continue
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
print(run.text) | |
Migrate task assignment snapshots to TimeEntry | # -*- coding: utf-8 -*-
# Manually written
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
import dateutil
def create_time_entries(apps, schema_editor):
TaskAssignment = apps.get_model('orchestra', 'TaskAssignment')
TimeEntry = apps.get_model('orchestra', 'Ti... | |
Convert RSPlayer 2 logs into CSV for programme return. | """Helper to process RSPlayer logs for Programme Return.
Put RSPlayer logs into some folder, change to it, open a Python prompt and paste
in this code. Be sure that the logs contain only the data you want (ie trim the
start and end to get rid of data outside of the reporting period).
XXX To do:
"""
import ... | |
Add smoke test for REST API on Travis | import requests
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "BE": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "BE": "E... | |
Add a management command to bulk turn off digests. | from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_change_enable_digest_emails
from zerver.models import Realm, UserProfile, get_user_profile_by_email
class Command(BaseCommand):
help = """Turn off digests... | |
Add helper functions for domain logic | from datetime import date
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = date(today.year, today.month, 1)
qs = Transaction.objects.filter(created__gte=first_day_of_a_month)... | |
Migrate default for is_native to database | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-11-19 15:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0016_auto_20181018_1401'),
]
operations = [
migrations.AlterField(
... | |
Add the prefered_theme field for User model | # -*- coding: UTF-8 -*-
# Copyright 2015-2016 Luc Saffre
# License: BSD (see file COPYING for details)
"""Database models for :mod:`extjs6`.
"""
from __future__ import unicode_literals
import logging
logger = logging.getLogger(__name__)
from django.utils.translation import ugettext_lazy as _
from lino.api import ... | |
Add script to draw learning curve | #!/usr/bin/env python
import argparse
import pandas as pd
import matplotlib.pyplot as plt
def learning_curve(csv_file):
df = pd.read_csv(csv_file)
df_train = df.query("type == 'train'")
df_val = df.query("type == 'val'")
plt.figure()
# train loss
plt.subplot(221)
plt.semilogy(df_train... | |
Add migration script for queryLayers column | from sqlalchemy import MetaData, Table, Column, types
from c2cgeoportal import schema
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
layer = Table('layer', meta, schema=schema, autoload=True)
Column('queryLayers', types.Unicode).create(layer)
def downgrade(migrate_engine):
meta =... | |
Add a test for SaveFile | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
import unittest
import os.path
import tempfile
from multiprocessing import Pool
from UM.SaveFile import SaveFile
write_count = 0
def write_dual(path):
with SaveFile(path, "w") as f:
f.write("test file")
... | |
Add script to import a folder of named images and attach to people. | """ Loop through images in a directory and attempt to match them to a person."""
import re
import os
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import MultipleObjectsReturned
from django.core.management.base import LabelCommand
from django.core.files import File
from django.ut... | |
Add script for jiesuan parameters | #!/usr/bin/python
# coding: utf-8
import sys
import urllib2
import json
import time
from datetime import datetime
CURSOR='o_cursor'
RD='report_date'
UD='update_date'
CU='COMMODITYDELIVFEEUNIT'
HL='HEDGLONGMARGINRATIO'
HS='HEDGSHORTMARGINRATIO'
IID='INSTRUMENTID'
SP='SETTLEMENTPRICE'
SL='SPECLONGMARGINRATIO'
SS='SPECSH... | |
Add ethernet type distribution script | #!/usr/bin/python2
# Processes Ethernet data
f = open("data/eth_data.txt", "r")
# skip header lines
[f.readline() for i in range(3) ]
data = []
for line in f:
data.append(line.split()[2])
eth_types = {'Xerox PUP':0, 'Sprite':0, 'IPv4':0, 'ARP':0, 'Reverse ARP':0,
'AppleTalk ARP':0, 'IEEE 802.1Q VLAN tagging':0, '... | |
Add mgmt command for basic otm1 migration checks | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from treemap.models import Species, Instance, Tree, Plot, Audit, TreePhoto
from treemap.mana... | |
Switch myisam to innodb for fulltext_record_properties |
"""Switch fulltext_record_properties to innodb
Revision ID: 53bb0f4f6ec8
Revises: 63fc392c91a
Create Date: 2014-09-30 09:20:05.884100
"""
# revision identifiers, used by Alembic.
revision = '53bb0f4f6ec8'
down_revision = '63fc392c91a'
from alembic import op
def upgrade():
op.drop_index('fulltext_record_propert... | |
Add simple unit tests for max, min and mean pooling | import pytest
import numpy
from numpy.testing import assert_allclose
from ...neural._classes.model import Model
from ...neural.vecs2vec import MeanPooling, MaxPooling
from ...neural.vecs2vec import MinPooling
@pytest.fixture(params=[MeanPooling, MaxPooling, MinPooling])
def PoolClass(request):
return request.par... | |
Test case added for replacing BOM | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import unittest
import frappe
test_records = frappe.get_test_records('BOM')
class TestBOMUpdateTool(unittest.TestCase):
def test_replace_bom(self):
... | |
Add pindah lesson plan tarikh | #!/usr/bin/python
#Created : Mon 08 Sep 2008 01:40:45 PM GMT
#Last Modified : Tue 28 Jul 2015 10:34:53 AM UTC
#qpy:2
#qpy:console
import site
import os
import sys
from time import strftime
import sqlite3
con01 = sqlite3.connect("/usb/phpmysql/lessonplan2010.db")
cur01 = con01.cursor()
con02 = sqlite3.connect("/usb/... | |
Add script for sending rf signals. | import os
import subprocess
# Enter codes for each outlet
codes = {'1': {'on': '21811', 'off': '21820'},
'2': {'on': '21955', 'off': '21964'},
'3': {'on': '22275', 'off': '22284'},
'4': {'on': '23811', 'off': '23820'},
'5': {'on': '29955', 'off': '29964'}}
num = input('Enter outlet... | |
Add yummly.recipe and yummly.search functions. |
import requests
# Yummly API: https://developer.yummly.com
# API URLs
URL_BASE = 'http://api.yummly.com/v1'
URL_GET = URL_BASE + '/api/recipe/'
URL_SEARCH = URL_BASE + '/api/recipes'
# API auth properties which should be set externally
api_id = None
api_key = None
# basic request config options
# @note: h... | |
Add a parallel fuzzing script | #!/usr/bin/python3
# SPDX-License-Identifier: LGPL-2.1+
import argparse
import sys
import subprocess
import os
def main():
parser = argparse.ArgumentParser(description='Run afl-fuzz on all cores')
parser.add_argument('--input', '-i', help='fuzzing input directory')
parser.add_argument('--output', '-o', he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.