Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add script for PCA compressing jacobian arrays.
import climate import logging import numpy as np import os from sklearn.decomposition import PCA def compress(source, k='mle', key='jac'): filenames = sorted(fn for fn in os.listdir(source) if key in fn and fn.endswith('.npy')) logging.info('%s: found %d jacobians matching %s', ...
Add tooling to get all of edx's web services.
import github from get_repos import * webservices = [] for repo in expanded_repos_list(orgs): try: metadata = get_remote_yaml(repo, 'openedx.yaml') except github.GithubException: continue if 'tags' in metadata and 'webservice' in metadata['tags']: print("{}".format(repo.html_url))...
Add migration to remove empty actionsets
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.db.models import Q import json def fix_empty_starts(apps, schema): empty_actions = ('[{"msg": {"eng": ""}, "type": "reply"}]', '[{"msg": {"base": ""}, "type": "reply"}]') from temba.flows.mod...
Add command to debug packages
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; eit...
Add simple test that table is readable
from astropy.table import Table TABLE_NAME = 'feder_object_list.csv' def test_table_can_be_read(): objs = Table.read(TABLE_NAME, format='ascii', delimiter=',') columns = ['object', 'ra', 'dec'] for col in columns: assert col in objs.colnames
Add simple script for benchmark execution
# ***************************************************************************** # Copyright (c) 2020, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of sou...
Create Node holder for Eve.
# -*- coding: utf-8 -*- from eve_neo4j.utils import node_to_dict, count_selection class Neo4jResultCollection(object): """ Collection of results. The object holds onto a py2neo-NodeSelection object and serves a generator off it. :param selection: NodeSelection object for the requested resource. "...
Add Solution to Problem 7.
# 10001st prime # Find the 10001st prime number # import math def generate_primes(n): p = 2 primes = [p] p += 1 primes.append(p) while len(primes) != n: p += 2 test_prime = True # Limit should only be up to the square root of current p, because nothing will exceed that. sqrt_limit = math.sqrt(p) fo...
Add configuration file for client
from os import environ DEMODULATION_COMMAND = environ.get('DEMODULATION_COMMAND', None) ENCODING_COMMAND = environ.get('ENCODING_COMMAND', None) DECODING_COMMAND = environ.get('DECODING_COMMAND', None)
Add missing migration from the switch to jsonfield
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-11 02:08 from __future__ import unicode_literals from django.db import migrations import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('eventlog', '0002_auto_20150113_1450'), ] operations = [ migr...
Add queueing server to handle multiple processes
#!/usr/bin/env python """ qserver This module will use a queuing server to execute a number of tasks across multiple threads. Example ------- tasks = (qserver.os_task("list files","ls -1"), \ qserver.task("my job",my_func,arg1,arg2,arg3)) qserver.start(tasks) Written by Brian Powe...
Add solution for problem 35
#!/usr/bin/python from math import sqrt, ceil, floor, log10, pow LIMIT = 1000000 def decimalShift(x): dec = x % 10; power = floor(log10(x)) x //= 10; x += dec * int(pow(10, power)) return x sievebound = (LIMIT - 1) // 2 sieve = [0] * (sievebound) crosslimit = (floor(sqrt(LIMIT)) - 1) // 2 for i ...
Add a simple and hackish plane scaling test.
#!/usr/bin/python3 import pykms import time import random card = pykms.Card() res = pykms.ResourceManager(card) conn = res.reserve_connector("hdmi") crtc = res.reserve_crtc(conn) plane = res.reserve_overlay_plane(crtc) mode = conn.get_default_mode() #mode = conn.get_mode(1920, 1080, 60, False) # Blank framefuffer f...
Add 03-task sample test file.
import datetime import unittest import solution class TestSocialGraph(unittest.TestCase): def setUp(self): self.terry = solution.User("Terry Gilliam") self.eric = solution.User("Eric Idle") self.graham = solution.User("Graham Chapman") self.john = solution.User("John Cleese") ...
Add general filter test file
import unittest import vapoursynth as vs class FilterTestSequence(unittest.TestCase): def setUp(self): self.core = vs.get_core() self.Transpose = self.core.std.Transpose self.BlankClip = self.core.std.BlankClip def test_transpose8_test(self): clip = self.BlankClip(format=vs....
Create script to time compass reads and db writes
#!/usr/bin/env python3 from sense_hat import SenseHat from pymongo import MongoClient sense = SenseHat() client = MongoClient("mongodb://192.168.0.128:27017") db = client.g2x for _ in range(0, 1000): reading = sense.get_compass() db.compass.insert_one({"angle": reading}) # db.compass.insert_one({"angle":...
Fix import for 1.6 version.
from django.conf.urls.defaults import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, { 'form_class': FileForm, 'response': lambda n...
try:# pre 1.6 from django.conf.urls.defaults import url, patterns except ImportError: from django.conf.urls import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<...
Add tests for formatter yaml
import unittest, argparse from echolalia.formatter.yamler import Formatter class YamlerTestCase(unittest.TestCase): def setUp(self): self.parser = argparse.ArgumentParser() self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)] self.formatter = Formatter() def test_add_args(self): ...
Add migration to convert GA timezone to UTC
""" Convert Google Analytics buckets from Europe/London to UTC """ import logging import copy from itertools import imap, ifilter from datetime import timedelta from backdrop.core.records import Record from backdrop.core.timeutils import utc log = logging.getLogger(__name__) GA_BUCKETS_TO_MIGRATE = [ "carers_al...
Add delete all jobs script
#!/usr/bin/env python ############################################################################ # # # Copyright 2014 Prelert Ltd # # ...
Add tests for game parser item
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from lxml import html from parsers.team_parser import TeamParser from parsers.game_parser import GameParser def test_2016(): url = "http://www.nhl.com/scores/htmlreports/20162017/ES020776.HTM" tp = TeamParser(get_data(url)) tp.load_data() ...
Remove exception eating from dispatch_hook.
# -*- coding: utf-8 -*- """ requests.hooks ~~~~~~~~~~~~~~ This module provides the capabilities for the Requests hooks system. Available hooks: ``args``: A dictionary of the arguments being sent to Request(). ``pre_request``: The Request object, directly after being created. ``pre_send``: The Request ...
# -*- coding: utf-8 -*- """ requests.hooks ~~~~~~~~~~~~~~ This module provides the capabilities for the Requests hooks system. Available hooks: ``args``: A dictionary of the arguments being sent to Request(). ``pre_request``: The Request object, directly after being created. ``pre_send``: The Request ...
Fix the script. It did not work at all before.
#!/usr/bin/python # Enable or disable the use of NMEA. import ubx import struct import calendar import os import gobject import logging import sys import socket import time loop = gobject.MainLoop() def callback(ty, packet): print("callback %s" % repr([ty, packet])) if ty == "CFG-PRT": if sys.argv[1...
#!/usr/bin/python # Enable or disable the use of NMEA. import ubx import struct import calendar import os import gobject import logging import sys import socket import time loop = gobject.MainLoop() def callback(ty, packet): print("callback %s" % repr([ty, packet])) if ty == "CFG-PRT": if sys.argv[1...
Add process memory usage script
#!/usr/bin/env python import os import sys def show_usage(): sys.stderr.write('''memio - Simple I/O for /proc/<pid>/mem Dump /proc/<pid>/maps: memio.py <pid> Read from or write to (when some input is present on stdin) memory: memio.py <pid> <start> (<end> | +<size>) memio.py <pid> <hexrange> <hexra...
Update photo and album models for non-required fields
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('imager_images', '0003_auto_20150726_1224'), ] operations = [ migrations.AlterField( model_name='album', ...
Introduce a single program to rule them all...
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Application to capture, and calibrate stereo cameras # # # External dependencies # import argparse import Calibration import CvViewer # # Command line argument parser # parser = argparse.ArgumentParser( description='Camera calibration toolkit.' ) parser.add_argum...
Add cumulative 60 module (L2)
#!/usr/bin/env python3 import json import zmq import zconfig import zutils def main(): logger = zutils.getLogger(__name__) ctx = zmq.Context() subsock = ctx.socket(zmq.SUB) subsock.connect("tcp://{}:{}".format(zconfig.IP_ADDR, zconfig.PROXY_PUB_PORT)) sub...
Add solution for problem 1a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2014 Fabian M. # # 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 configs unit test case
# Copyright (c) 2015 Intel Corp. # # 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 writin...
Add a new script that downloads data for a date range
# Exports all data for the particular user for the particular day # Used for debugging issues with trip and section generation import sys import logging logging.basicConfig(level=logging.DEBUG) import uuid import datetime as pydt import json import bson.json_util as bju import arrow import emission.storage.timeserie...
Add openid fix migration script
"""Fix openids with spaces. A change in the openstackid naming made is so IDs with spaces are trimmed, so %20 are no longer in the openid url. This migration will replace any '%20' with a '.' in each openid. Revision ID: 434be17a6ec3 Revises: 59df512e82f Create Date: 2017-03-23 12:20:08.219294 """ # revision identi...
Add basic tests for CommandChainDispatcher
# -*- coding: utf-8 -*- """Tests for CommandChainDispatcher.""" from __future__ import absolute_import #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import nose.tools as nt from IPython.core.erro...
Add usage test. Currently failing because expects sets and gets lists.
from ccs.icd9 import ICD9 from clinvoc.icd9 import ICD9CM, ICD9PCS from nose.tools import assert_equals def test_icd9(): codesets = ICD9() dx_vocab = ICD9CM() px_vocab = ICD9PCS() for k, v in codesets.dx_single_level_codes: assert isinstance(k, basestring) assert isinstance(v, set) # F...
Add initial code to open agency.txt
import csv import sys def clean_agency_file(*agencies): with open('agency.txt', 'r') as f: reader = csv.reader(f) next(f) for row in reader: if row[0] in agencies: print(row) def main(): agencies = sys.argv[1:] clean_agency_file(*agencies) if __name_...
Add a test for the event server
import os import select import socket import time import unittest from jobmon.protocol import * from jobmon import event_server, transport PORT = 9999 class TestEventServer(unittest.TestCase): def test_event_server(self): event_srv = event_server.EventServer(PORT) event_srv.start() time.s...
Add exercise 4 checking code
from learntools.core import * import tensorflow as tf class Q1(ThoughtExperiment): _solution = "" class Q2(ThoughtExperiment): _solution = "" class Q3A(ThoughtExperiment): _hint = "" _solution = "" class Q3B(ThoughtExperiment): _hint = "" _solution = "" class Q3C(ThoughtExperiment): ...
Write migration to associate group users with the group's files.
"""Associate groups with files. Revision ID: a3fe8c8a344 Revises: 525162a280bd Create Date: 2013-11-05 13:55:04.498181 """ # revision identifiers, used by Alembic. revision = 'a3fe8c8a344' down_revision = '525162a280bd' from alembic import op from collections import defaultdict from sqlalchemy.sql import table, col...
TEST (Still not automatic, to be converted eventually.)
# This tests the observation of observables into lists and maps. # This test should be converted to unittest import _importer from gtkmvc import Model, Observer, Observable # ---------------------------------------------------------------------- # An ad-hoc class which has a chaging method 'change' class MyObservabl...
Test mask resulted in the same value as comprehension list
import numpy as np import pytest from hypothesis import given # To test the equivalence of code to check if it does the same thing: def test_convolution_indexing(): """ To test equivalence of code to repalce for speed""" wav_extended = np.arange(100, 200) flux_extended = np.random.random(size=wav_extende...
Add expire reservations in backport position.
# 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 applicable law or agreed to in...
Add the nodev.specs example code.
# import pytest from nodev.specs.generic import FlatContainer # # possible evolution of a ``skip_comments`` function # def skip_comments_v0(stream): return [line.partition('#')[0] for line in stream] def skip_comments_v1(stream): for line in stream: yield line.partition('#')[0] def skip_comments_...
Add a test for the payload generator of the Uploader class.
"""Tests for the uploader module""" from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from os.path import join from datapackage import DataPackage ...
Add 3D power spectrum for comparing with generated fields
import numpy as np def threeD_pspec(arr): ''' Return a 1D power spectrum from a 3D array. Parameters ---------- arr : `~numpy.ndarray` Three dimensional array. Returns ------- freq_bins : `~numpy.ndarray` Radial frequency bins. ps1D : `~numpy.ndarray` One...
Remove the auth contenttypes thing for now, needs improvement
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a par...
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a par...
Add a couple set benchmarks
""" Benchmark various operations on sets. """ from __future__ import division import numpy as np from numba import jit # Set benchmarks # Notes: # - unless we want to benchmark marshalling a set or list back to Python, # we return a single value to avoid conversion costs @jit(nopython=True) def unique(seq): ...
Implement Parametizer class for defining and cleaning GET parameters
def clean_bool(value, allow_none=False): if isinstance(value, bool): return value if isinstance(value, basestring): value = value.lower() if value in ('t', 'true', '1', 'yes'): return True if value in ('f', 'false', '0', 'no'): return False if allow_n...
Add a debugging plugin to log the size of the queue.
import logging logger = logging.getLogger(__name__) from arke.collect import Collect class queue_monitor(Collect): default_config = {'interval': 60, } def gather_data(self): logger.info("persist_queue: %i, collect_pool: %i" % (self.persist_queue.qsize(), len(self._pool)))
Add example to show random search vs gp
from time import time import numpy as np import matplotlib.pyplot as plt from sklearn.base import clone from sklearn.datasets import load_digits from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedKFold from skopt.dummy_op...
Add functional test for OSUtils
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
Add unit test for the ssh password regex matching
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.cloud_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the salt-cloud utilitie...
Add exercise 6 checking code
from learntools.core import * import tensorflow as tf # Free class Q1(CodingProblem): _solution = "" _hint = "" def check(self): pass class Q2A(ThoughtExperiment): _hint = "Remember that whatever transformation you apply needs at least to keep the classes distinct, but otherwise should more ...
Add spider for Merrill Lynch offices
# -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem import json class MerrillLynchSpider(scrapy.Spider): name = 'merrilllynch' allowed_domains = ['ml.com'] start_urls = ('https://fa.ml.com/',) def parse_branch(self, response): data = json.loads(response.body_as...
Add a very simple performance testing tool.
""" Simple peformance tests. """ import sys import time import couchdb def main(): print 'sys.version : %r' % (sys.version,) print 'sys.platform : %r' % (sys.platform,) tests = [create_doc, create_bulk_docs] if len(sys.argv) > 1: tests = [test for test in tests if test.__name__ in sys.argv...
Add unit test for Splitter.
import os import os.path import pytest from psyrun.core import load_infile, load_results, save_outfile from psyrun.pspace import Param from psyrun.split import Splitter @pytest.mark.parametrize( 'pspace_size,max_splits,min_items,n_splits', [ (7, 4, 4, 2), (8, 4, 4, 2), (9, 4, 4, 3), (15, 4, 4, 4...
TEST New test/example for the new feature supporting custom getter/setter for properties
# Author: Roberto Cavada <cavada@fbk.eu> # # Copyright (c) 2006 by Roberto Cavada # # pygtkmvc is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option...
Add Processor interface for post processing of schemas.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from abc import ABCMeta, abstractmethod class Processor(object): '''Process schemas.''' __metaclass__ = ABCMeta @abstractmethod def process(self, schemas): '''Process *schemas* :p...
Add sample for set chlauth
''' This sample will create a new local queue. MQWeb runs on localhost and is listening on port 8081. ''' import sys import json import httplib import socket import argparse parser = argparse.ArgumentParser( description='MQWeb - Python sample - Set Channel Authentication Record', epilog="For more information: http...
Solve Code Fights build palindrome problem
#!/usr/local/bin/python # Code Fights Build Palindrome Problem def buildPalindrome(st): if st == st[::-1]: return st for i in range(len(st)): s = st + st[i::-1] if s == s[::-1]: return s def main(): tests = [ ["abcdc", "abcdcba"], ["ababab", "abababa"]...
Add small script to print out db stats
#!/usr/bin/env python # Dump stats for raw and queue. import os import time import pymongo import json conn = pymongo.Connection() # db -> collections dbs = { 'raw' : ['commits', 'repos', 'users'], 'queue' : ['commits', 'repos', 'users'] } for db, collections in dbs.iteritems(): for collection in ...
Add text to speech example.
#!/usr/bin/env python # -*- coding: utf-8 -*- """Asks for coffee using different Python modules. Requires macspeechX module: * https://pypi.python.org/pypi/macspeechX/ * http://old.nabble.com/Re:-py-access-to-speech-synth--p18845607.html """ from macspeechX import SpeakString import pyttsx # Using macspeechX # Note:...
Add migration to clear INVITED_AS_REALM_ADMIN.
# -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2020-06-16 22:26 from __future__ import unicode_literals from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def clear_preregistrationuser_invited_as_a...
Complete population script and seeding
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): suits_cat = add_cat('Suits') add_page(cat=suits_cat, title = "Blue suit") add_page(cat=suits_cat, title = "Georgio Arm...
Add python example - channel options
# Copyright 2018 gRPC 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 writing...
Add tests for phone number template tag.
from common.templatetags.common import phone_number class TestPhoneNumberTag(object): """Test cases for the phone number tag""" def test_multi_whitespace(self): """Test passing in a string with lots of whitespace. Whitespace more than 1 character wide should be condensed down to one ...
Add test for uart magma impl
import fault import magma from txmod import TXMOD import random def get_random(port): if isinstance(port, magma.BitType): return random.choice((0, 1)) N = type(port).N return random.randint(0, 2 ** N - 1) if __name__ == "__main__": random.seed(0) #TXMOD_v = magma.DefineFromVerilogFile("...
Cover AggregateFilter with unit tests
import mock from django.test import TestCase from nodeconductor.logging import models as logging_models from nodeconductor.logging.tests import factories as logging_factories from nodeconductor.structure.filters import AggregateFilter from nodeconductor.structure.tests import factories class AggregateFilterTest(Test...
Add missing skimage script for valgrind
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia skimage executable. """ from build_step import BuildStep from valgrind_build_step import ValgrindBuildStep from r...
Test the Pipe base class
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2016 Rémi Duraffort # This file is part of ReactOBus. # # ReactOBus 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, either version 3 of the License, ...
Add a script to find files for DS/Run/LS
#!/usr/bin/env python import argparse from dbs.apis.dbsClient import DbsApi _PREFIX = 'root://eoscms.cern.ch//eos/cms/' def getFilesForQuery(args): global _PREFIX query = { 'dataset' : args.dataset, 'run_num': args.run, 'lumi_list': [l for l in range(args.ls_min, args.ls_max+1)] } api = DbsAp...
Add a version of sensu checking script which works on monitoring-1
#!/usr/bin/env python # encoding: utf-8 import datetime import json import requests JSON_REQUEST = { "query": { "filtered": { "query": { "bool": { "should": [ { "query_string": { "query": "*" } } ] } ...
Add simple switch/case usage example
#!/usr/bin/env python3 ''' Suppose you're trying to estimate someone's median household income based on their current location. Perhaps they posted a photograph on Twitter that has latitude and longitude in its EXIF data. You might go to the FCC census block conversions API (https://www.fcc.gov/general /census-block-co...
Add a simple test for %s
a = "well" b = "seems to work" c = "something else" # form 0 s = "b=%s" % a print s # form 1 s = "b,c,d=%s+%s+%s" % (a, b, c) print s
Test new language feature in cuda python
""" Test basic language features """ from __future__ import print_function, absolute_import, division import numpy as np from numba import cuda from numba.cuda.testing import unittest class TestLang(unittest.TestCase): def test_enumerate(self): tup = (1., 2.5, 3.) @cuda.jit("void(float64[:])") ...
Add nonworking tests for xml writer
import glob import itertools as it import os import parmed as pmd from pkg_resources import resource_filename import pytest from foyer import Forcefield from foyer.tests.utils import atomtype from foyer.xml_writer import write_foyer def test_write_xml(filename, ff_file): structure = pmd.loadfile(filename) forc...
Check in a script to diagnose common system configuration problems.
#!/usr/bin/python # Copyright (c) 2012 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. """Diagnose some common system configuration problems on Linux, and suggest fixes.""" import subprocess import sys all_checks = [] d...
Create Add Data Test script
__author__ = 'chuqiao' import script script.addDataToSolrFromUrl("http://www.elixir-europe.org:8080/events", "http://www.elixir-europe.org:8080/events"); script.addDataToSolrFromUrl("http://localhost/ep/events?state=published&field_type_tid=All", "http://localhost/ep/events");
Add the main interface file.
#!/usr/bin/env python """cli2phone pushes messages from the command line to your android phone. Requires Android 2.2 or newer, and the chrometophone application installed. See: http://code.google.com/p/chrometophone/ Usage: cli2phone URL """ import sys import getopt from auth import Auth apiVersion = '5' baseUrl = ...
Add new Python module for McDowell Chapter 1.
def unique(string): counter = {} for c in string: if c in counter: counter[c] += 1 else: counter[c] = 1 print(counter) for k in counter: if counter[k] > 1: return False else: return True def reverse(string): result = [] for...
Add fetch recipe for the Flutter Engine repository.
# Copyright 2021 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 sys import config_util # pylint: disable=import-error # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=no...
Migrate db to make default_registrant unique for project
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-07 08:15 from __future__ import unicode_literals from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('...
Add basic test script for mcmc_serial. Code now passes with conditions on prior.
import time import numpy as np import yaml import quantitation # Set parameters path_cfg = 'examples/basic.yml' # Load config cfg = yaml.load(open(path_cfg, 'rb')) # Load data mapping_peptides = np.loadtxt(cfg['data']['path_mapping_peptides'], dtype=np.int) mapping_states_obs, intensi...
Add script to convert GTF to BED file.
import tempfile from argparse import ArgumentParser import gffutils import os def disable_infer_extent(gtf_file): """ guess if we need to use the gene extent option when making a gffutils database by making a tiny database of 1000 lines from the original GTF and looking for all of the features """ ...
Add the example test of SeleniumBase in French
# French Language Test - Python 3 Only! from seleniumbase.translate.french import CasDeBase class ClasseDeTest(CasDeBase): def test_exemple_1(self): self.ouvrir_url("https://fr.wikipedia.org/wiki/") self.vérifier_le_texte("Wikipédia") # noqa self.vérifier_un_élément('[title="Visiter la p...
Add compound selection usage example to examples.
from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.behaviors import CompoundSelectionBehavior from kivy.app import runTouchApp from kivy.core.window import Window class SelectableGrid(CompoundSelectionBehavior, GridLayout): def __init__(self, **kwargs): super(Sele...
Test for the __init__ function of the Paladin class
import unittest from classes import Paladin from models.spells.loader import load_paladin_spells_for_level class PaladinTests(unittest.TestCase): def setUp(self): self.name = "Netherblood" self.level = 3 self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength...
Add script for generating spectra on a grid
# -*- coding: utf-8 -*- """Class to create spectra spaced on a regular grid through the box""" import numpy as np import hdfsim import spectra class GriddedSpectra(spectra.Spectra): """Generate metal line spectra from simulation snapshot. Default parameters are BOSS DR9""" def __init__(self,num, base, nspec=2...
Write function to parse cl-json.
from .kqml_string import KQMLString from .kqml_list import KQMLList from .kqml_token import KQMLToken from .kqml_exceptions import KQMLException def parse_json(json_obj): if isinstance(json_obj, list): ret = KQMLList() for elem in json_obj: ret.append(parse_json(elem)) elif isinsta...
Add camelCase to snake_case function.
# -*- coding: utf-8 -*- """ utils.py ~~~~~~~~ Defines utility functions used by UPnPy. """ def camelcase_to_underscore(text): """ Convert a camelCasedString to one separated_by_underscores. Treats neighbouring capitals as acronyms and doesn't separated them, e.g. URL does not become u_r_l. That would...
Add a test of the parser.
from kqml import cl_json, KQMLList def test_parse(): json_dict = {'a': 1, 'b': 2, 'c': ['foo', {'bar': None, 'done': False}], 'this is json': True} res = cl_json.parse_json(json_dict) assert isinstance(res, KQMLList) assert len(res) == 2*len(json_dict.keys())
Create conflict in a more user-friendly way
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. import sys, os, time sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common'))) import driver, http_admin, scenario_common from vcoptparse import * op = OptParser() scenario_common.prepare_option_parser...
Add an awesome way to apply different functions over an array.
""" Apply different function over an array """ def square(num): return num ** 2 def cube(num): return num ** 3 def is_pair(num): return num % 2 functions = [square, cube, is_pair] array = range(0,20) for elemn in array: value = map(lambda x: x(elemn), functions) print (elemn, value)
Add solution to exercise 4.4.
# 3-4 Guest List guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"] message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday." print(message) message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday." print(message) message = "Hi " + guest_l...
Add subroutine to print a dictionary tree
#!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest # To test this module: # python -m unittest -v nested def string_maxlen(txt,max_len=12): n = len(txt)...
Add simple and untested FFT transform
import cmath def fft0(xs): n, ys = len(xs), [] for i in range(n): yi = complex(0, 0) for j in range(n): yi += complex(xs[j]) * cmath.exp(complex(0, -2 * cmath.pi / n * i * j)) ys.append(yi) return ys if __name__ == '__main__': print(fft0([1, 2, 3]))
Fix add help text on forms with migration
# Generated by Django 3.1.13 on 2021-07-16 10:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('infrastructure', '0023_auto_20210716_0738'), ] operations = [ migrations.AlterField( model_nam...
Fix default value for owner
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-02 23:00 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependen...
Test harness and tests for the invert function
import CijUtil import numpy as np import unittest class TestInvertCijFunctions(unittest.TestCase): def setUp(self): self.inmatrix = np.matrix([[0.700, 0.200],[0.400, 0.600]]) self.inerrors = np.matrix([[0.007, 0.002],[0.004, 0.006]]) self.true_inv = np.matrix([[1.765, -0.588],[-1.177, 2.05...
Add script for triggering Buildbucket builds
#!/usr/bin/env python # Copyright (c) 2015 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. """Tool for interacting with Buildbucket. Usage: $ depot-tools-auth login https://cr-buildbucket.appspot.com $ buildbucket.py ...
Add resolution for the 2dGeometry Homework
#!/usr/bin/python import os import numpy as np import math print "This script solves the excercises propossed in the Linear Algebra & 2D Geometry Lectures" # -------------------------------------------------------------------------------------------------- # Length and Normalized Vector v = np.array([4, 8, -4]) len_...
Add a user test script
#!/usr/bin/env python try: import sympy except ImportError: print("sympy is required") else: if sympy.__version__ < '0.7.5': print("SymPy version 0.7.5 or newer is required. You have", sympy.__version__) if sympy.__version__ != '0.7.5': print("The stable SymPy version 0.7.5 is recomme...