code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
import json
import logging
import requests
from requests.exceptions import ConnectionError, HTTPError
from .errors import RequestError, NotFoundError
from .services import (CustomerService, InvoiceService, DraftService,
TaxService)
logger = logging.getLogger('pydebitoor... | idlead/pydebitoor | pydebitoor/client.py | Python | mit | 7,309 |
"""
Connection utilities
"""
import paramiko
import os
import logging
from teuthology.config import config
from teuthology.contextutil import safe_while
from paramiko.hostkeys import HostKeyEntry
log = logging.getLogger(__name__)
def split_user(user_at_host):
"""
break apart user@host fields into user and h... | dmick/teuthology | teuthology/orchestra/connection.py | Python | mit | 3,430 |
from __future__ import print_function, unicode_literals
import site,os
home_dir=os.getenv('HOME')
site.addsitedir('{}/repos/pythonlibs'.format(home_dir))
from pyutils.compat import PY2
from dateutil.parser import parse
import time
import datetime, pytz
from math import floor
def build_rfc3339_phrase(datetime_obj):
... | phaustin/timetable | test_timestamp.py | Python | mit | 3,015 |
def test_default_log(creplay, testlog):
ret = creplay('echo', 'foo', creplay_args=[], cwd=testlog.dirname)
assert ret.success
assert ret.stdout == 'foo\n'
assert ret.stderr == ''
def test_echo_n(creplay, logfile):
ret = creplay('echo', '-n', 'foo')
assert ret.success
assert ret.stdout == '... | kvas-it/cli-mock | tests/test_creplay.py | Python | mit | 1,051 |
# coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class... | Telestream/telestream-cloud-python-sdk | telestream_cloud_qc_sdk/telestream_cloud_qc/models/black_frame_test.py | Python | mit | 24,026 |
#!/usr/bin/env python3
# Copyright (c) 2017-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test HD Wallet keypool restore function.
Two nodes. Node1 is under test. Node0 is providing transactio... | syscoin/syscoin | test/functional/wallet_keypool_topup.py | Python | mit | 4,455 |
import os
import json
import logging
from framework._utils import FunctionHook
class GitHubExtractCompatibility(FunctionHook):
''' test compatibility over language versions. '''
@staticmethod
def handle_python(directory):
''' returns number of Python files in a repository that is syntactic
... | neizod/coding-analysis | framework/github/extract/compatibility.py | Python | mit | 4,835 |
"""empty message
Revision ID: 37s5rj356547
Revises: j4d9g3scvf4s
Create Date: 2019-02-20 16:45:34.186981
"""
# revision identifiers, used by Alembic.
revision = '37s5rj356547'
down_revision = 'j4d9g3scvf4s'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... | CSC-IT-Center-for-Science/pouta-blueprints | migrations/versions/37s5rj356547_.py | Python | mit | 611 |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... | tysonholub/twilio-python | twilio/rest/serverless/v1/service/environment/deployment.py | Python | mit | 15,554 |
from ClashOfClansBot.Interfaces.BotAPI import ITask
class TrainTroopsTask(ITask):
def __init__(self, **troops):
pass
| DavidBarishev/ClashOfClansBot | ClashOfClansBot/Plugins/Tasks/TrainTroops/_TrainTroopsTask.py | Python | mit | 131 |
from __future__ import print_function
from __future__ import division
from builtins import range
from past.utils import old_div
from proteus import Comm, Profiling
import numpy as np
import numpy.testing as npt
import unittest
import random
from math import cos,sin,cosh,sinh,pi,tanh,log,atan2,asin,acos,radians
import s... | erdc/proteus | proteus/tests/test_bodydynamics.py | Python | mit | 32,368 |
#!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoi... | cuio/MyElysiumCoin | contrib/spendfrom/spendfrom.py | Python | mit | 10,321 |
#from bs4 import BeautifulSoup
from pprint import pprint
from bs4 import BeautifulSoup
import requests
import urllib2
import re
'''
info = 'http://codeforces.com/api/user.status?handle=tacklemore&from=1&count=1'
solution = 'view-source:http://codeforces.com/contest/686/submission/18671530'
do not include problems wi... | ethancaballero/neural-engineers-first-attempt | scrapers/codeforces/codeforces_get_list_and_tags.py | Python | mit | 1,818 |
from pip.req import parse_requirements as pip_parse_requirements
from pip.req import InstallRequirement
def is_pypi_requirement(requirement):
return requirement.req and not requirement.link
def parse_requirements(path_to_requirements):
""" Parse requirements
:param path_to_requirements: path/to/require... | 5monkeys/reqlice | reqlice/requirement.py | Python | mit | 926 |
#!/usr/bin/python
import os, re,sys
from remote_exe import create_thread
from subprocess import Popen, PIPE
from main import base_fun
fio_cmd = "fio --name=global --ioengine=sync --bs=4k --rw=read --filename=/dev/{0} --runtime={1} --direct=1 -numjobs=1 -iodepth=4 --name=job"
stress_time = 60
class FIO_FUN(base_fun... | trelay/multi-executor | main/main_fio.py | Python | mit | 1,282 |
# coding: utf-8
# Author: Vova Zaytsev <zaytsev@usc.edu>
import os
import json
def project_dir(dir_name):
return os.path.join(os.path.dirname(__file__), "..", dir_name)\
.replace("\\", "//")
# with open(project_dir("conf/dev.json"), "rb") as fp:
# CONF = json.load(fp)
SECRET_KEY = "h8(e(u3#k)l802(... | LucidAi/nlcd | nlcd/local.py | Python | mit | 2,115 |
# -*- coding: utf-8 -*-
# DO NOT DELETE
import StringIO
import csv
import datetime
today = datetime.date.today()
from flask import (
Blueprint,
make_response
)
from flask.ext.login import login_required
from sqlalchemy import desc
from feedback.surveys.models import Survey
blueprint = Blueprint(
'sur... | codeforamerica/mdc-feedback | feedback/surveys/views.py | Python | mit | 1,698 |
import logging
from logging import FileHandler
import psycopg2
import sqlalchemy
from sqlalchemy_utils import database_exists, create_database
from mongoengine import *
from flask import Flask
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from .config import test_config
from .config import app... | testlnord/entity_matching_tool | entity_matching_tool/__init__.py | Python | mit | 2,695 |
# coding: utf-8
from rest_framework import generics
from rest_framework import filters
from employee.models import Operator
from employee.serializers import EmployeeDetailSerializer
class IsOwnerFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.f... | lbjworld/article-search | article-manager/site/employee/views.py | Python | mit | 526 |
import pandas as pd
import numpy as np
from six import iteritems
from scipy import stats
#from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import \
RandomForestRegressor, \
ExtraTreesRegressor, \
GradientBoostingRegr... | maxisacson/sml-project | Henrik_Project/ensemble_methods.py | Python | mit | 11,726 |
import logging
import discord
from discord.abc import PrivateChannel
from cogs.cog import Cog
from utils.utilities import (split_string, format_on_delete, format_on_edit,
format_join_leave, get_avatar,
get_image_from_embeds,
is_ima... | s0hvaperuna/Not-a-bot | cogs/logging.py | Python | mit | 9,606 |
#!/usr/bin/env python
import sys
import re
import subprocess
import os
import optparse
import datetime
import inspect
import threading
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesImpl
VERSION = '1.0.0'
ALL_TESTS = []
LOGFILE = None
CURRENT_SUITE = 'default'
DEFAULT_TEST_TIMEOUT = ... | noselasd/testrunner | testrunner.py | Python | mit | 21,002 |
import _plotly_utils.basevalidators
class TexttemplateValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="texttemplate", parent_name="scattermapbox", **kwargs
):
super(TexttemplateValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/scattermapbox/_texttemplate.py | Python | mit | 527 |
# File = Lab3.py
# Programmer = Keith Murphy
# date created = 2-5-2015
# date Modified = 2-9-2015
__author__ = 'pather'
# Hello Mark,
# This is my first a stab at the Lab3 assignment. Everything tested well logically ans tried to fallow pseudocode
# specs closely. Let me know if I can make any improvements. Thanks... | nomad-mystic/nomadmystic | fileSystem/school-projects/development/softwaredesignandcomputerlogiccis122/cis122lab3/python/Lab3.py | Python | mit | 18,030 |
# -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
from cdo import Cdo
from pycmbs.data import Data
import tempfile as tempfile
import copy
import glob
import os
import sys
import ast
import numpy as np
from pycmbs.be... | pygeo/pycmbs | pycmbs/benchmarking/models/cmip5.py | Python | mit | 20,505 |
from __future__ import absolute_import
from proteus import *
try:
from .twp_navier_stokes_p import *
from .risingBubble import *
except:
from twp_navier_stokes_p import *
from risingBubble import *
if timeDiscretization=='vbdf':
timeIntegration = VBDF
timeOrder=2
stepController = Min_dt_cfl... | erdc/proteus | proteus/tests/surface_tension/rising_bubble_rans3p/twp_navier_stokes_n.py | Python | mit | 1,998 |
import logging
import os
import re
from datetime import datetime
from typing import Tuple, Optional, List, Dict, Union, Any
from urllib.error import URLError
from bs4 import BeautifulSoup
from bs4.element import Tag
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.we... | vapkarian/soccer-analyzer | src/parsers/flashscore.py | Python | mit | 30,552 |
from django.test import TestCase
from fixtureless import Factory
from owc_fixtureless import constants
from owc_fixtureless import models
class MageTestCase(TestCase):
def setUp(self):
self.factory = Factory()
def test_brothers_in_arms(self):
# Exclude the mage itself
mage_1 = self.f... | ricomoss/open-west-2015-fixtureless | owc_fixtureless/owc_fixtureless/tests.py | Python | mit | 927 |
"""
python script that generates mesh for Howorka geometry
"""
import numpy
from importlib import import_module
import nanopores.py4gmsh.basic
import nanopores.py4gmsh.extra
from nanopores.py4gmsh import *
from warnings import warn
import os
from nanopores import INSTALLDIR
def get_geo(**params):
"""
writes a... | mitschabaude/nanopores | nanopores/geometries/P_geo/py4geo.py | Python | mit | 1,164 |
# coding=utf8
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import os
from os.path import join
import tempfile
import shutil
from six.moves import configparser
import pytest
from tests import setenv, test_doc0
f... | eukaryote/knowhow | tests/conftest.py | Python | mit | 1,892 |
# -*- coding: utf-8 -*-
#
# Thumbor documentation build configuration file, created by
# sphinx-quickstart on Mon Sep 1 13:18:38 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | thumbor-community/shortener | docs/conf.py | Python | mit | 8,491 |
from pymongo import MongoClient
from elasticsearch import Elasticsearch
client = MongoClient()
db = client.wp
posts = db.posts.find({})
es = Elasticsearch()
es.indices.delete(index='wp-posts', ignore=[400, 404])
es.indices.create(
index='wp-posts',
body={
'settings': {
# just one shard, n... | noppanit/wp-downloader | dump_to_es.py | Python | mit | 1,435 |
from setmagic.models import Setting
from .exceptions import NoSuchSettingError
class SettingsBackend(object):
'''
A structure to organize the settings scheme and provide a simple API for
easier access to all registered settings.
'''
settings = property(lambda self: self._settings)
def __ini... | 7ws/django-setmagic | setmagic/backend.py | Python | mit | 1,189 |
from axiom.test.historic.stubloader import saveStub
from axiom.dependency import installOn
from xmantissa.people import Organizer
def createDatabase(s):
installOn(Organizer(store=s), s)
if __name__ == '__main__':
saveStub(createDatabase, 13142)
| twisted/mantissa | xmantissa/test/historic/stub_organizer2to3.py | Python | mit | 258 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''Hacky way to make sure imports work'''
from os.path import abspath, dirname, realpath, join
import sys
# This allows imports to work, even if sim_game is not in python path:
package_location = abspath(join(dirname(realpath(__file__)) , ".."))
sys.path.insert(0, package... | olehermanse/sim_game | tests/path_fix.py | Python | mit | 331 |
# -*- test-case-name: axiom.test.test_batch -*-
"""
Utilities for performing repetitive tasks over potentially large sets
of data over an extended period of time.
"""
import weakref, datetime, os, sys
from zope.interface import implements
from twisted.python import reflect, failure, log, procutils, util, runtime
fr... | hawkowl/axiom | axiom/batch.py | Python | mit | 40,033 |
import urllib
from flask import url_for
from flask_script import Manager, Server, Shell, Command
from config.app import create_app
from config.db import db
from config.initializers.newrelic_monitoring import NewrelicMonitoring
from federation_api.people.model import Person
manager = Manager(create_app)
server = Serve... | practo/federation | manage.py | Python | mit | 1,415 |
# -*- coding: utf-8 -*-
# pylint: disable=too-many-locals,too-many-statements
from __future__ import division
import pytest
from ethereum import slogging
from raiden.channel import (
BalanceProof,
Channel,
ChannelEndState,
ChannelExternalState,
)
from raiden.exceptions import (
InsufficientBalance... | tomashaber/raiden | raiden/tests/unit/test_channel.py | Python | mit | 32,853 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import codecs
import os
import sys
sys.path.append(os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, 'DropPy.Common')))
from file_tools import get_file_paths_from_directory
class Task(object):
"""
Documentation: htt... | geberl/droppy-workspace | Tasks/Text.RemoveMultiNewlines/task.py | Python | mit | 2,087 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0016_hello'),
]
operations = [
migrations.AddField(
model_name='hello',
name='done',
... | acreations/rockit-server | rockit/core/migrations/0017_hello_done.py | Python | mit | 419 |
#!/usr/bin/env python
"""
crossref-client.py - Implement a tool for interaction with the api.crossref.org
Usage:
crossref-client.py -h | --help
crossref-client.py [-c]
Options:
-h --help Show the help message
-c --count-publishers Display the number of publishers available
... | indera/crossref-client | crossref-client.py | Python | mit | 1,731 |
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission, Group
from django.contrib.sites.models import Site
from django.db.models.signals import post_save, post_migrate
from django.core.exceptions import ObjectDoesNotExist
from main.models import SiteSettings, UserP... | mattr555/AtYourService-school | main/__init__.py | Python | mit | 1,906 |
import shopify
from test.test_helper import TestCase
class EventTest(TestCase):
def test_prefix_uses_resource(self):
prefix = shopify.Event._prefix(options={"resource": "orders", "resource_id": 42})
self.assertEqual("https://this-is-my-test-show.myshopify.com/admin/api/unstable/orders/42", prefix)... | Shopify/shopify_python_api | test/event_test.py | Python | mit | 509 |
'''
Created on Jul 26, 2014
@author: lwoydziak
'''
from mockito.mocking import mock
from pertinosdk import PertinoSdk, QueryBuilder, where
from mockito.mockito import when, verify
from mockito.matchers import any, Matcher
class Contains(Matcher):
def __init__(self, sub):
self.sub = sub
def ma... | Pertino/pertino-sdk-python | pertinosdk/tests/pertinosdk_test.py | Python | mit | 3,217 |
from units import runner
import numpy as np
def job_gen():
for N in range(4, 21, 2):
for rate_power in [1, 3/2.]:
rate = np.power(N, rate_power)
test = {
'test': {},
'net': {'topology': 'grid', 'N': N},
'pattern': {'type': 'random_one... | efectivo/network_sim | grid1_basic.py | Python | mit | 755 |
"""Timeouts using with statement"""
from signal import alarm, signal, SIGALRM
from time import time
import sys
class TimeoutError(Exception):
"""A function timed out"""
def alarm_handler(*_):
"""Trigger any alarms due"""
first = None
for tstamp in sorted(sys.deadlines.keys()):
if tstamp > time... | dickon/sshrun | sshrun/time_limit.py | Python | mit | 2,228 |
# Copyright (c) 2011 by Joshua Hoak, Alissa Pajer
# Licensed under the MIT License
# Authors: Josh Hoak (jrhoak@gmail.com)
import properties
class Parser(object):
def __init__(self, parse_type, options):
self.parse_type = parse_type
self.options = options
self.css_class = options.TAGS_CLASS
def pa... | Kashomon/pyrite | pyrite/data_structures/tags_prop.py | Python | mit | 906 |
# -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.domain.payment.definitions.order_output import OrderOutput
from ingenico.connect.sdk.domain.payment.definitions.refund_bank_method_specific_out... | Ingenico-ePayments/connect-sdk-python3 | ingenico/connect/sdk/domain/payment/definitions/refund_output.py | Python | mit | 9,736 |
# coding=utf-8
from django.conf.urls import url
from .views import (
AliTemplateView,
AliVideoconferenciasDetailView,
AreaDetailView,
AulaDetailView,
CuerpoDetailView,
IndexView,
LaboratorioDetailView,
LaboratorioInformaticoDetailView,
LaboratorioInformaticoListView,
NivelDetai... | utn-frm-si/reservas | app_reservas/urls.py | Python | mit | 4,160 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: diplomacy_tensorflow/contrib/tpu/proto/topology.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from goo... | diplomacy/research | diplomacy_research/proto/diplomacy_tensorflow/contrib/tpu/proto/topology_pb2.py | Python | mit | 3,566 |
#!/usr/bin/env python
#
# Copyright (c) 2009, Roboterclub Aachen e.V.
# 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 source code must retain the above copyright
# ... | jrahlf/3D-Non-Contact-Laser-Profilometer | xpcc/scons/site_tools/hosted.py | Python | mit | 2,890 |
from datetime import datetime
import glob
import markdown
import os
import re
from flask import Flask, render_template, abort, send_from_directory
from flask_frozen import Freezer
from flask_flatpages import FlatPages, pygments_style_defs
from werkzeug.contrib.atom import AtomFeed
from config import *
from utils impo... | bmbove/flask-static-homepage | app.py | Python | mit | 4,066 |
import Linked_List
import sys
import random
def split_list(lst, a, b):
if lst.length % 2 == 1:
first_length = (lst.length / 2) + 1
else:
first_length = lst.length / 2
list_iterator = lst.head
count = 0
while count < first_length:
a.append(list_iterator.data)
list_i... | afaquejam/Linked-List-Problems | Others/FrontBackSplit.py | Python | mit | 1,330 |
# _V!(3, 3)
# This file was automatically generated by `dump_dis.py`.
# This file is designed for Python (3, 3).
import sys
# Check Python version
if sys.version_info[0:2] != (3, 3):
raise SystemError("Inappropriate Python version for these bytecode symbols.")
# Begin tokens. These are ordered.
POP_TOP = 1
ROT_T... | SunDwarf/Pyte | pyte/tokens_33.py | Python | mit | 2,143 |
"""Streamis - Subscribe to Redis pubsub channels via HTTP and EventSource."""
import logging
import asyncio
from asyncio import Queue
import aioredis
from tornado.platform.asyncio import AsyncIOMainLoop
from tornado import web
from tornado.iostream import StreamClosedError
from tornado.options import options, define... | mivade/streamis | streamis.py | Python | mit | 4,156 |
import sys
import re
import numpy as np
import json
import pickle
from string import ascii_letters
from keras.models import Sequential, model_from_json
from keras.layers import Dense, Activation, Dropout
from keras.layers import LSTM
from ivanatrumpalot import clean_text, predict, sample
# This code is heavily infl... | QCaudron/ivanatrumpalot | code/train_lstm.py | Python | mit | 5,169 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Meta level spider components. Each communicates with one or more servers via
sub-components.
"""
from .pagegetter import PageGetter
from .worker import Worker
from .interface import Interface
from .jobgetter import JobGetter
from .jobscheduler import JobScheduler
from... | hiidef/hiispider | hiispider/metacomponents/__init__.py | Python | mit | 805 |
# -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem415.py
#
# Titanic sets
# ============
# Published on Sunday, 17th February 2013, 10:00 am
#
# A set of lattice points S is called a titanic set if there exists a line
# passing through exactly two points in S. An example of a titanic set is S =
# {(0, 0), (0, 1... | olduvaihand/ProjectEuler | src/python/problem415.py | Python | mit | 990 |
"""Tests for the PVOutput integration."""
from unittest.mock import MagicMock
from pvo import (
PVOutputAuthenticationError,
PVOutputConnectionError,
PVOutputNoDataError,
)
import pytest
from homeassistant.components.pvoutput.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, Conf... | rohitranjan1991/home-assistant | tests/components/pvoutput/test_init.py | Python | mit | 2,660 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append('/Users/pybae/etc/Project Euler/')
import general
array = general.prime(200000)
print array[10000]
| pybae/etc | Project Euler/1-9/python/problem7.py | Python | mit | 175 |
from __future__ import absolute_import
import redisext.backend.abc
import rm.rmredis
class Client(redisext.backend.abc.IClient):
def __init__(self, database=None, role=None):
self._redis = rm.rmredis.RmRedis.get_instance(database, role)
class Connection(redisext.backend.abc.IConnection):
CLIENT = C... | mylokin/redisext | redisext/backend/rmredis.py | Python | mit | 326 |
# -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | ryanss/holidays.py | holidays/countries/australia.py | Python | mit | 9,872 |
# _*_ encoding: utf-8 _*_
"""Demonstrate doubly-linked list in python."""
from linked_list import Node
class DoublyLinked(object):
"""Implement a doubly-linked list from a singly-linked list."""
def __init__(self, val=None):
"""Initialize the list."""
self.head = object()
self._mark =... | palindromed/data-structures2 | src/doubly_linked.py | Python | mit | 4,501 |
# -*- coding: utf-8 -*-
"""
Module to handle getting data loading classes and helper functions.
"""
import json
import io
import torch
import numpy as np
from collections import Counter, defaultdict
from torch.utils.data import Dataset
from . import constants as Constants
from .timer import Timer
##################... | stanfordnlp/coqa-baselines | rc/utils/data_utils.py | Python | mit | 10,586 |
import aioredis
import asyncio
from unittest import TestCase
class BaseTestCase(TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
db_co = aioredis.create_redis(
address=('localhost', 6379),
db=13,
loop=self.loo... | paxos-bankchain/subconscious | tests/base.py | Python | mit | 634 |
import math
def sieve(limit):
primes_set = set()
primes = [True] * limit
primes[0] = primes[1] = False
for (i, is_prime) in enumerate(primes):
if is_prime:
primes_set.add(i)
for n in xrange(i*i, limit, i):
primes[n] = False
return primes_set
def P035():
limit = 1000000
prime_se... | brendanzhao/ProjectEuler | src/P035.py | Python | mit | 719 |
"""
This module provides utility functions for the SaltyRTC Signalling
Server.
"""
# noinspection PyUnresolvedReferences
from typing import Coroutine # noqa
from typing import (
Any,
Awaitable,
Callable,
List,
Mapping,
Optional,
TypeVar,
cast,
)
import asyncio
import binascii
import li... | saltyrtc/saltyrtc-server-python | saltyrtc/server/util.py | Python | mit | 11,300 |
#!/usr/bin/env python3
import argparse
from biocode import utils, gff
def main():
'''
This script reports statistics on the areas of a genome where features aren't - introns and
intergenic space. Pass a valid GFF3 file (along with FASTA data) and get a report like this:
Molecule count: 9
Gene... | jorvis/biocode | gff/report_gff_intron_and_intergenic_stats.py | Python | mit | 9,713 |
import sys
import os
from setuptools import setup, find_packages
from rest_framework_gis import get_version
def get_install_requires():
"""
parse requirements.txt, ignore links, exclude comments
"""
requirements = []
for line in open('requirements.txt').readlines():
# skip to next iteratio... | pglotov/django-rest-framework-gis | setup.py | Python | mit | 2,039 |
from rest_framework import serializers
from collectors.models import Day
class DaySerializer(serializers.ModelSerializer):
class Meta:
model = Day
fields = ('result',)
| andyzinsser/good-day | collectors/serializers.py | Python | mit | 190 |
"""Tests for the sop_class module."""
import pytest
from pydicom._uid_dict import UID_dictionary
from pynetdicom.sop_class import (
uid_to_sop_class,
uid_to_service_class,
SOPClass,
_SERVICE_CLASSES,
_APPLICATION_EVENT_CLASSES,
ProceduralEventLoggingSOPClass,
_BASIC_WORKLIST_CLASSES,
... | scaramallion/pynetdicom3 | pynetdicom/tests/test_sop.py | Python | mit | 18,339 |
import requests
import xmltodict
import json
class GoodreadsRequestException(Exception):
def __init__(self, error_msg, url):
self.error_msg = error_msg
self.url = url
def __str__(self):
return self.url, ':', self.error_msg
class GoodreadsRequest():
def __init__(self, client, pat... | TEJESH/gandhi | goodreads/request.py | Python | mit | 1,054 |
# -*- coding: utf-8 -*-
import logging
from django.core.urlresolvers import reverse
from django.http.response import Http404, JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from photos.gallery.seri... | relekang/photos | photos/gallery/views.py | Python | mit | 2,650 |
"""
Udacity CS253 - Lesson 5 - Homework 1
"""
import webapp2, handlers
app = webapp2.WSGIApplication([
('/', handlers.HomePage),
('/newpost', handlers.NewPostPage),
('/signup', handlers.SignupPage),
('/login', handlers.LoginPage),
('/logout', handlers.LogoutPage),
('/welcome', handlers.WelcomePage),
('... | vcelis/cs253 | lesson5/homework1/blog.py | Python | mit | 438 |
"""tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | okin006/tracker | tracker/urls.py | Python | mit | 811 |
import unittest
from flask import current_app
from app import create_app, db
class BasicsTestCase(unittest.TestCase):
# Runs before each test
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
... | bitmotive/flask-boilerplate | tests/test_basics.py | Python | mit | 705 |
#!/usr/bin/env python
import os.path
import sys
MODULE_ROOT = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, MODULE_ROOT)
from to_battle.player import Hero, Villain
from to_battle.battle import Battle
if __name__ == '__main__':
player1 = Hero(name='Rico')
player2 = Villain(name='Thanos')
... | ricomoss/python-april-2014 | class7/to_battle/script.py | Python | mit | 380 |
#!/usr/bin/python
# coding: utf-8
"""
The MIT License (MIT)
Copyright (c) 2013 Fatih Karatana
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... | fatihzkaratana/cluster-organizer | __init__.py | Python | mit | 1,472 |
#!/usr/bin/python
#======================================================================
#
# Project : hpp_IOStressTest
# File : Libs/IOST_WMain/IOST_WMainSATA.py
# Date : Oct 20, 2016
# Author : HuuHoang Nguyen
# Contact : hhnguyen@apm.com
# : hoangnh.hpp@gmail.com
# License : MIT License
# Copy... | HPPTECH/hpp_IOSTressTest | Refer/IOST_OLD_SRC/IOST_0.20/Libs/IOST_WMain/IOST_WMain_SATA.py | Python | mit | 7,573 |
'''
Convert a mod format to a tabix accessible format.
Created on Oct 30, 2012
@author: Shunping Huang
'''
import logging
import gzip
import tempfile
import pysam
__all__ = ['getTabixMod']
def getTabixMod(filename):
'''Unzip a mod file, use bgzip to rezip it, and and build tabix index.'''
logger = loggin... | andrewparkermorgan/lapels | modtools/tmpmod.py | Python | mit | 836 |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(len(board)):
sudoku = {}
for j in range(len(board[i])):
if board[i][j] in sudoku:
return False... | FeiZhan/Algo-Collection | answers/leetcode/Valid Sudoku/Valid Sudoku.py | Python | mit | 1,115 |
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import View
# model
#from drawroute.models import *
# Create your views here.
class MapHandler(View):
'''This class manages the map where lines are drawn '''
def __init__(self):
self.context={}
def get(s... | SmartcitySantiagoChile/onlineGPS | drawroute/views.py | Python | mit | 422 |
import bleach
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
register = template.Library()
@stringfilter
def sanitize_html(value):
if isinstance(value, basestring):
value = bleach.clean(va... | sema/django-2012 | website/mosaicportfolio/templatetags/htmlsanitizer.py | Python | mit | 564 |
#!/usr/bin/python3
import config as cfg
import SimpleITK as sitk
import numpy as np
import csv
from glob import glob
import pandas as pd
from tqdm import tqdm
import tools
import os
def mkdir(d):
try:
os.makedirs(d)
except:
pass
df_node = pd.read_csv(cfg.root+"annotations.csv")
# Getting lis... | yancz1989/cancer | Qi/img_mask_gen.py | Python | mit | 2,636 |
__author__ = 'davidl'
| davidvoler/ate_meteor | launcher/api/utils.py | Python | mit | 24 |
import cvlib
angle = 0
angles = []
center = []
for i in range(24): #24
img = cvlib.load("findloop_%d.jpg" % angle)
angles.append(angle)
rng = cvlib.inRangeThresh(img, (20,30,20), (200,130,120))
rng = cvlib.bitNot(rng)
cnt = cvlib.findContours(rng, thresh=250)
if cvlib.area(cnt[0]) > cvlib.area(... | nextBillyonair/compVision | AMX/Crystal/loop.py | Python | mit | 1,215 |
days = "Mon Tue Wed Thur Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec"
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something foine on here.
With the three double quotes.
We'll be able to type as much as we want.
Even 4 lines if we want... | joeryan/hardway | ex9.py | Python | mit | 337 |
"""Main functions for user interaction. All of these are imported into the
top-level namespace."""
import flavio
import numpy as np
from collections import defaultdict
from multiprocessing import Pool
from functools import partial
import warnings
def np_prediction(obs_name, wc_obj, *args, **kwargs):
"""Get the c... | flav-io/flavio | flavio/functions.py | Python | mit | 13,966 |
class DataClassFileTests():
def test_functionName1_test_case_4(self):
# Given: First test function line one
obj = new aClass()
expected = "Some result"
parameter1 = False
# When: First test function line two
result = obj.functionName1(parameter1)
... | anconaesselmann/ClassesAndTests | classes_and_testsTest/DocumentationFromUnitTestsTestData/DataSet4_py_ClassFileTest.py | Python | mit | 1,206 |
from fontTools.misc import transform
from fontParts.base.base import (
BaseObject,
TransformationMixin,
PointPositionMixin,
SelectionMixin,
IdentifierMixin,
dynamicProperty,
reference
)
from fontParts.base import normalizers
from fontParts.base.deprecated import DeprecatedPoint, RemovedPoint... | robofab-developers/fontParts | Lib/fontParts/base/point.py | Python | mit | 10,725 |
from frasco import current_app, url_for
from flask import safe_join
import os
upload_backends = {}
def file_upload_backend(cls):
upload_backends[cls.name] = cls
return cls
class StorageBackend(object):
def __init__(self, options):
self.options = options
def save(self, file, filename):
... | frascoweb/frasco-upload | frasco_upload/backends.py | Python | mit | 1,658 |
from unittest import TestCase
import re
from iperflexer import oatbran
bran = oatbran
COW = 'cow'
class TestOatBran(TestCase):
def test_brackets(self):
L_BRACKET = '['
R_BRACKET = "]"
self.assertRegexpMatches(L_BRACKET, bran.L_BRACKET)
self.assertNotRegexpMatches(R_BRACKET, bran.L... | rsnakamura/iperflexer | tests/testoatbran.py | Python | mit | 4,746 |
"""
wrap up widget construction in functions for easier use, making some
assumptions (e.g., expansion); use extras kw args for width, font/color
"""
from Tkinter import *
def frame(root, side=TOP, **extras):
widget = Frame(root)
widget.pack(side=side, expand=YES, fill=BOTH)
if extras: widg... | gmnamra/python-image-utils | Tools/widgets.py | Python | mit | 1,326 |
#!/usr/bin/env python3
# coding: utf-8
"""
登陆微信::
# 导入模块
from wxpy import *
# 初始化机器人,扫码登陆
bot = Bot()
找到好友::
# 搜索名称含有 "游否" 的男性深圳好友
my_friend = bot.friends().search('游否', sex=MALE, city="深圳")[0]
发送消息::
# 发送文本给好友
my_friend.send('Hello WeChat!')
# 发送图片
my_friend.send_image('... | youfou/wxpy | wxpy/__init__.py | Python | mit | 2,313 |
# -*- coding: utf-8 -*-
'''
Created on 2014-2-17
@author: CL.lam
'''
from sqlalchemy.sql.expression import and_
from rpac.widgets.components import RPACForm, RPACText, RPACCalendarPicker, \
RPACSelect
from rpac.model import ORDER_NEW, ORDER_INPROCESS, ORDER_COMPLETE, qry, \
PrintShop, ORDER_CANCEL
from rpac.mod... | LamCiuLoeng/fd | rpac/widgets/ordering.py | Python | mit | 1,705 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "addressfinder.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| ministryofjustice/addressfinder | manage.py | Python | mit | 256 |
"""unset a default setting
unset config
unset target
"""
from mod import log, settings
#-------------------------------------------------------------------------------
def run(fips_dir, proj_dir, args) :
"""run the 'unset' verb"""
if len(args) > 0 :
noun = args[0]
settings.unset(proj_dir, nou... | floooh/fips | verbs/unset.py | Python | mit | 705 |
f = open("taylor.txt")
lines = f.read().split("\n")
f.close()
words = []
for i in lines:
words.extend( i.split(" ") )
words = pd.Dataframe( words )
words = words[0].unique()
db = {}
for word in words:
db.update( { word : { "_word" : word } } )
db.update( {"_begin" : {"_word" : "_begin" } } )
for i in line... | Gurulhu/Reborn | features/chat/markov_creation_snippets.py | Python | mit | 895 |
import unittest
import modular_core.libfundamental as lfu
from modular_core.libsimcomponents import ensemble_manager as mng
import os, sys, pdb
#log = open(os.path.join(os.getcwd(), 'test_ensemble.log'), 'w')
#sys.stdout = log
import lattice as mod
class dummyTestCase(unittest.TestCase):
"""Tests for `dummy modul... | ctogle/lattice | tests/test_lattice.py | Python | mit | 1,022 |
#Olivia Millard - Homework 3
#This program will generate a Sierpinski Triangle.
import pygame, random, math
## PRE- user-inputted width/height to generate the size of the image
## POST- Creates a list with (len(length[0])); each list item is a list with (len(size[1]))
## Points = ima... | oliviamillard/CS141 | ChaosSierpinskiTriangle.py | Python | mit | 2,806 |