Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix - add missed migrations | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-13 13:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_auto_20160422_1256'),
]
operations = [
migrations.AddField(
... | |
Add a test for clickthrough | import openliveq as olq
import os
class TestClickthrough(object):
def test_load(self):
filepath = os.path.join(os.path.dirname(__file__),
"fixtures", "sample_clickthrough.tsv")
cs = []
with open(filepath) as f:
for line in f:
c = olq.Clickthrough.rea... | |
Add fake limited composite example | # -----------------------------------------------------------------------------
# User configuration
# -----------------------------------------------------------------------------
outputDir = '/Users/seb/Desktop/float-image/'
# -----------------------------------------------------------------------------
from paravie... | |
Create attr-utils module; create attribute memoization helper | def _set_attr( obj, attr_name, value_to_set ):
setattr( obj, attr_name, value_to_set )
return getattr( obj, attr_name )
def _memoize_attr( obj, attr_name, value_to_set ):
return getattr( obj, attr_name, _set_attr( obj, attr_name, value_to_set ) )
| |
Add unit test of utils module. | # -*- coding: utf-8 -*-
import unittest
import re
import sys
import os.path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from anydo.lib import utils
class UtilsTests(unittest.TestCase):
def setUp(self):
self.pattern = re.compile('(^([\w-]+)==$)', flags=re.U)
def test_create_uuid(sel... | |
Create a model-based form for whitelist requests | from django.forms import ModelForm
from whitelist.models import Player
class WhitelistForm(ModelForm):
""" Automatically generate a form based on the Player model
"""
class Meta:
model = Player
fields = ('ign', 'email')
| |
Add script for uploading bdists | from __future__ import (division, print_function, absolute_import,
unicode_literals)
import os
import glob
from conda import config
#from conda_build.metadata import MetaData
from binstar_client.inspect_package.conda import inspect_conda_package
from obvci.conda_tools.build import upload
fro... | |
Add a script to add mapit area IDs to new Place objects for 2013 | import sys
from optparse import make_option
from pprint import pprint
from django.core.management.base import NoArgsCommand
from django.template.defaultfilters import slugify
from django.conf import settings
# from helpers import geocode
from core import models
from mapit import models as mapit_models
class Command... | |
Add simple test for FormDesignerPlugin | import pytest
from cms import api
from cms.page_rendering import render_page
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefini... | |
Add test trek_dtail_pdf language none | import os
from django.test import TestCase
from django.conf import settings
from geotrek.trekking.factories import TrekFactory
from geotrek.trekking.models import Trek
class AltimetryMixinTest(TestCase):
def test_get_elevation_chart_none(self):
trek = TrekFactory.create(no_path=True)
trek.get_el... | |
Add PyQtGraph random walk without datetime | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This example demonstrates a random walk with pyqtgraph.
"""
import sys
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
from numpy_buffer import RingBuffer # https://github.com/scls19fr/numpy-buffer
class RandomWalkPlot:
def __init... | |
Add a management command to rename a stream. | from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_rename_stream
from zerver.models import Realm, get_realm
class Command(BaseCommand):
help = """Change the stream name for a realm.
Usage: python manage.py rename-stream <domain> <old name... | |
Add a test for check_inputs. | from utilities.simulation_utilities import check_inputs
import pytest
import numpy as np
@pytest.mark.parametrize("input,expected", [
(None, np.ndarray([0])),
([0], np.array([0])),
(1, np.array([1])),
(range(5), np.array([0,1,2,3,4]))
])
def test_check_inputs(input, expected):
assert np.allclose(... | |
Add poolstat api example to project root. | import requests
import hmac
import hashlib
import base64
PUBLIC_KEY = '##'
PRIVATE_KEY = '##'
URL = 'https://www.poolstat.net.au/restapi/v1/ladders'
digest = hmac.new(PRIVATE_KEY, URL, digestmod=hashlib.sha256).hexdigest()
# signature = base64.b64encode(digest).decode()
print digest
#print signature
headers = {
... | |
Create new module for continuous design variables | """Implementation of a Dakota continous design variable."""
from .base import VariableBase
classname = 'ContinuousDesign'
class ContinuousDesign(VariableBase):
"""Define attributes for Dakota continous design variables."""
def __init__(self,
variables=('x1', 'x2'),
initi... | |
Add initial script to export feed downloads. | # -*- coding: utf-8 -*-
import psycopg2
import psycopg2.extras
import requests
import json
import mc_database
import mediacloud
def get_download_from_api( mc_api_url, api_key, downloads_id ):
r = requests.get( mc_api_url +'/api/v2/downloads/single/' + str( downloads_id) ,
params = { 'k... | |
Enable Django Admin for some of our data | from django.contrib import admin
from models import MuseumObject,FunctionalCategory
class MOAdmin(admin.ModelAdmin):
fields = ('registration_number','country','description','comment')
list_display = ('registration_number','country','description','comment')
list_filter = ('country','functional_category')
... | |
Add custom IPython configuration ✨ | """
IPython configuration with custom prompt using gruvbox colors.
- https://github.com/reillysiemens/ipython-style-gruvbox
Thanks to @petobens for their excellent dotfiles.
- https://github.com/petobens/dotfiles
"""
from typing import List, Optional, Tuple
import IPython.terminal.prompts as prompts
from prompt_toolk... | |
Add a cronjob script for sending studentvoice notifications. | import os
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "studentportal.settings")
from django.core.urlresolvers import reverse
from django.conf import settings
from post_office import mail
from studentvoice.models import Voice
for voice in Voice.objects.filter(was_sent=False, parent... | |
Add script to plot population vs distinct hashtags. | """
Plot and calculate county population size to number of distinct hashtags.
"""
import matplotlib.pyplot as plt
import seaborn
import pandas
import twitterproj
import scipy.stats
import numpy as np
def populations():
# Grab demographic info
data = {}
df = pandas.read_csv('../census/county/PEP_2013_PEPAN... | |
Raise ConfigurationError error that causes server to fail and dump whole stacktrace | from .errors import *
from .browser import AggregationBrowser
from .extensions import get_namespace, initialize_namespace
__all__ = (
"open_store",
"Store"
)
def open_store(name, **options):
"""Gets a new instance of a model provider with name `name`."""
ns = get_namespace("s... | from .errors import *
from .browser import AggregationBrowser
from .extensions import get_namespace, initialize_namespace
__all__ = (
"open_store",
"Store"
)
def open_store(name, **options):
"""Gets a new instance of a model provider with name `name`."""
ns = get_namespace("s... |
Add command to migrate SMSLog to SQL | from corehq.apps.sms.models import SMSLog, SMS
from custom.fri.models import FRISMSLog
from dimagi.utils.couch.database import iter_docs
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
class Command(BaseCommand):
args = ""
help = ("Migrates SMSLog to SMS")
... | |
Add the skeleton and docs | # -*- encoding: utf-8 -*-
'''
Safe Command
============
The idea behind this module is to allow an arbitrary command to be executed
safely, with the arguments to the specified binary (optionally) coming from
the fileserver.
For example, you might have some internal license auditing application for
which you need the ... | |
Add API tests for profile validation | # 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 a script that can be used to compare asyncio.sleep to time.sleep | #!/usr/bin/env python
"""https://docs.python.org/3.7/library/asyncio-task.html 変奏版
Features:
- asyncio.gather()
- asyncio.sleep()
- asyncio.run()
"""
import asyncio
import logging
import time
concurrent = 3
delay = 5
# PYTHONASYNCIODEBUG=1
logging.basicConfig(level=logging.DEBUG)
async def async_pause():
awai... | |
Add test file to check consistent use of default arguments | """Make sure that arguments of open/read/write don't diverge"""
import pysoundfile as sf
from inspect import getargspec
open = getargspec(sf.open)
init = getargspec(sf.SoundFile.__init__)
read_function = getargspec(sf.read)
read_method = getargspec(sf.SoundFile.read)
write_function = getargspec(sf.write)
def defau... | |
Add Subjects model, methods for report and export | from collections import defaultdict
from corehq.apps.users.models import CouchUser
from custom.openclinica.const import AUDIT_LOGS
from custom.openclinica.utils import (
OpenClinicaIntegrationError,
is_item_group_repeating,
is_study_event_repeating,
get_item_measurement_unit,
get_question_item,
... | |
UPDATE - add migration file | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vote', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='multiquestion',
name='gr... | |
Create child class for Rainbow bulb | from pyplaybulb.playbulb import Playbulb
EFFECT_FLASH = '00'
EFFECT_PULSE = '01'
EFFECT_RAINBOW = '02'
EFFECT_RAINBOW_FADE = '03'
class Rainbow(Playbulb):
hexa_set_colour = '0x001b'
hexa_effect = '0x0019'
hexa_get_colour = '0x0019'
def set_colour(self, colour):
self.connection.char_write(self... | |
Add module for range support. | from collections import namedtuple
from vintage_ex import EX_RANGE_REGEXP
import location
EX_RANGE = namedtuple('ex_range', 'left left_offset separator right right_offset')
def get_range_parts(range):
parts = EX_RANGE_REGEXP.search(range).groups()
return EX_RANGE(
left=parts[1],
... | |
Add outlier detection util script. | #!/usr/bin/env python2
#
# Detect outlier faces (not of the same person) in a directory
# of aligned images.
# Brandon Amos
# 2016/02/14
#
# Copyright 2015-2016 Carnegie Mellon University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... | |
Add a script to check TOI coverage for a bbox and zoom range | import mercantile
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('min_lon',
type=float,
help='Bounding box minimum longitude/left')
parser.add_argument('min_lat',
type=float,
help='Bounding box minimum latitude/bottom')
parser.add_argu... | |
Add basic mechanism to override the default EntryAdmin | """EntryAdmin for zinnia-wymeditor"""
from django.contrib import admin
from zinnia.models import Entry
from zinnia.admin.entry import EntryAdmin
class EntryAdminWYMEditorMixin(object):
"""
Mixin adding WYMeditor for editing Entry.content field.
"""
pass
class EntryAdminWYMEditor(EntryAdminWYMEditor... | |
Create a skeleton for node propagation integration tests | class TestPropagation(object):
def test_node_propagation(self):
"""
Tests that check node propagation
1) Spin up four servers.
2) Make the first one send a sync request to all three others.
3) Count the numbers of requests made.
4) Check databases to see that they al... | |
Add missing migrations for limit_choices_to on BlogPage.author | # Generated by Django 2.2.2 on 2019-06-05 08:04
import blog.abstract
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_squashed_0006_auto_20180206_2239'),
]
operations... | |
Add function to save/restore environment between configuration checks. | from copy import deepcopy
def save_and_set(env, opts, keys=None):
"""Put informations from option configuration into a scons environment, and
returns the savedkeys given as config opts args."""
saved_keys = {}
if keys is None:
keys = opts.keys()
for k in keys:
saved_keys[k] = (env.h... | |
Create initial night sensor code for Pi | """
@author: Sze "Ron" Chau
@e-mail: chaus3@wit.edu
@source: https://github.com/wodiesan/sweet-skoomabot
@desc Night sensor-->RPi for Senior Design 1
"""
import logging
import os
import RPi.GPIO as GPIO
import serial
import subprocess
import sys
import time
import traceback
# GPIO pins. Uses the BC... | |
Add migration to create roles | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from corehq.apps.hqadmin.management.commands.cchq_prbac_bootstrap import cchq_prbac_bootstrap
from corehq.sql_db.operations import HqRunPython
class Migration(migrations.Migration):
dependencies = [
(... | |
Extend MediaRemovalMixin to move media files on updates | import os
from django.conf import settings
class MediaRemovalMixin(object):
"""
Removes all files associated with the model, as returned by the
get_media_files() method.
"""
# Models that use this mixin need to override this method
def get_media_files(self):
return
def delete(se... | import os
from django.conf import settings
class MediaRemovalMixin(object):
"""
Removes all files associated with the model, as returned by the
get_media_files() method.
"""
# Models that use this mixin need to override this method
def get_media_files(self):
return
def delete(se... |
Add script to replace text | #!/usr/bin/env python3
# This Python 3 script replaces text in a file, in-place.
# For Windows, use:
#!python
import fileinput
import os
import sys
def isValidFile(filename):
return (filename.lower().endswith('.m3u') or
filename.lower().endswith('.m3u8'))
def processFile(filename):
'''Makes cust... | |
Add script to update cvsanaly databases | from jiradb import *
if __name__ == "__main__":
log.setLevel(logging.DEBUG)
# Add console log handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(logging.Formatter('%(message)s'))
log.addHandler(ch)
# Add file log handler
fh = logging.FileHandler('updateGit.lo... | |
Test case for LSPI on gridworld. | #!/usr/bin/env python
__author__ = "William Dabney"
from Domains import GridWorld
from Tools import Logger
from Agents import LSPI
from Representations import Tabular
from Policies import eGreedy
from Experiments import Experiment
def make_experiment(id=1, path="./Results/Temp"):
"""
Each file specifying an... | |
Add automatic leak detection python script in examples | import sys
import rpc.ws
import edleak.api
import edleak.slice_runner
def usage():
print('autodetect [period] [duration]')
def print_leaker(leaker):
print('-------------------------------')
print('class : ' + leaker['leak_factor']['class'])
print('leak size : ' + str(leaker['leak_factor']['leak']))
... | |
Add unit test for glacier vault | #!/usr/bin/env python
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without ... | |
Add an example for dynamic RPC lookup. | import asyncio
import aiozmq
import aiozmq.rpc
class DynamicHandler(aiozmq.rpc.AttrHandler):
def __init__(self, namespace=()):
self.namespace = namespace
def __getitem__(self, key):
try:
return getattr(self, key)
except AttributeError:
return DynamicHandler(se... | |
Copy paste artist from filename1 to filename2 | # Extract the artist name from songs with filenames in this format:
# (number) - (artist) - (title).mp3
# and add the artists name to songs with filenames in this format:
# (number)..(title).mp3
# to make filenames in this format:
# (number)..(artist)..(title).mp3
#
# eg.: 14 - 13th Floor Elevators -... | |
Test that specific Failures are caught before parent Failures | from twisted.trial import unittest
import ooni.errors
class TestErrors(unittest.TestCase):
def test_catch_child_failures_before_parent_failures(self):
"""
Verify that more specific Failures are caught first by
handleAllFailures() and failureToString().
Fails if a subclass is list... | |
Add `OrganizationOption` tests based on `ProjectOption`. | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from sentry.models import OrganizationOption
from sentry.testutils import TestCase
class OrganizationOptionManagerTest(TestCase):
def test_set_value(self):
OrganizationOption.objects.set_value(self.organization, 'foo', 'bar')
assert ... | |
Add test coverage for rdopkg.guess version2tag and tag2version | from rdopkg import guess
from collections import namedtuple
import pytest
VersionTestCase = namedtuple('VersionTestCase', ('expected', 'input_data'))
data_table_good = [
VersionTestCase(('1.2.3', None), '1.2.3'),
VersionTestCase(('1.2.3', 'vX.Y.Z'), 'v1.2.3'),
VersionTestCase(('1.2.3', 'VX.Y.Z'), 'V1.2.3... | |
Add helper-lib for json object conversion and split dicts | #! /usr/bin/env python2.7
import datetime
def typecast_json(o):
if isinstance(o, datetime.datetime) or isinstance(o, datetime.date):
return o.isoformat()
else:
return o
def split_dict(src, keys):
result = dict()
for k in set(src.keys()) & set(keys):
result[k] = src[k]
return result
| |
Solve Code Fights lineup problem | #!/usr/local/bin/python
# Code Fights Lineup Problem
def lineUp(commands):
aligned, tmp = 0, 0
com_dict = {"L": 1, "A": 0, "R": -1}
for c in commands:
tmp += com_dict[c]
if tmp % 2 == 0:
aligned += 1
return aligned
def main():
tests = [
["LLARL", 3],
[... | |
Add download apikey test case | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.test import TestCase
from tastypie.test import ResourceTestCase
from django.test.client import Client
from django.conf import settings
from django.contrib.auth.models import User
class ApiKeyDownloadTestCase(ResourceTestCase):
def ... | |
Add a new script to clean up a habitica user given user email | import argparse
import sys
import logging
import emission.core.get_database as edb
import emission.net.ext_service.habitica.proxy as proxy
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("user_email",
help="the email addre... | |
Add py solution for 459. Repeated Substring Pattern | class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
for i in xrange(1, len(s) / 2 + 1):
if len(s) % i == 0 and len(set(s[j:j+i] for j in xrange(0, len(s), i))) == 1:
return True
return False
| |
Add commands for cases and variants | # -*- coding: utf-8 -*-
import logging
import click
from . import base_command
logger = logging.getLogger(__name__)
@base_command.command()
@click.option('-c' ,'--case-id',
help='Search for case'
)
@click.pass_context
def cases(ctx, case_id):
"""Display all cases in the database."""
ada... | |
Add py solution for 575. Distribute Candies | class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
return min(len(candies) / 2, len(set(candies)))
| |
Add some code to auto-remove Ltac | import re
__all__ = ["recursively_remove_ltac"]
LTAC_REG = re.compile(r'^\s*(?:Local\s+|Global\s+)?Ltac\s+([^\s]+)', re.MULTILINE)
def recursively_remove_ltac(statements, exclude_n=3):
"""Removes any Ltac statement which is not used later in
statements. Does not remove any code in the last exclude_n
sta... | |
Add a script to convert from rst style files to markdown | #!/usr/bin/python
import os
import re
import shutil
from optparse import OptionParser
def main():
parser = OptionParser(usage="usage: %prog [options]",
version="%prog 1.0")
parser.add_option("-i", "--inputdir",
action="store",
dest="indir",... | |
Add toy example of reading a large XML file | #!/usr/bin/env python
import xml.etree.cElementTree as ET
from sys import argv
input_file = argv[1]
NAMESPACE = "{http://www.mediawiki.org/xml/export-0.10/}"
with open(input_file) as open_file:
in_page = False
for _, elem in ET.iterparse(open_file):
# Pull out each revision
if elem.tag == NA... | |
Add script to create a historic->modern dictionary | """Reverse modern->historic spelling variants dictonary to historic->modern
mappings
"""
import argparse
import codecs
import json
from collections import Counter
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('input_dict', help='the name of the json file '
... | |
Add solution class for Ghia et al. (1982) | """
Implementation of the class `GhiaEtAl1982` that reads the centerline velocities
reported in Ghia et al. (1982).
_References:_
* Ghia, U. K. N. G., Ghia, K. N., & Shin, C. T. (1982).
High-Re solutions for incompressible flow using the Navier-Stokes equations
and a multigrid method.
Journal of computational ph... | |
Add migration for CI fix | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-09-22 07:29
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('infrastructure', '0019_project_latest_implementation_year'... | |
Add tests for proxy drop executable | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2017 Mozilla Corporation
from positive_alert_test_case import PositiveAlertTestCase
from negative_alert_t... | |
Check consecutive elements in an array | import unittest
"""
Given an unsorted array of numbers, return true if the array only contains consecutive elements.
Input: 5 2 3 1 4
Ouput: True (consecutive elements from 1 through 5)
Input: 83 78 80 81 79 82
Output: True (consecutive elements from 78 through 83)
Input: 34 23 52 12 3
Output: False
"""
"""
Approach:
... | |
Add a script for generating unicode name table | #!/usr/bin/python3
# Input: https://www.unicode.org/Public/UNIDATA/UnicodeData.txt
import io
import re
class Builder(object):
def __init__(self):
pass
def read(self, infile):
names = []
for line in infile:
if line.startswith('#'):
continue
line... | |
Add regression test with non ' ' space character as token | # coding: utf-8
from io import StringIO
word2vec_str = """, -0.046107 -0.035951 -0.560418
de -0.648927 -0.400976 -0.527124
. 0.113685 0.439990 -0.634510
-1.499184 -0.184280 -0.598371"""
def test_issue834(en_vocab):
f = StringIO(word2vec_str)
vector_length = en_vocab.load_vectors(f)
assert vector_lengt... | |
Add test file for graph.py and add test of Greengraph class constructor | from greengraph.map import Map
from greengraph.graph import Greengraph
from mock import patch
import geopy
from nose.tools import assert_equal
start = "London"
end = "Durham"
def test_Greengraph_init():
with patch.object(geopy.geocoders,'GoogleV3') as mock_GoogleV3:
test_Greengraph = Greengraph(start,end)... | |
Add file writer utility script | #!/bin/env python
import argparse
import sys
import os
parser = argparse.ArgumentParser(description="Write multiple svgs from stdin to files")
parser.add_argument('-o', '--outfile', metavar='OUTFILE', default='output.svg')
args = parser.parse_args()
base, extension = os.path.splitext(args.outfile)
def write_files... | |
Add test of removing unreachable terminals | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 17.08.2017 14:23
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import main, TestCase
from grammpy import *
from grammpy_transforms import *
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class D(Nonterminal):... | |
Add utility script for database setup | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
c... | |
Move main code to function because of pylint warning 'Invalid constant name' | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Ori... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import grp
import pwd
import inspect
import argparse
def list_all_users_in_group(groupname):
"""Get list of all users of group.
Get sorted list of all users of group GROUP,
including users with main group GROUP.
Ori... |
Save team member picture with extension. | from django.db import models
def team_member_image_name(instance, filename):
return 'team/{0}'.format(instance.name)
class TeamMember(models.Model):
bio = models.TextField(
verbose_name='biography')
name = models.CharField(
max_length=50,
unique=True,
verbose_name='name')... | import os
from django.db import models
def team_member_image_name(instance, filename):
_, ext = os.path.splitext(filename)
return 'team/{0}{1}'.format(instance.name, ext)
class TeamMember(models.Model):
bio = models.TextField(
verbose_name='biography')
name = models.CharField(
max_... |
Add functional tests for create_image | # -*- coding: utf-8 -*-
# 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, softw... | |
Add a management command to check if URNs are present in the database | import csv
from django.core.management.base import BaseCommand
from apps.plea.models import DataValidation, Case
from apps.plea.standardisers import standardise_urn, format_for_region
class Command(BaseCommand):
help = "Build weekly aggregate stats"
def add_arguments(self, parser):
parser.add_argum... | |
Add a python plotter that compares the results of with Stirling numbers | import matplotlib.pyplot as plt
import numpy
from math import factorial
def binom(a,b):
return factorial(a) / (factorial(b)*factorial(a-b))
def stirling(n,k):
if n<=0 or n!=0 and n==k:
return 1
elif k<=0 or n<k:
return 0
elif n==0 and k==0:
return -1
else:
s = sum(... | |
Add Timelapse script for sunrise timelapses | import sys
import time
from goprocam import GoProCamera, constants
import threading
import logging
"""
I use PM2 to start my GoPro cameras, using a Raspberry Pi 4, works perfectly.
pm2 start timelapse.py --cron "30 7 * * *" --log timelapse.log --no-autorestart
This script will overrride some settings for reliability... | |
Remove duplicates in all subdirectories - working raw version. | import hashlib, csv, os
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def process_directory_csv(current_dir_fullpath, sub_dir_list, files, csvwriter):
for file i... | |
Introduce a timer based update of activities | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import io
import datetime
from django.core.management.base import BaseCommand
from server.models import Instruction, Tour, Talk, Session, Season
from server.views.bulletin impo... | |
Add script to explore parameters units | # -*- coding: utf-8 -*-
from openfisca_core.parameters import ParameterNode, Scale
from openfisca_france import FranceTaxBenefitSystem
tax_benefit_system = FranceTaxBenefitSystem()
parameters = tax_benefit_system.parameters
def get_parameters_by_unit(parameter, parameters_by_unit = None):
if parameters_by_uni... | |
Add tests for form mixin. | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from django import forms
from mock import patch
from test_app.models import AuthorshipModel
from thecut.authorship.factories import UserFactory
from thecut.authorship.forms import AuthorshipMixin
class Au... | |
Add tests for custom authentication backend | """logintokens app unittests for backends
"""
from time import sleep
from django.test import TestCase, Client
from django.contrib.auth import get_user_model, authenticate
from logintokens.tokens import default_token_generator
USER = get_user_model()
class EmailOnlyAuthenticationBackendTest(TestCase):
"""Test... | |
Add tests for template tags | from datetime import datetime
from django.test import TestCase
from geotrek.authent.tests.factories import UserFactory, UserProfileFactory
from geotrek.feedback.templatetags.feedback_tags import (
predefined_emails, resolved_intervention_info, status_ids_and_colors)
from geotrek.feedback.tests.factories import (P... | |
Add a new Model-View-Projection matrix tool. | # -*- coding:utf-8 -*-
# ***************************************************************************
# Transformation.py
# -------------------
# update : 2013-11-13
# copyright : (C) 2013 by Michaël Roy
# email :... | |
Add test module for napalm_acl | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Anthony Shaw <anthonyshaw@apache.org>`
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (... | |
Add new file missed in earlier commit place holder for projects that do not load for some reason | '''
====================================================================
Copyright (c) 2016 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
===========================================================... | |
Fix loading of ply files exported by meshlab | #!/usr/bin/env python3
from pathlib import Path
"""Code for comparing point clouds"""
cloud1Path = Path("./data/reconstructions/2016_10_24__17_43_17/reference.ply")
cloud2Path = Path("./data/reconstructions/2016_10_24__17_43_17/high_quality.ply")
from load_ply import load_ply
cloud1PointData = load_ply(cloud1Path)... | |
Add directory for tests of rules removin | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 17.08.2017 22:06
:Licence GNUv3
Part of grammpy
""" | |
Add test for contact success view. | from django.test import RequestFactory
from django.urls import reverse
from contact.views import SuccessView
class TestSuccessView(object):
"""Test cases for the success view"""
url = reverse('contact:success')
def test_get(self, rf: RequestFactory):
"""Test sending a GET request to the view.
... | |
Add management command for resyncing mobile worker location user data | from corehq.apps.locations.models import Location
from corehq.apps.users.models import CommCareUser
from dimagi.utils.couch.database import iter_docs
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
args = "domain"
help = "Fix location user data for mobile workers.... | |
Add tests for cross domain xhr view | """Test for go.base.utils."""
from mock import patch, Mock
from django.core.urlresolvers import reverse
from go.base.tests.utils import VumiGoDjangoTestCase
class BaseViewsTestCase(VumiGoDjangoTestCase):
def cross_domain_xhr(self, url):
return self.client.post(reverse('cross_domain_xhr'), {'url': url})
... | |
Add integration test checking compatibility of Keras models with TF optimizers. | from __future__ import print_function
import os
import tempfile
import pytest
import keras
from keras import layers
from keras.utils.test_utils import get_test_data
from keras.utils.test_utils import keras_test
@pytest.mark.skipif(keras.backend.backend() != 'tensorflow', reason='Requires TF backend')
@keras_test
def... | |
Create a simple method to segment a trip into sections | # Standard imports
import attrdict as ad
import numpy as np
import datetime as pydt
# Our imports
import emission.analysis.classification.cleaning.location_smoothing as ls
import emission.analysis.point_features as pf
import emission.storage.decorations.location_queries as lq
def segment_into_sections(trip):
poin... | |
Add simple function-size analysis tool. |
import os
import re
import sys
import optparse
MARKER_START_FUNCS = "// EMSCRIPTEN_START_FUNCS"
MARKER_END_FUNCS = "// EMSCRIPTEN_END_FUNCS"
FUNCTION_CODE_RE = re.compile(
r"function (?P<name>[a-zA-Z0-9_]+)(?P<defn>.*?)((?=function)|(?=$))"
)
def analyze_code_size(fileobj, opts):
funcs = {}
name_re = Non... | |
Add a history demo in documentation. | # coding: utf-8
from deprecated.history import deprecated
from deprecated.history import versionadded
from deprecated.history import versionchanged
@deprecated(
reason="""
This is deprecated, really. So you need to use another function.
But I don\'t know which one.
- The first,
- The se... | |
Create a simple static gallery script. | from . import flag
#from go import html
from go import os
from go import path/filepath
def ReadAlbumDirs(input_dir):
f = os.Open(input_dir)
with defer f.Close():
names = f.Readdirnames(-1)
for name in names:
stat = os.Stat(filepath.Join(input_dir, name))
if stat.IsDir():
yield name
def... | |
Add script to update uploaded files. | #!/usr/bin/env python
#import hashlib
import os
def main():
for root, dirs, files in os.walk("/mcfs/data/materialscommons"):
for f in files:
print f
if __name__ == "__main__":
main()
| |
Add a basic Storage engine to talk to the DB | """
This is the Storage engine. It's how everything should talk to the database
layer that sits on the inside of the inventory-control system.
"""
import MySQLdb
class StorageEngine(object):
"""
Instantiate a DB access object, create all the necessary hooks and
then the accessors to a SQL database.
... | |
Test script for the heart container | #Test script for heart container testing if all the imports are successful
import sys
import os
import numpy as np
import h5py
import fnmatch
from modeling.sync_batchnorm.replicate import patch_replication_callback
from modeling.deeplab import *
from torchvision.utils import make_grid
from dataloaders.utils import dec... | |
Add migrations for game change suggestions | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-11-04 21:46
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('games', '0022_installer_reason'),
]
operations = [... | |
Add a module to set the "display name" of a dedicated server | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ansible.module_utils.basic import AnsibleModule
__metaclass__ = type
DOCUMENTATION = '''
---
module: dedicated_server_display_name
short_description: Modify the server display name in ovh manager
descri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.