commit stringlengths 40 40 | old_file stringlengths 4 264 | new_file stringlengths 4 264 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 624 | message stringlengths 15 4.7k | lang stringclasses 3
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
da80b3deb8d1b3a0172a11fb46af99c1af003c56 | clinical_db/experiment_script.py | clinical_db/experiment_script.py | '''
Experiments are recorded in this script
'''
# Experiment Date:06/24/2015
def compare_lab_tests_and_vitals():
''' Compare the ability of prediction with lab tests and vital test for HF patients'''
if __name__ == '__main__':
| Add script for experiment records | Add script for experiment records
| Python | mit | belemizz/mimic2_tools,belemizz/mimic2_tools | |
28acda0265c8913e761f9a63315fe17c09a3e5fc | src/zeit/content/text/tests/test_jinja.py | src/zeit/content/text/tests/test_jinja.py | import zeit.cms.testing
import zeit.content.text.jinja
import zeit.content.text.testing
class PythonScriptTest(zeit.cms.testing.FunctionalTestCase):
layer = zeit.content.text.testing.ZCML_LAYER
def create(self, text):
result = zeit.content.text.jinja.JinjaTemplate()
result.uniqueId = 'http:/... | Add test for dummy rendering (belongs to commit:be85116) | ZON-4007: Add test for dummy rendering (belongs to commit:be85116)
| Python | bsd-3-clause | ZeitOnline/zeit.content.text | |
de8d507e64894bdaaf036f99f179637c2660f0f1 | tests/issue0078.py | tests/issue0078.py | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 22:09:10 2013
@author: Jeff
"""
import logging
try: print('Logger already instantiated, named: ', logger.name)
except:
# create logger
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# create console handler with a higher log level
ch... | Test script show how we might use the Python logger more effectively | Test script show how we might use the Python logger more effectively
Former-commit-id: cc69a6ab3b6c61fd2f3e60bd16085b81cda84e42
Former-commit-id: 28ba0ba57de3379bd99b9f508972cd0520c04fcb | Python | mit | amdouglas/OpenPNM,amdouglas/OpenPNM,stadelmanma/OpenPNM,PMEAL/OpenPNM,TomTranter/OpenPNM | |
2b7a2e0ffde981afd96395e5422eb9574e4ff51f | svm_experiments.py | svm_experiments.py | from svm import SVMModel
if __name__ == '__main__':
features = [
# 'refuting',
'ngrams',
# 'polarity',
'named',
# 'jaccard'
]
model = SVMModel()
train_data = model.get_data('data/train_bodies.csv', 'data/train_stances.csv')
test_data = model.get_data('data/compet... | Add svm experiment on test data | Add svm experiment on test data
| Python | apache-2.0 | sarahannnicholson/FNC | |
1c4e1dc0fbd4681fbb1bf5c63145a2fbed130890 | xpcom-leak-analyzer.py | xpcom-leak-analyzer.py | #!/usr/bin/python
# 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/.
import sys
import os
import re
bloatStartPatt = re.compile('^..:..:.. INFO - \|<----------... | Add script to analyze bloatview logs | Add script to analyze bloatview logs
| Python | mpl-2.0 | amccreight/mochitest-logs | |
149879c6029efac02bec30b67d13592287f2898c | tests/test_flatc.py | tests/test_flatc.py | import pytest
# TODO: Duplicate code
# Figure out how to import from flatc.py
def get_attrs_dict(attrs):
attrs_dict = {x[0]: x[1] for x in attrs if len(x) == 2}
ret = {x[0]: None for x in attrs}
ret.update(attrs_dict)
return ret
def test_attrs_dict():
assert get_attrs_dict(['a', ['b', 10], 'c'])... | Add a unit test for flatc | Add a unit test for flatc
| Python | mit | adsharma/flattools,adsharma/flattools,adsharma/flattools | |
cd88e724f7f2f8293a509db3dc0558904beee6e4 | tools/test/psa/psa_target_config_test.py | tools/test/psa/psa_target_config_test.py | #!/usr/bin/env python
"""
Copyright (c) 2019-2020 ARM Limited. All rights reserved.
SPDX-License-Identifier: Apache-2.0
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/licens... | Add a script to validate PSA targets | psa: Add a script to validate PSA targets
Add a script to parse `targets.json` to identify PSA targets and ensure
mandatory parameters are configured correctly for all PSA targets.
Signed-off-by: Devaraj Ranganna <53e2fcb007e5c6e2caf46b91114119a655266f64@arm.com>
| Python | apache-2.0 | mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed | |
85da0b9062d8266a3e3fe4cd29fbb5ea79a7cedf | tests/geneagrapher/local_data_grabber.py | tests/geneagrapher/local_data_grabber.py | import os
import sys
from BeautifulSoup import BeautifulSoup
from geneagrapher.grabber import get_record_from_tree
class LocalDataGrabber:
"""A class for grabbing locally-cached test data."""
def __init__(self):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_v... | Add LocalDataGrabber class so tests work with local data. | Add LocalDataGrabber class so tests work with local data.
This changeset adds the LocalDataGrabber class in the test source
tree. This class exposes the same interface as Grabber -- so that
it can be used in place of it -- but is only able to grab test
data from the local test data directory. This is useful for testin... | Python | mit | davidalber/Geneagrapher,davidalber/Geneagrapher | |
1f3625b98de4edd8a0d0bcce882c5f79aeaf23b2 | tests/rules_tests/NoRuleSpecifiedTest.py | tests/rules_tests/NoRuleSpecifiedTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class NoRuleSpecifiedTest(TestCase):
pass
if __name__ == '__main__':
main() | Add file for tests, when no rule is specified | Add file for tests, when no rule is specified
| Python | mit | PatrikValkovic/grammpy | |
2cb905a4a0da9650135ab297d9e55c02bc7261c5 | pytest_run.py | pytest_run.py | # coding=utf-8
"""This is a script for running pytest from the command line.
This script exists so that the project directory gets added to sys.path, which
prevents us from accidentally testing the globally installed willie version.
pytest_run.py
Copyright 2013, Ari Koivula, <ari@koivu.la>
Licensed under the Eiffel F... | Add a script for running pytest with the correct sys.path. | Add a script for running pytest with the correct sys.path.
| Python | mit | Uname-a/knife_scraper,Uname-a/knife_scraper,Uname-a/knife_scraper | |
eb5e6bde589f3598d955c0d7389f7054a3a3c642 | 2017-code/test_scalability.py | 2017-code/test_scalability.py | # test_scalability.py
# Ronald L. Rivest with Huasyn Karimi
import syn2
def tester(se):
# copy code here from syn2.test; modify as needed
def test_scale(k):
# start timer
se = syn2.SynElection()
# ... set parameters here based on k
# run "test"
# stop timer; print k and elapsed time
f... | Add prototype code for testing scalability. | Add prototype code for testing scalability.
| Python | mit | ron-rivest/2017-bayes-audit,ron-rivest/2017-bayes-audit | |
1fafccc7df5179ce89b100537e45307417658512 | tests/test_validators.py | tests/test_validators.py | """
test_validators
~~~~~~~~~~~~~~
Unittests for bundled validators.
:copyright: 2007-2008 by James Crasta, Thomas Johansson.
:license: MIT, see LICENSE.txt for details.
"""
from py.test import raises
from wtforms.validators import ValidationError, length, url, not_empty, email, ip_addres... | Add first basic unittests using py.test | Add first basic unittests using py.test
| Python | bsd-3-clause | clones/wtforms | |
3644e3dc2d97f87b3810f1295a98b8977fa0c387 | tests/test_template_filters.py | tests/test_template_filters.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from flask import render_template_string
def test_nl2br_filter(app):
s = '{{ "\n"|nl2br }}'
rs = render_template_string(s)
assert rs == '<p><br/>\n</p>'
def test_blankspace2nbsp_filter(app):
s = '{{ " \t"|blankspace2nbs... | Add template filters test cases | Add template filters test cases
| Python | mit | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf | |
58bee0ac0df709f9a5cee83e7828dce148182d10 | tests/v6/test_tee_generator.py | tests/v6/test_tee_generator.py | from .context import tohu
from tohu.v6.primitive_generators import Integer, TimestampPrimitive
from tohu.v6.derived_generators import IntegerDerived, Tee
from tohu.v6.derived_generators_v2 import TimestampDerived
from tohu.v6.custom_generator import CustomGenerator
def test_tee_generator():
class QuuxGenerator(C... | Add a few tests for Tee | Add a few tests for Tee
| Python | mit | maxalbert/tohu | |
2d9cc52e6ce6a6d2584e1d73e3d84ca3538758d9 | Sensors/recordCalibration.py | Sensors/recordCalibration.py | from pymavlink import mavutil
fileout = open('acc.txt', 'w')
filemag = open('mag.txt', 'w')
filegyro = open('gyro.txt', 'w')
# create a mavlink serial instance
master = mavutil.mavlink_connection('/dev/ttyUSB1', baud=57600, source_system=255)
try:
while True:
msg = master.recv_match(type='HEARTBEAT', bloc... | Add a script to generate some files to be used for the sensor calibration | Add a script to generate some files to be used for the sensor calibration
| Python | mit | baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite | |
6ca79d2ce16f8745c8d58c3dea20174931820ef3 | api/models.py | api/models.py | from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from datetime import datetime
from api import db
class User(db.Model):
id = db.Column(db.Inte... | Add User object to model | Add User object to model
| Python | mit | EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list | |
d57fab92485e403dd24321ded7090b9c46d61655 | send_packet.py | send_packet.py | from socket import *
def send_packet(src, dst, eth_type, payload, interface = "eth0"):
"""Send raw Ethernet packet on interface."""
assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses
assert(len(eth_type) == 2) # 16-bit ethernet type
s = socket(AF_PACKET, SOCK_RAW)
# From the docs: "For raw pack... | Add sending raw packet example | Add sending raw packet example | Python | mit | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts | |
5f411b0ce564eba7a4b1f6c07d0d3209d63eef8e | searchbypmid.py | searchbypmid.py | import requests, untangle
pmcid = 'PMC3834665'
epmc_basequeryurl = "http://www.ebi.ac.uk/europepmc/webservices/rest/search"
''' Make query to EuropePMC'''
query = {'query':pmcid,'resulttype':'core'}
r = requests.get(epmc_basequeryurl, params=query)
'''Use untangle to make python structure from xml'''
obj = untangle.... | Add basic search by pmcid | Add basic search by pmcid
| Python | mit | tarrow/epmclib | |
57c09aad6ad8de1fb5bb13d92b69db381f55cdac | lobster/filemanager.py | lobster/filemanager.py | import os
import time
TMP_DIR = "/tmp/lobster"
def get_tempdir():
tmp_path = TMP_DIR
if not os.path.isdir(tmp_path):
os.mkdir(tmp_path)
return tmp_path
def get_workingdir():
tmp_dir = get_tempdir()
dir_name = str(int(time.time()))
path = "/".join([tmp_dir, dir_name])
os.mkdir(path... | Add functions to handle temp directory for download | Add functions to handle temp directory for download
| Python | mit | noahfx/lobster | |
3e52dcc7c4af0ab7208abebdfb59a079ee9b764b | tests/test_iati_wiki.py | tests/test_iati_wiki.py | import pytest
from web_test_base import *
class TestIATIWiki(WebTestBase):
urls_to_get = [
"http://wiki.archive.iatistandard.org/"
]
def test_locate_links(self, loaded_request):
"""
Tests that each page contains links to the defined URLs.
"""
result = self._get_link... | Add tests for the IATI wiki | Add tests for the IATI wiki
This adds tests to ensure that IATI wiki is up and contains specified links
| Python | mit | IATI/IATI-Website-Tests | |
031016e21879ad7c0e3a2c1c888e973bfb23c529 | abel/tests/test_hansenlaw.py | abel/tests/test_hansenlaw.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
from numpy.testing import assert_allclose
from abel.hansenlaw import iabel_hansenlaw
from abel.analytical import GaussianAnalytical
from abel.benchmark import absolute_ratio... | Add unit tests for the HansenLaw implementation | Add unit tests for the HansenLaw implementation
| Python | mit | PyAbel/PyAbel,rth/PyAbel,DhrubajyotiDas/PyAbel,stggh/PyAbel,huletlab/PyAbel | |
76c580f04edc1995e2dc9d107f84a714c088c0c2 | nth-prime/nth_prime1.py | nth-prime/nth_prime1.py | def nth_prime(n):
if n <= 0:
raise ValueError
for i, prime in enumerate(prime_gen()):
if n == i + 1:
return prime
def prime_gen():
def n_gen():
n = 2
while True:
yield n
n += 1
nonprimes = {}
for n in n_gen():
prime = nonp... | Add better solution for nth prime | Add better solution for nth prime
| Python | mit | always-waiting/exercism-python | |
cd4380577061bd3e10c72926db80a830f3e90100 | tests/unit/cloud/clouds/openstack_test.py | tests/unit/cloud/clouds/openstack_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Bo Maryniuk <bo@suse.de>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase
from salt.cloud.clouds import openstack
from salttesting.mock import MagicMock, patch
from tests.unit.cloud.clouds ... | Add initial unit test for openstack cloud module | Add initial unit test for openstack cloud module
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | |
df5ee98d6a2e39318e76f67afb4b02cd8e48def1 | py/http2/http2/utils.py | py/http2/http2/utils.py | __all__ = [
'make_ssl_context',
]
import ssl
def make_ssl_context(crt, key):
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_context.load_cert_chain(crt, key)
if ssl.HAS_ALPN:
ssl_context.set_alpn_protocols(['h2'])
else:
asserts.precond(ssl.HAS_NPN)
ssl_context.set_... | Add helper for HTTP/2 SSL context | Add helper for HTTP/2 SSL context
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | |
9244e9d17ed57e1848bf52566d401e19c2cde8b7 | integration-test/491-feature-tests.py | integration-test/491-feature-tests.py | from . import FixtureTest
class FeaturesTest(FixtureTest):
def test_shops(self):
self._run_test(
'http://www.openstreetmap.org/node/2893904480',
'16/19299/24631', {'kind': 'bakery'})
self._run_test(
'http://www.openstreetmap.org/node/886395953',
'16/... | Add tests for some shop POIs | Add tests for some shop POIs
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | |
92946362496f950a28357f3dee44b936cc59909a | StandingsCheck.py | StandingsCheck.py | #!/usr/bin/python
from eveapi import eveapi
import ChatKosLookup
import sys
class StandingsChecker:
def __init__(self, keyID, vCode):
self.checker = ChatKosLookup.KosChecker()
self.eveapi = self.checker.eveapi.auth(keyID=keyID, vCode=vCode)
def check(self):
contacts = self.eveapi.char.ContactList()
... | Add standings checker to prevent friendly fire | Add standings checker to prevent friendly fire
| Python | mit | lizthegrey/nrds-tools | |
102855b8d3dc7258c68a1f2bac3bb4c8953732dc | backend/scripts/adminuser.py | backend/scripts/adminuser.py | #!/usr/bin/env python
import rethinkdb as r
from optparse import OptionParser
import sys
def create_group(conn):
group = {}
group['name'] = "Admin Group"
group['description'] = "Administration Group for Materials Commons"
group['id'] = 'admin'
group['owner'] = 'admin@materialscommons.org'
grou... | Add utility to create administrative users. | Add utility to create administrative users.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | |
84acd57a114fb2a9c2e17e729586399e66bb0eb9 | bin/scrape-bus-stops.py | bin/scrape-bus-stops.py | #!/usr/bin/python3
import urllib.request
import json
import os
import sys
endpoint = 'http://datamall2.mytransport.sg/ltaodataservice/BusStops?$skip='
def get_bus_stops(account_key: str, offset: int):
url = '{}{}'.format(endpoint, offset)
req = urllib.request.Request(url, headers={'AccountKey': account_key... | Add script to get bus stops from datamall | [skip ci] Add script to get bus stops from datamall
| Python | mit | yi-jiayu/bus-eta-bot,yi-jiayu/bus-eta-bot,yi-jiayu/bus-eta-bot,yi-jiayu/bus-eta-bot | |
4ec87c35ed6603f1eafb540840a8f978ea87130c | argqueue/queue.py | argqueue/queue.py | import sqlite3 as sql
class Queue(object):
def __init__(self, db_filename):
self.con = sql.connect(db_filename)
self._create_tables()
def _create_tables(self):
with self.con:
cur = self.con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS "
"Arguments(Id INTEGER PRIMARY K... | Create Queue with pop and put | Create Queue with pop and put
| Python | mit | bewt85/jobqueue | |
a097aef42255b963b91c54494355d34cdc7c08f7 | single-pop/singlepop2npy.py | single-pop/singlepop2npy.py | import sys
import numpy as np
def read_phi(flname, n_steps, n_loci):
sampled_phis = np.zeros((n_steps, n_loci))
fl = open(flname)
current_iter_idx = 0 # index used for storage
last_iter_idx = 0 # index used to identify when we finish a step
for ln in fl:
cols = ln.strip().split()
iter_idx = int(cols[0])
loc... | Add conversion script for single pop to numpy | Add conversion script for single pop to numpy
| Python | apache-2.0 | rnowling/pop-gen-models | |
3236e1dc9624a4e4a2770cf463e8f366e4eb7cde | algorithms/a_star_tree_misplaced_tiles.py | algorithms/a_star_tree_misplaced_tiles.py | """
pynpuzzle - Solve n-puzzle with Python
A* tree search algorithm using misplaced tiles heuristic
Version : 1.0.0
Author : Hamidreza Mahdavipanah
Repository: http://github.com/mahdavipanah/pynpuzzle
License : MIT License
"""
import heapq
from .util import best_first_seach as bfs
def search(state, goal_state):
... | Add a* tree search algorithm using misplaced tiles heuristic | Add a* tree search algorithm using misplaced tiles heuristic
| Python | mit | mahdavipanah/pynpuzzle | |
9f5e11f789c01e3a6da0ff2c7376c4ead2741a6a | pyramid_authsanity/tests/test_includeme.py | pyramid_authsanity/tests/test_includeme.py | import pytest
from pyramid.authorization import ACLAuthorizationPolicy
import pyramid.testing
from zope.interface import (
Interface,
implementedBy,
providedBy,
)
from zope.interface.verify import (
verifyClass,
verifyObject
)
from pyramid_services import IServiceClassifier
from... | Add tests for the includeme/settings | Add tests for the includeme/settings
| Python | isc | usingnamespace/pyramid_authsanity | |
6aab268f697a2cbdc39aa6ccf59801bd04068626 | examples/livestream_datalogger.py | examples/livestream_datalogger.py | from pymoku import Moku, MokuException
from pymoku.instruments import *
import time, logging, traceback
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.DEBUG)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP
m = Moku('192.1... | Add example code to use stream from network | Datalogger: Add example code to use stream from network
| Python | mit | benizl/pymoku,liquidinstruments/pymoku | |
cd13ddd24df33e3a34cd5fc71c3ad0b352952f8b | police_api/exceptions.py | police_api/exceptions.py | from requests.exceptions import HTTPError
class BaseException(Exception):
pass
class APIError(BaseException, HTTPError):
"""
The API responded with a non-200 status code.
"""
def __init__(self, http_error):
self.message = getattr(http_error, 'message', None)
self.response = geta... | from requests.exceptions import HTTPError
class BaseException(Exception):
pass
class APIError(BaseException, HTTPError):
"""
The API responded with a non-200 status code.
"""
def __init__(self, http_error):
self.message = getattr(http_error, 'message', None)
self.response = geta... | Add __str__ to APIError exception | Add __str__ to APIError exception
| Python | mit | rkhleics/police-api-client-python |
018ecf79f5235882b47d37f363f746fce271a7cd | fabfile-development.py | fabfile-development.py | from fabric.api import *
# Fill out USER and HOSTS configuration before running
env.user = ''
env.hosts = ['']
env.code_dir = '/home/%s/rtd/checkouts/readthedocs.org' % (env.user)
env.virtualenv = '/home/%s/rtd' % (env.user)
def install_prerequisites():
"""Install prerequisites."""
sudo("apt-get -y install p... | Add fabfile to install readthedocs for development. | Add fabfile to install readthedocs for development.
* Automates step-by-step instructions in Installation docs.
* Installing prerequisites is specific to Debian/Ubuntu. Edit
if using a different distribution or different OS.
* Clean is also Debian/Ubuntu specific.
| Python | mit | laplaceliu/readthedocs.org,clarkperkins/readthedocs.org,LukasBoersma/readthedocs.org,safwanrahman/readthedocs.org,agjohnson/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,dirn/readthedocs.org,stevepiercy/readthedocs.org,attakei/readthedocs-oauth,cgourlay/readthedocs.org,davidfischer/readthedocs.org,attakei/r... | |
2fa79ad053f8af0acc121543a9ceb85cc07c2ac2 | step_0/scripts/instructional_sampling.py | step_0/scripts/instructional_sampling.py | # coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# sc is an existing SparkContext.
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
directory = "/Volumes/JS'S FIT/json"
datasets = sqlContext.read.json(directory)
file_count = datasets.where(datasets['verb'].isNull()).count()
assert ... | Add step 0, which create a sample file for labelling instruction | Add step 0, which create a sample file for labelling instruction
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis | |
d269568387b622861001fdc39eeeaff03ebd9a78 | formulamanager.py | formulamanager.py | import os
import imp
_formula_cache = {}
_default_search_path = [os.path.join(os.path.dirname(__file__), "..", "Formula")]
class FormulaManager:
@staticmethod
def _find(name, search_path=[]):
file_path = ""
for path in search_path + default_search_path:
if os.path.exists(os.path.j... | Implement class for managing formulas | Implement class for managing formulas
| Python | mit | peterl94/CLbundler,peterl94/CLbundler | |
eff79d3dc25e2cd5a296f50e051bd950e73ebf47 | generate_sound.py | generate_sound.py | from scipy.io import wavfile
import numpy as np
import subprocess
from scipy.signal import hilbert, chirp
from tuning import pitch_to_freq
def sample_time(since, until, fs=44100.):
'''
Generates time sample in given interval [since; until]
with given sampling rate (fs).
'''
return np.arange(since,... | Add basic sound generation (time sampling, sine wave, white noise, save to WAV file, play via afplay). | Add basic sound generation (time sampling, sine wave, white noise, save to WAV file, play via afplay).
| Python | mit | bzamecnik/tfr,bzamecnik/tfr | |
c12d70090b47765a658a98c29fd332ca6ec057d7 | bin/migrate-tips.py | bin/migrate-tips.py | from gratipay.wireup import db, env
from gratipay.models.team import Team, AlreadyMigrated
db = db(env())
slugs = db.all("""
SELECT slug
FROM teams
WHERE is_approved IS TRUE
""")
for slug in slugs:
team = Team.from_slug(slug)
try:
team.migrate_tips()
print("Migrated tips for '%... | Add script for migrating tips to new teams | Add script for migrating tips to new teams
| Python | mit | studio666/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio6... | |
63b4b1dd0301686f9d14842d680a1f41eb7d0596 | candidates/tests/test_person_view.py | candidates/tests/test_person_view.py | # Smoke tests for viewing a candidate's page
import re
from mock import patch
from django_webtest import WebTest
from .fake_popit import FakePersonCollection
@patch('candidates.popit.PopIt')
class TestPersonView(WebTest):
def test_get_tessa_jowell(self, mock_popit):
mock_popit.return_value.persons = F... | Add a basic smoke test for a person view page | Add a basic smoke test for a person view page
| Python | agpl-3.0 | datamade/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,openstate/yournextrepresentat... | |
2a35dc8835aab9471198a2e1bd32de0ad31014eb | ci/send-test/run.py | ci/send-test/run.py | import bernhard
import socket
import struct
import time
import sys
def events(n):
events = list()
for i in range(0, n):
events.append(bernhard.Event(params={'host': "host-%i" % i,
'service' : 'service-foo',
'tags'... | Add integration test for receiving chunks | Add integration test for receiving chunks
| Python | mit | juruen/cavalieri,juruen/cavalieri,juruen/cavalieri,juruen/cavalieri | |
fdc1723e5d4769902f7896264e27a7d475f2ba1a | test/features/steps/access_db.py | test/features/steps/access_db.py | #!/usr/bin/env python2
from __future__ import print_function
import logging
import time
import sys
import psycopg2
from behave import *
from contextlib import contextmanager
from cluster_under_test import *
from db_retriable import *
@when('application inserts {number} batches of test data')
def step_insert_test_data(... | Add db related test steps | Add db related test steps
| Python | mit | Galeria-Kaufhof/private-postgres-rds,Galeria-Kaufhof/private-postgres-rds,Galeria-Kaufhof/private-postgres-rds | |
1316ed65550b47d694b870093c38fef47e88a06c | tests/test_entities.py | tests/test_entities.py | from __future__ import unicode_literals
from ftfy import fix_text, fix_text_segment
from nose.tools import eq_
def test_entities():
example = '&\n<html>\n&'
eq_(fix_text(example), '&\n<html>\n&')
eq_(fix_text_segment(example), '&\n<html>\n&')
eq_(fix_text(example, fix_entities=True... | Add tests for the fix_entities parameter | Add tests for the fix_entities parameter
| Python | mit | rspeer/python-ftfy | |
ef99851831472c75308220ca6a2ac6d14c17e150 | comics/crawlers/spikedmath.py | comics/crawlers/spikedmath.py | from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
from comics.crawler.utils.lxmlparser import LxmlParser
class ComicMeta(BaseComicMeta):
name = 'Spiked Math'
language = 'en'
url = 'http://www.spikedmath.com/'
start_date = '2009-08-24'
history_capable_day... | Add crawler for 'Spiked Math' | Add crawler for 'Spiked Math'
| Python | agpl-3.0 | klette/comics,jodal/comics,datagutten/comics,datagutten/comics,klette/comics,jodal/comics,jodal/comics,datagutten/comics,klette/comics,datagutten/comics,jodal/comics | |
ef6457f6cbe6c56ade9d84bce738f8ab58cd4e95 | encryptit/tests/dump_json/test_encoder.py | encryptit/tests/dump_json/test_encoder.py | import json
from nose.tools import assert_equal
from encryptit.dump_json import OpenPGPJsonEncoder
def test_encode_bytes():
result = json.dumps(bytes(bytearray([0x01, 0x08])), cls=OpenPGPJsonEncoder)
assert_equal('{"octets": "01:08", "length": 2}', result)
def test_encode_bytearray():
result = json.du... | Add test for JSON encoding `bytes` and `bytearray` | Add test for JSON encoding `bytes` and `bytearray`
| Python | agpl-3.0 | paulfurley/encryptit,paulfurley/encryptit | |
e303425602e7535fb16d97a2f24a326791ef646d | tests/test_job.py | tests/test_job.py | import pytest
import multiprocessing
from copy import deepcopy
from pprint import pprint
import virtool.job
class TestProcessor:
def test(self, test_job):
"""
Test that the processor changes the ``_id`` field to ``job_id``.
"""
processed = virtool.job.processor(deepcopy... | Add first job module tests | Add first job module tests
| Python | mit | igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool | |
8860cb45cbc0be048a0f87335b7a150a4d8b0b7a | PRESUBMIT.py | PRESUBMIT.py | # 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.
_EXCLUDED_PATHS = (
)
def _CommonChecks(input_api, output_api):
results = []
results.extend(input_api.canned_checks.PanProjectChecks(
input_api... | Add a basic presubmit script. | Add a basic presubmit script.
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@70 0e6d7f2b-9903-5b78-7403-59d27f066143
| Python | bsd-3-clause | bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer | |
b008bcab5078e7ac598e743bc8f739393c62334f | contrib/add-capsule-header.py | contrib/add-capsule-header.py | #!/usr/bin/python3
#
# Copyright (C) 2019 Richard Hughes <richard@hughsie.com>
#
# SPDX-License-Identifier: LGPL-2.1+
import sys
import uuid
import argparse
import struct
CAPSULE_FLAGS_PERSIST_ACROSS_RESET = 0x00010000
CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE = 0x00020000
CAPSULE_FLAGS_INITIATE_RESET = 0x00040000
def mai... | Add a simple script to add a capsule header | Add a simple script to add a capsule header
This may be helpful for OEMs and ODMs shipping 'bare' firmware.
| Python | lgpl-2.1 | fwupd/fwupd,hughsie/fwupd,fwupd/fwupd,hughsie/fwupd,vathpela/fwupd,vathpela/fwupd,hughsie/fwupd,vathpela/fwupd,fwupd/fwupd,vathpela/fwupd,hughsie/fwupd,fwupd/fwupd | |
f525d04e978c35132db6ff77f455cf22b486482f | mod/httpserver.py | mod/httpserver.py | """wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.s... | """wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), ... | Allow resuse-addr at http server start | Allow resuse-addr at http server start
| Python | mit | floooh/fips,floooh/fips,michaKFromParis/fips,floooh/fips,michaKFromParis/fips,anthraxx/fips,mgerhardy/fips,anthraxx/fips,mgerhardy/fips,code-disaster/fips,code-disaster/fips |
2585d3fac2cedf17a5d851629f8e898d0ed6ec61 | umibukela/migrations/0014_auto_20170110_1019.py | umibukela/migrations/0014_auto_20170110_1019.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('umibukela', '0013_auto_20161215_1252'),
]
operations = [
migrations.RemoveField(
model_name='surveysource',
... | Add forgotten table delete for table we don't need | Add forgotten table delete for table we don't need
| Python | mit | Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela | |
eec00e07d8e50d260249eab6cbefc976cc184683 | crypto/PRESUBMIT.py | crypto/PRESUBMIT.py | # 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.
"""Chromium presubmit script for src/net.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit ... | Add crypto pre-submit that will add the openssl builder to the default try-bot list. | Add crypto pre-submit that will add the openssl builder to the default try-bot list.
BUG=None
TEST=git try should run a linux_redux try job too.
Review URL: http://codereview.chromium.org/9235031
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@119094 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | Fireblend/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,rogerwang/chromium,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,ltilve/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dednal/chromium.src,patrickm/chromium.src,littlstar/chromium.src,mohamed--ab... | |
ecd9e9a3f97bdf9489b6dc750d736855a2c109c2 | tests/test_setup_py_hook.py | tests/test_setup_py_hook.py | from unittest import TestCase, mock
from semantic_release import setup_hook
class SetupPyHookTests(TestCase):
@mock.patch('semantic_release.cli.main')
def test_setup_hook_should_not_call_main_if_to_few_args(self, mock_main):
setup_hook(['setup.py'])
self.assertFalse(mock_main.called)
@m... | Add tests for the setup.py hook | Add tests for the setup.py hook
| Python | mit | wlonk/python-semantic-release,relekang/python-semantic-release,jvrsantacruz/python-semantic-release,relekang/python-semantic-release,riddlesio/python-semantic-release | |
5e48d933795cc367ba0c5c378994c1b6c5cb3fb2 | osf/migrations/0023_merge_20170503_1947.py | osf/migrations/0023_merge_20170503_1947.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-04 00:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0022_auto_20170503_1818'),
('osf', '0021_retraction_date_retracted'),
]
operat... | Add merge migration for hotfix 0.107.6 | Add merge migration for hotfix 0.107.6
| Python | apache-2.0 | Nesiehr/osf.io,Johnetordoff/osf.io,icereval/osf.io,caseyrollins/osf.io,saradbowman/osf.io,baylee-d/osf.io,chrisseto/osf.io,cslzchen/osf.io,TomBaxter/osf.io,cslzchen/osf.io,adlius/osf.io,aaxelb/osf.io,mfraezz/osf.io,chennan47/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,aaxelb/osf.io,baylee-d/osf.io,ch... | |
7a15963a81da6120a79f282dcf43e5e508d13ff5 | queries.py | queries.py | #!/usr/bin/env python
# Brandon Heller
#
# Run geo, time, and combined queries to get an early idea of how interactive
# this might be.
import time
from datetime import datetime
from pymongo import Connection
INPUT_DB = 'processed'
conn = Connection(slave_okay=True)
processed = conn[INPUT_DB]
def time_queries():
... | Add time and geo query examples | Add time and geo query examples
| Python | mit | emarschner/gothub,emarschner/gothub,emarschner/gothub,emarschner/gothub | |
1294679a7ea4ceacf610e4dc103677aeedc7b7ea | common/src/split.py | common/src/split.py |
from pysamimport import pysam
import re, os, hashlib
class SplitBAM(object):
def __init__(self,bamfile,readgroups,batchsize=10,directory='.',index=False):
self.bamfile = bamfile
self.bambase,self.bamextn = self.bamfile.rsplit('.',1)
self.readgroups = readgroups
self.batchsize = bat... | Split bam into files based on read grouping | Split bam into files based on read grouping
| Python | mit | HorvathLab/NGS,HorvathLab/NGS,HorvathLab/NGS,HorvathLab/NGS,HorvathLab/NGS | |
2dec0f46c6b8ed61f6fd4723bb43711603ea754f | examples/github_test.py | examples/github_test.py | from seleniumbase import BaseCase
class GitHubTests(BaseCase):
def test_github(self):
self.open("https://github.com/")
self.update_text("input.header-search-input", "SeleniumBase\n")
self.click('a[href="/seleniumbase/SeleniumBase"]')
self.assert_element("div.repository-content")
... | Add a new example test (GitHub) | Add a new example test (GitHub)
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/SeleniumBase | |
5d8f4c3dc7fbd8bc7380e272889640271b512582 | tests/io/test_pickle.py | tests/io/test_pickle.py | import pickle
import pytest
from bonobo import Bag, PickleReader, PickleWriter, open_fs
from bonobo.constants import BEGIN, END
from bonobo.execution.node import NodeExecutionContext
from bonobo.util.testing import CapturingNodeExecutionContext
def test_write_pickled_dict_to_file(tmpdir):
fs, filename = open_fs(... | Add tests for pickle functionality | Add tests for pickle functionality
| Python | apache-2.0 | python-bonobo/bonobo,hartym/bonobo,hartym/bonobo,python-bonobo/bonobo,hartym/bonobo,python-bonobo/bonobo | |
d184afa1cfcef372b50ab8b231fe6db01b497f65 | projects/gsc/experiments/gsc_onecyclelr.py | projects/gsc/experiments/gsc_onecyclelr.py | # Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it unde... | Add a basic example GSC experiment with OneCycleLR | Add a basic example GSC experiment with OneCycleLR
| Python | agpl-3.0 | numenta/nupic.research,numenta/nupic.research,subutai/nupic.research,mrcslws/nupic.research,subutai/nupic.research,mrcslws/nupic.research | |
39a15c3842faa8ffeae78ec31db54656888448ec | testcases/OpTestRebootTimeout.py | testcases/OpTestRebootTimeout.py | #!/usr/bin/env python2
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2018
# [+] International Business Machines 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 Lic... | Test time to complete reboot call | TestReboot: Test time to complete reboot call
Useful for tracking the time we're losing between calling reboot and
actually rebooting.
Signed-off-by: Samuel Mendoza-Jonas <f16bed56189e249fe4ca8ed10a1ecae60e8ceac0@mendozajonas.com>
| Python | apache-2.0 | open-power/op-test-framework,open-power/op-test-framework,open-power/op-test-framework | |
918cef54c3cd83f41d1322ffc509c78e28b341f5 | tests/test_redis/test_lua_error_return.py | tests/test_redis/test_lua_error_return.py | #!/usr/bin/env python
#coding: utf-8
from unittest import TestCase
from redis import Redis, ResponseError
from .common import *
class LuaReturnErrorTestCase(TestCase):
def test_lua_return_error(self):
"""Test the error described on issue 404 is fixed.
https://github.com/twitter/twemproxy/issue... | Add testcase of error with no space | Add testcase of error with no space
Cherry-picked from https://github.com/twitter/twemproxy/pull/406
The alternate fix 6c962267d7fab8595940367b0cc8fb6f75f66cea was used
Amended to work with the updated test framework
Related to https://github.com/twitter/twemproxy/issues/404
Co-Authored-By: Tyson Andre <a29c2fb3fa... | Python | apache-2.0 | ifwe/twemproxy,ifwe/twemproxy,ifwe/twemproxy,ifwe/twemproxy | |
bead9f754bb8a3b6ffc55ae24c7436771c0f792e | CodeFights/fileNaming.py | CodeFights/fileNaming.py | #!/usr/local/bin/python
# Code Fights File Naming Problem
def fileNaming(names):
valid = []
tmp = dict()
for name in names:
if name not in tmp:
valid.append(name)
tmp[name] = True
else:
# That file name has been used
k = 1
new = n... | Solve Code Fights file naming problem | Solve Code Fights file naming problem
| Python | mit | HKuz/Test_Code | |
57ff677027eec19c0d659e050675e7a320123637 | tests/test_serialize_response.py | tests/test_serialize_response.py | from typing import List
import pytest
from fastapi import FastAPI
from pydantic import BaseModel, ValidationError
from starlette.testclient import TestClient
app = FastAPI()
class Item(BaseModel):
name: str
price: float = None
owner_ids: List[int] = None
@app.get("/items/invalid", response_model=Item)... | Add tests for validation errors in response | :white_check_mark: Add tests for validation errors in response
| Python | mit | tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi | |
6d1ed4bf18ded809371e383e87679ed1b5714699 | pyromancer/test/mock_objects.py | pyromancer/test/mock_objects.py | from pyromancer.objects import Connection
class MockConnection(Connection):
def __init__(self, *args, **kwargs):
self.outbox = []
def write(self, data):
self.outbox.append(data)
| Add mock Connection object for testing purposes. | Add mock Connection object for testing purposes.
| Python | mit | Gwildor/Pyromancer | |
dde87e6b0d2de331e536d335ead00db5d181ee96 | spacy/tests/parser/test_add_label.py | spacy/tests/parser/test_add_label.py | '''Test the ability to add a label to a (potentially trained) parsing model.'''
from __future__ import unicode_literals
import pytest
import numpy.random
from thinc.neural.optimizers import Adam
from thinc.neural.ops import NumpyOps
from ...attrs import NORM
from ...gold import GoldParse
from ...vocab import Vocab
fro... | Add tests for adding parser actions | Add tests for adding parser actions
| Python | mit | recognai/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/s... | |
16a36338fecb21fb3e9e6a15a7af1a438da48c79 | apps/jobs/migrations/0003_jobs_per_page.py | apps/jobs/migrations/0003_jobs_per_page.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('jobs', '0002_auto_20140925_1117'),
]
operations = [
migrations.AddField(
model_name='jobs',
name='pe... | Add missing `per_page` migration file. | Add missing `per_page` migration file.
| Python | mit | onespacemedia/cms-jobs,onespacemedia/cms-jobs | |
6f024ec7fada73388e5a9c1df9446747c8e1e586 | tests/utils/test_http.py | tests/utils/test_http.py | # 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 the Li... | Copy is_safe_url unit test from Django. | Copy is_safe_url unit test from Django.
| Python | apache-2.0 | ismail-s/warehouse,HonzaKral/warehouse,dstufft/warehouse,HonzaKral/warehouse,pypa/warehouse,karan/warehouse,karan/warehouse,dstufft/warehouse,wlonk/warehouse,ismail-s/warehouse,wlonk/warehouse,pypa/warehouse,alex/warehouse,ismail-s/warehouse,chopmann/warehouse,alex/warehouse,karan/warehouse,alex/warehouse,ismail-s/ware... | |
ad6670874f37c52f4a15f30e1ab2682bd81f40f8 | python/helpers/profiler/yappi_profiler.py | python/helpers/profiler/yappi_profiler.py | import yappi
class YappiProfile(object):
""" Wrapper class that represents Yappi profiling backend with API matching
the cProfile.
"""
def __init__(self):
self.stats = None
def runcall(self, func, *args, **kw):
self.enable()
try:
return func(*args, **kw)
... | import yappi
class YappiProfile(object):
""" Wrapper class that represents Yappi profiling backend with API matching
the cProfile.
"""
def __init__(self):
self.stats = None
def runcall(self, func, *args, **kw):
self.enable()
try:
return func(*args, **kw)
... | Fix 2nd and more capturing snapshot (PY-15823). | Fix 2nd and more capturing snapshot (PY-15823).
| Python | apache-2.0 | adedayo/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,da1z/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/i... |
3f9eaa6ed1e69e6d40637ff9711dd72ad1113457 | tmp/test_result_proxy.py | tmp/test_result_proxy.py | #!/usr/bin/env python
from circuits import Component, Event
class Test(Event):
"""Test Event"""
class Foo(Event):
"""Foo Event"""
class Bar(Event):
"""Bar Event"""
class App(Component):
def foo(self):
return 1
def bar(self):
return 2
def test(self):
a = self.fire(... | Test added for testing proof of concept | Test added for testing proof of concept
| Python | mit | eriol/circuits,eriol/circuits,treemo/circuits,eriol/circuits,treemo/circuits,treemo/circuits,nizox/circuits | |
49ed704f02b686888aef81eafb1a3c57910f9d74 | DataWrangling/CaseStudy/sample_file.py | DataWrangling/CaseStudy/sample_file.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow
import os
OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file
SAMPLE_FILE = "sample_sfb.osm"
k = 20 # Parameter: take every k-th top level element
def get_element(osm... | Add a script which split your region in smaller sample | feat: Add a script which split your region in smaller sample
| Python | mit | aguijarro/DataSciencePython | |
38f43f5555a799afbec8adb2fc09e895a3c71637 | strip-html.py | strip-html.py | #!/usr/bin/env python
import re
import srt
import utils
def strip_html_from_subs(subtitles):
for subtitle in subtitles:
subtitle_lines = subtitle.content.splitlines()
stripped_subtitle_lines = (
re.sub('<[^<]+?>', '', line) for line in subtitle_lines
)
subtitle.content... | Add utility to strip HTML | Add utility to strip HTML
| Python | mit | cdown/srt | |
6749e116f47b9307571e016762b3ff918445ba9e | examples/update_status.py | examples/update_status.py | import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# Tweet / Update Status
# The app and the corresponding credentials must have th... | Add Tweet / update status example | Add Tweet / update status example
| Python | mit | tweepy/tweepy,svven/tweepy | |
c6d2a791a9984855dbaad026e741723ad129c137 | gsw/utilities/mat2npz.py | gsw/utilities/mat2npz.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# mat2npz.py
#
# purpose: Convert matlab file from TEOS-10 group to a npz file
# author: Filipe P. A. Fernandes
# e-mail: ocefpaf@gmail
# web: http://ocefpaf.tiddlyspot.com/
# created: 06-Jun-2011
# modified: Wed 02 May 2012 04:29:32 PM EDT
#
# obs:
#
import n... | Convert the data from a Matlab -v6 file to numpy "npz". | Convert the data from a Matlab -v6 file to numpy "npz".
| Python | mit | castelao/python-gsw,lukecampbell/python-gsw,rabernat/python-gsw,TEOS-10/python-gsw,ocefpaf/python-gsw | |
23b80f5a5bd5f418e8da229f39d9912b0b4e8e77 | git-lang-guesser/guesser.py | git-lang-guesser/guesser.py |
import argparse
import http.client
import pprint
from . import exceptions
from . import git_requester
from . import guess_lang
def main():
parser = argparse.ArgumentParser("git-lang-guesser")
parser.add_argument("username")
parser.add_argument("--list-all", action="store_true")
args = parser.parse_... | Add a main function with top-level logic | Add a main function with top-level logic
This is now at the point where I'd give it to a developer for in-house
usage, however before being "done" I need to check the edge cases.
| Python | mit | robbie-c/git-lang-guesser | |
0ea33e658cdbf0605ee4a2f28a1e0cd24a57b608 | examples/ags_rockstar.py | examples/ags_rockstar.py | from rockstar import RockStar
ags_code = "Display("Hello, world!");"
rock_it_bro = RockStar(days=777, file_name='helloworld.asc', code=ags_code)
rock_it_bro.make_me_a_rockstar()
| Add AGS (Adventure Game Studio) example | Add AGS (Adventure Game Studio) example
| Python | mit | yask123/rockstar,varunparkhe/rockstar,monsterwater/rockstar,gokaygurcan/rockstar,haosdent/rockstar,jrajath94/RockStar,ActuallyACat/rockstar,Endika/rockstar,jehb/rockstar,avinassh/rockstar | |
7b527400c162ad6810f938c38e06fdb68e488467 | multiplication_table.py | multiplication_table.py | #! /usr/bin/env python
# multiplication_table.py -- Creates a multiplication table in excel
import sys
import openpyxl
from openpyxl.styles import Font
# A program that takes a number N from the command line
# and creates an NxN multiplication table in an Excel spreadsheet.
try:
usr_input = int(sys.argv[1])
excep... | Create Multiplication table in Excel | Create Multiplication table in Excel
| Python | mit | terrameijar/useful_scripts | |
39147b41147cb4551e60d1356be1795822ae7d72 | migrations/versions/12113d3fcab1_.py | migrations/versions/12113d3fcab1_.py | """empty message
Revision ID: 12113d3fcab1
Revises: 85ee128c8304
Create Date: 2016-05-26 16:35:36.442452
"""
# revision identifiers, used by Alembic.
revision = '12113d3fcab1'
down_revision = '85ee128c8304'
from datetime import datetime
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
... | Upgrade to backfill existing observations with a dummy audit row so we can require audits for all observations. | Upgrade to backfill existing observations with a dummy audit row
so we can require audits for all observations.
| Python | bsd-3-clause | uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal | |
ede47b64d892878e21178aeda2a16f24db59567b | setup.py | setup.py | """Python Bindings for Psynteract.
"""
# This is built on the demo package as described at
# https://packaging.python.org/en/latest/distributing.html
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here ... | Add tentative support for installation via pip | Add tentative support for installation via pip
| Python | apache-2.0 | psynteract/psynteract-py | |
9c762d01b6dafd48d227c0ef927b844a257ff1b9 | joommf/energies/test_demag.py | joommf/energies/test_demag.py | from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_string[0] == 'S'
assert mif_string[-1] == '\n'
assert mif_string... | from demag import Demag
def test_demag_mif():
demag = Demag()
mif_string = demag.get_mif()
assert 'Specify Oxs_Demag {}' in mif_string
assert demag.__repr__() == "This is the energy class of type Demag"
def test_demag_formatting():
demag = Demag()
mif_string = demag.get_mif()
assert mif_s... | Increase test coverage for energy classes | Increase test coverage for energy classes
| Python | bsd-2-clause | ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python |
bd303aa652cd071a612060e7c0e6b0b11dc91018 | php4dvd/test_php4dvd.py | php4dvd/test_php4dvd.py | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import unittest
class TestPhp4dvd(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(10)
self.base_url = "http://hub.wart.ru/... | Add a first test script. | Add a first test script.
| Python | bsd-2-clause | bsamorodov/selenium-py-training-samorodov | |
01428c6eca0351ad6a1767ac39969408c961aec1 | examples/push_tx.py | examples/push_tx.py | from bitcoinrpc.authproxy import AuthServiceProxy
#################################################
# Sending a transation to the network with RPC #
#################################################
# --------------------------------------------------------------------------------------------------------------------... | Add an example to push raw transaction to the network via RPC | Add an example to push raw transaction to the network via RPC
| Python | bsd-3-clause | sr-gi/bitcoin_tools | |
51965dc3b26abfd0f9fb730c3076ee16b13612bc | dadi/__init__.py | dadi/__init__.py | """
For examples of dadi's usage, see the examples directory in the source
distribution.
Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()
import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
impo... | """
For examples of dadi's usage, see the examples directory in the source
distribution.
Documentation of all methods can be found in doc/api/index.html of the source
distribution.
"""
import logging
logging.basicConfig()
import Demographics1D
import Demographics2D
import Inference
import Integration
import Misc
impo... | Hide spurious numpy warnings about divide by zeros and nans. | Hide spurious numpy warnings about divide by zeros and nans.
git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@429 979d6bd5-6d4d-0410-bece-f567c23bd345
| Python | bsd-3-clause | yangjl/dadi,ChenHsiang/dadi,cheese1213/dadi,ChenHsiang/dadi,RyanGutenkunst/dadi,cheese1213/dadi,niuhuifei/dadi,paulirish/dadi,beni55/dadi,yangjl/dadi,RyanGutenkunst/dadi,niuhuifei/dadi,beni55/dadi,paulirish/dadi |
01db1d6f591858b52b6a75ac72b5bdcb49aca708 | python/extract_logs_from_nextflow.py | python/extract_logs_from_nextflow.py | #!/usr/bin/env python
import os
import sys
import pandas as pd
from glob import glob
import subprocess
def main():
if len(sys.argv) != 3:
print("Usage: extract_logs_from_nextflow.py <nextflow_trace_file> <task_tag>:<stderr|stdout|both>",file=sys.stderr)
# Load Nextflow trace
nextflow_trac... | Add script to extract stderr and stout from nextflow | Add script to extract stderr and stout from nextflow
| Python | apache-2.0 | maubarsom/biotico-tools,maubarsom/biotico-tools,maubarsom/biotico-tools,maubarsom/biotico-tools,maubarsom/biotico-tools | |
9be2e5927487dd1400d635d40f85192371a0d1ba | tests/test_eight_schools_large.py | tests/test_eight_schools_large.py | """Test a "large" version of the schools model.
Introduced in response to a macOS bug that only
triggered when a larger number of parameters were used.
"""
import pytest
import stan
program_code = """
data {
int<lower=0> J; // number of schools
real y[J]; // estimated treatment effects
real<low... | Verify a model with many parameters works | test: Verify a model with many parameters works
Check that a schools model with many parameters (160) works. Prompted
by a unusual macOS bug in late 2020 (#163).
| Python | isc | stan-dev/pystan,stan-dev/pystan | |
f5d9ce7ffef618e00252cd65775aef5c42404f8f | DataTag/management/commands/collecttags.py | DataTag/management/commands/collecttags.py | # -*- coding: utf-8 -*-
# vim: set ts=
from __future__ import unicode_literals
from django.conf import settings
from django.core.management.base import BaseCommand
import os
import yaml
class Command(BaseCommand):
args = None
help = 'Collect the tags from the sub-directories'
option_list = BaseCommand.... | Add an helper to collect all tags | Add an helper to collect all tags
This helper will walk on all sub-directories to find the tags that are missing
in the root configuration.
| Python | agpl-3.0 | ivoire/DataTag,ivoire/DataTag,ivoire/DataTag | |
4493b6d42d025ac79f6e89c40ed3b583802a2330 | 2048/test_value_2048.py | 2048/test_value_2048.py | from __future__ import print_function
import numpy as np
import math
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential, model_from_json
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, ... | Test Keras DNN for 2048 value | Test Keras DNN for 2048 value
| Python | mit | choupi/NDHUDLWorkshop | |
fbd49abfb5a3d32f30de0e85c70f08c873813755 | cpro/migrations/0014_auto_20170129_2236.py | cpro/migrations/0014_auto_20170129_2236.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import cpro.models
class Migration(migrations.Migration):
dependencies = [
('cpro', '0013_auto_20161025_0249'),
]
operations = [
migrations.AddField(
model_name='card',
... | Store HD version of the art images (made with waifux2 by @meiponnyan on Twitter), use it when it exists on the homepage and when using the download link | Store HD version of the art images (made with waifux2 by @meiponnyan on Twitter), use it when it exists on the homepage and when using the download link
| Python | apache-2.0 | SchoolIdolTomodachi/CinderellaProducers,SchoolIdolTomodachi/CinderellaProducers | |
d1e1e682122a66e76c70052a5fec3e6d9a00ab46 | babel_util/scripts/log_to_json.py | babel_util/scripts/log_to_json.py | import json
from parsers.infomap_log import InfomapLog
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates JSON file from Infomap Logs")
parser.add_argument('outfile')
parser.add_argument('infiles', nargs='+')
args = parser.parse_args()
logs = []
... | Convert infomap logs to JSON | Convert infomap logs to JSON
| Python | agpl-3.0 | jevinw/rec_utilities,jevinw/rec_utilities | |
22c96540eb5cbf33d9ea868458769031dc57102a | lib/logSupport.py | lib/logSupport.py | #
# Description: log support module
#
# Author:
# Igor Sfiligoi (Oct 25th 2006)
#
import time
# this class can be used instead of a file for writing
class DayLogFile:
def __init__(self,base_fname):
self.base_fname=base_fname
return
def close(self):
return # nothing to do, just a place... | Support library for managing log files | Support library for managing log files
| Python | bsd-3-clause | holzman/glideinwms-old,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS | |
70fa6d750fbbdae405b0012b9aa53f066008ba5f | setup.py | setup.py | # coding=utf-8
from setuptools import setup, find_packages
setup(
name="tinydb",
version="2.1.0",
packages=find_packages(),
# development metadata
zip_safe=True,
# metadata for upload to PyPI
author="Markus Siemens",
author_email="markus@m-siemens.de",
description="TinyDB is a tin... | # coding=utf-8
from setuptools import setup, find_packages
from codecs import open
setup(
name="tinydb",
version="2.1.0",
packages=find_packages(),
# development metadata
zip_safe=True,
# metadata for upload to PyPI
author="Markus Siemens",
author_email="markus@m-siemens.de",
desc... | Fix decode error of README.rst during installation | Fix decode error of README.rst during installation
| Python | mit | ivankravets/tinydb,Callwoola/tinydb,raquel-ucl/tinydb,cagnosolutions/tinydb,msiemens/tinydb |
8c2aa6409358b4b5830e9a6242194030307f2aa6 | makemigrations.py | makemigrations.py | #!/usr/bin/env python
import decimal
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
DEBUG=True,
USE_TZ=True,
TIME_ZONE='UTC',
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MIDDLEWARE_CLASSES=[
... | Add a helper script for creating migrations | Add a helper script for creating migrations
| Python | mit | pinax/django-stripe-payments | |
3dce48f228caec9b317f263af3c5e7a71372f0be | project/members/tests/test_application.py | project/members/tests/test_application.py | # -*- coding: utf-8 -*-
import pytest
from members.tests.fixtures.memberlikes import MembershipApplicationFactory
from members.tests.fixtures.types import MemberTypeFactory
from members.models import Member
@pytest.mark.django_db
def test_application_approve():
mtypes = [MemberTypeFactory(label='Normal member')]
... | # -*- coding: utf-8 -*-
import pytest
from django.core.urlresolvers import reverse
from members.tests.fixtures.memberlikes import MembershipApplicationFactory
from members.tests.fixtures.types import MemberTypeFactory
from members.models import Member
@pytest.mark.django_db
def test_application_approve():
mtypes =... | Test that we can get the application form | Test that we can get the application form
| Python | mit | hacklab-fi/asylum,HelsinkiHacklab/asylum,rambo/asylum,jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,rambo/asylum,rambo/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,jautero/asylum,jautero/asylum,HelsinkiHacklab/asylum |
a094b0978034869a32be1c541a4d396843819cfe | project/management/commands/generatesecretkey.py | project/management/commands/generatesecretkey.py | from django.core.management.templates import BaseCommand
from django.utils.crypto import get_random_string
import fileinput
from django.conf import settings
class Command(BaseCommand):
help = ("Replaces the SECRET_KEY VALUE in settings.py with a new one.")
def handle(self, *args, **options):
# Crea... | Add management command to generate a random secret key | Add management command to generate a random secret key
| Python | mit | Angoreher/xcero,Angoreher/xcero,Angoreher/xcero,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,Angoreher/xcero,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3 | |
7941202bf8c7f3c553e768405b72b0b5b499dee6 | tfidf.py | tfidf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import nlp.tokenizer
import nlp.TextVectorizer
import sys
data = []
filenames = sys.argv[1:]
for filename in filenames:
t = open(filename).read().decode('utf-8')
data.append(t)
data = "\n".join(data)
print 'word,count'
v = nlp.TextVectorizer.TfVectorizer(tokeniz... | Change output format to csv | Change output format to csv
| Python | mit | otknoy/ExTAT,otknoy/ExTAT | |
067fa81cf56b7f8ab29060ec8a1409c0c07c797e | greedy/Job_sequencing_problem/python/jobsequencing.py | greedy/Job_sequencing_problem/python/jobsequencing.py | class Job:
def __init__(self, name, deadline, duration, profit):
self.name = name
self.deadline = deadline
self.duration = duration
self.profit = profit
def __lt__(self, other):
return self.profit < other.profit
def __str__(self):
return self.name
# Greedy ... | Add job sequencing greedy Python | Add job sequencing greedy Python
| Python | cc0-1.0 | ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovs... | |
f4b5dafbb9a1a9af00b8981dbb442fa8f8385203 | pupa/migrations/0002_auto_20150906_1458.py | pupa/migrations/0002_auto_20150906_1458.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.dev20150906080247 on 2015-09-06 14:58
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pupa', '0001_initial'),
]
operation... | Revert "Revert "add migration for new fields"" | Revert "Revert "add migration for new fields""
This reverts commit 31b01725ae23624358c7da819a6c6e4c9a41b0c4.
| Python | bsd-3-clause | datamade/pupa,mileswwatkins/pupa,opencivicdata/pupa,datamade/pupa,mileswwatkins/pupa,opencivicdata/pupa | |
587011702ffca5d02263736dcae04f31ce8c38d4 | test/models/test_output_type.py | test/models/test_output_type.py | from test.base import ApiDBTestCase
from zou.app.models.output_type import OutputType
from zou.app.utils import fields
class OutputTypeTestCase(ApiDBTestCase):
def setUp(self):
super(OutputTypeTestCase, self).setUp()
self.generate_data(OutputType, 3)
def test_get_output_types(self):
... | Add tests for output type crud routes | Add tests for output type crud routes
| Python | agpl-3.0 | cgwire/zou | |
4aef9a5bca4927db0ff7b661850de1c8d3c61274 | seqseek/format_fasta.py | seqseek/format_fasta.py | import argparse
def run(path):
print "Formatting %s" % path
with open(path) as fasta:
header = ''
first_line = fasta.readline()
if not first_line.startswith('>'):
header = '> ' + path.split('/')[-1].split('.')[0] + '\n'
first_line.replace('\n', '')
clean... | Add utility for formatting fasta files for seqseek | Add utility for formatting fasta files for seqseek
| Python | mit | 23andMe/seqseek | |
531d1c868b36580a8423d71c3ee324c8669ab98b | pycelle/misc.py | pycelle/misc.py | from __future__ import division
from math import ceil, log
__all__ = [
'base_expansion',
]
def base_expansion(n, to_base, from_base=10, zfill=None):
"""
Converts the number `n` from base `from_base` to base `to_base`.
Parameters
----------
n : list | int
The number to convert. If an ... | Add function to convert between number bases. | Add function to convert between number bases.
| Python | bsd-3-clause | ComSciCtr/pycelle | |
628c092b2fd8b53e116e04b240f04b7508ab6118 | enthought/traits/ui/wx/array_view_editor.py | enthought/traits/ui/wx/array_view_editor.py | #-------------------------------------------------------------------------------
# Imports:
#-------------------------------------------------------------------------------
from enthought.traits.ui.ui_editors.array_view_editor \
import _ArrayViewEditor as BaseArrayViewEditor
from ui_editor \
import UIEditor
... | Add wx implementation of the ArrayViewEditor. | Add wx implementation of the ArrayViewEditor.
| Python | bsd-3-clause | geggo/pyface,brett-patterson/pyface,geggo/pyface,pankajp/pyface | |
cf160d8259fb98ef4003283063529be8c4c087fb | python/helpers/pycharm_generator_utils/test/data/SkeletonCaching/binaries/compile_binaries.py | python/helpers/pycharm_generator_utils/test/data/SkeletonCaching/binaries/compile_binaries.py | import os
from Cython.Build.Cythonize import main as cythonize
_binaries_dir = os.path.dirname(os.path.abspath(__file__))
_cythonize_options = ['--inplace']
def main():
for dir_path, _, file_names in os.walk(_binaries_dir):
for file_name in file_names:
mod_name, ext = os.path.splitext(file_n... | Add a script to compile all binary modules in test data directory | Add a script to compile all binary modules in test data directory
GitOrigin-RevId: b4da703157f1397dac2760ca844d43143bae5cdc
| Python | apache-2.0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.