code stringlengths 3 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int64 3 1.05M |
|---|---|---|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/server/template_extras.py
#
# 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
# notice, ... | securestate/king-phisher | tests/server/template_extras.py | Python | bsd-3-clause | 2,395 |
"""
This script makes a dataset of two million approximately whitened patches,
extracted at random uniformly from the CIFAR-100 train dataset.
This script is intended to reproduce the preprocessing used by Adam Coates
et. al. in their work from the first half of 2011 on the CIFAR-10 and
STL-10 datasets.
"""
from __fut... | junbochen/pylearn2 | pylearn2/scripts/datasets/make_cifar100_patches_8x8.py | Python | bsd-3-clause | 2,282 |
"""Hue sensor entities."""
from aiohue.sensors import TYPE_ZLL_LIGHTLEVEL, TYPE_ZLL_TEMPERATURE
from homeassistant.components.hue.sensor_base import (
GenericZLLSensor,
SensorManager,
async_setup_entry as shared_async_setup_entry,
)
from homeassistant.const import (
DEVICE_CLASS_ILLUMINANCE,
DEVICE... | leppa/home-assistant | homeassistant/components/hue/sensor.py | Python | apache-2.0 | 3,075 |
import unittest
from mock import Mock, call
from dosagedaemon import DosageDaemon, TorrentClient, TorrentProvider
from dosagedaemon import Series, startdb
def faketrack(name, season, chapter):
name = name.lower()
try:
serie = Series.get(Series.name == name)
except Series.DoesNotExist:
ser... | jairot/dosage | test/dosagedaemon_test.py | Python | mit | 4,864 |
#! /usr/bin/env python
"""
couchbasekit.schema
~~~~~~~~~~~~~~~~~~~
:website: http://github.com/kirpit/couchbasekit
:copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt.
:license: MIT, see LICENSE.txt for details.
"""
from abc import ABCMeta
import datetime
from dateutil.parser import parse
fr... | kirpit/couchbasekit | couchbasekit/schema.py | Python | mit | 12,359 |
# -*- coding: utf-8 -*-
import os
"""
solve a scalar diffusion-reaction equation:
phi_t = kappa phi_{xx} + (1/tau) R(phi)
using operator splitting, with implicit diffusion
M. Zingale (2013-04-03)
"""
import numpy
from scipy import linalg
import sys
import pylab
def frhs(phi, tau):
""" reaction ODE righthand s... | NicovincX2/Python-3.5 | Physique/Diffusion de la matière/Équation de diffusion/diffreact.py | Python | gpl-3.0 | 6,948 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def run(str_command):
print str_command
os.system(str_command)
run('start chrome http://127.0.0.1:8080')
| argeweb/start | manage/open.py | Python | mit | 172 |
import os
import errno
import itertools
import flexmock
import pytest
import requests
from uuid import uuid4
from sqlalchemy import (create_engine, Column, String)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
from f8a_worker.defaults impor... | fridex/fabric8-analytics-worker | tests/test_utils.py | Python | gpl-3.0 | 10,587 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Clean and analyse POS/NER patterns.
#
# Usage:
#
# Author: rja
#
# Changes:
# 2017-05-05 (rja)
# - initial version
from __future__ import print_function
import re
import fileinput
re_clean_ner = re.compile("\(([A-Z]+) .+?\)")
re_clean_sla = re.compile("\w+/([A-Z]+)")
# ... | weltliteratur/vossanto | first/analyse_patterns.py | Python | gpl-3.0 | 1,679 |
class Tag(object):
def __init__(self, name, parent_api):
self.name = name
self.artist_counts = {}
self.parent_api = parent_api
self.parent_api.cached_tags[self.name] = self # add self to cache of known Tag objects
def set_artist_count(self, artist, count):
"""
A... | Christilut/DeputyDJ | src/external/pygazelle/tag.py | Python | gpl-2.0 | 826 |
# -*- encoding: utf-8 -*-
# Copyright (C) 2015-2016 Eric Goller <eric.goller@ninjaduck.solutions>
# This file is part of 'hamster-lib'.
#
# 'hamster-lib' is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe... | projecthamster/hamster-lib | hamster_lib/helpers/time.py | Python | gpl-3.0 | 12,685 |
#!/usr/bin/python3.4
import sys, os
from time import sleep
def main():
print("What do you want to do?")
print("1: Add")
print("2: Change state")
print("3: Show the lists")
print("4: Quit")
ques = input("...")
if ques == "1":
add()
elif ques == "2":
pick_done()
elif q... | JonathanPartain/todo-program | main.py | Python | gpl-3.0 | 2,535 |
import storage
from representation import Representation
from patch import Patch
| ChrisTimperley/EvoAnalyser.py | src/representation/__init__.py | Python | mit | 81 |
import unittest
from isbn_verifier import verify
# Tests adapted from `problem-specifications//canonical-data.json` @ v2.2.0
class IsbnVerifierTests(unittest.TestCase):
def test_valid_isbn_number(self):
self.assertIs(verify('3-598-21508-8'), True)
def test_invalid_check_digit(self):
self.a... | rootulp/exercism | python/isbn-verifier/isbn_verifier_test.py | Python | mit | 1,676 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Android mmssms.db database event formatter."""
import unittest
from plaso.formatters import android_sms
from tests.formatters import test_lib
class AndroidSmsFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the Android call history event form... | dc3-plaso/plaso | tests/formatters/android_sms.py | Python | apache-2.0 | 931 |
# -*- coding: utf-8 -*-
##
# This file is part of Testerman, a test automation system.
# Copyright (c) 2008,2009,2010 Sebastien Lefevre and other contributors
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software... | seblefevre/testerman | core/DependencyResolver.py | Python | gpl-2.0 | 12,705 |
import re
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.exceptions import ValidationError
from rest_framework.settings import api_settings
from rest_framework_json_api.utils import undo_format_field_name
class DjangoFilterBackend(DjangoFilterBackend):
"""
A Django-style O... | django-json-api/rest_framework_ember | rest_framework_json_api/django_filters/backends.py | Python | bsd-2-clause | 5,902 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND ... | mobb-io/django-erp | djangoerp/core/templatetags/introspection.py | Python | mit | 2,656 |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | KaranToor/MA450 | google-cloud-sdk/lib/googlecloudsdk/api_lib/dns/export_util.py | Python | apache-2.0 | 2,079 |
#!/usr/bin/python
import dbus
import sys, os
import time
import gobject
from dbus.mainloop.glib import DBusGMainLoop
WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1"
WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1"
WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1"
WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface"
... | robacklin/uclinux-users | wpa_supplicant/wpa_supplicant/examples/wpas-dbus-new.py | Python | gpl-2.0 | 4,272 |
""" invdisttree.py: inverse-distance-weighted interpolation using KDTree
fast, solid, local
"""
from __future__ import division
import numpy as np
from scipy.spatial import cKDTree as KDTree
# http://docs.scipy.org/doc/scipy/reference/spatial.html
__date__ = "2010-11-09 Nov" # weights, doc
#.......... | niels-anders/eubrazilcc-lidar | invdisttree.py | Python | gpl-3.0 | 6,158 |
#!/usr/bin/env python2
"""
WeatherAlerts
*******************
File Information
==================
**Project Home:**
http://github.com/zebpalmer/WeatherAlerts
**Original Author:**
Zeb Palmer
http://www.zebpalmer.com
**Documentation:**
http://weatheralerts.readthedocs.org
**License:**
MIT - full text inc... | zebpalmer/WeatherAlerts | weatheralerts/__init__.py | Python | mit | 467 |
'''
This code is basically an adaptation of the Arduino_TSL2591 library from
adafruit: https://github.com/adafruit/Adafruit_TSL2591_Library
for configuring I2C in a raspberry
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c
datasheet:
http://ams.com/eng/Products/Light-Sensors/L... | pindanet/Raspberry | domoticaController/var/www/html/tls2591.py | Python | gpl-3.0 | 7,829 |
import random
import jinja2
from jingo import register
@register.function
def emaillink(email, title=None, klass=None):
if not email:
return ""
fallback = email[::-1] # reverse
# inject junk somewhere
i = random.randint(0, len(email) - 1)
fallback = u"%s%s%s" % (jinja2.escape(fallback[:... | ingenioustechie/zamboni | mkt/users/helpers.py | Python | bsd-3-clause | 1,166 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms ... | mycodeday/crm-platform | website_blog/__openerp__.py | Python | gpl-3.0 | 1,819 |
#!/usr/bin/env python
#
# Copyright (c) 2016, IPnett AS
# 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 notice, this
# list o... | IPnett/puppet-yaml-enc | yamlenc/yamlenc.py | Python | bsd-2-clause | 4,300 |
from contextlib import contextmanager
try:
import hiredis # noqa
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
try:
import cryptography # noqa
CRYPTOGRAPHY_AVAILABLE = True
except ImportError:
CRYPTOGRAPHY_AVAILABLE = False
def from_url(url, **kwargs):
"""
... | andymccurdy/redis-py | redis/utils.py | Python | mit | 1,547 |
# Copyright (C) 2012 Andy Balaam and The Pepper Developers
# Released under the MIT License. See the file COPYING.txt for details.
from assert_parser_result import assert_parser_result
def test_import():
assert_parser_result(
r"""
0001:0001 "import"(import)
0001:0008 SYMBOL(sys)
0001:0011 NEWLI... | andybalaam/pepper | old/pepper1/src/test/parser/test_import.py | Python | mit | 427 |
#!/usr/bin/python3
# -*- coding: latin-1 -*-
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app... | jmcomber/FlaskDB | flaskr/__init__.py | Python | mit | 4,142 |
from ..utils import DocLoader
show = DocLoader("show", ".view", "cortex.webgl")
#def show(*args, **kwargs):
# from . import view
# return view.show(*args, **kwargs)
make_static = DocLoader("make_static", ".view", "cortex.webgl")
#def make_static(*args, **kwargs):
# from . import view
# return view.make_... | CVML/pycortex | cortex/webgl/__init__.py | Python | bsd-2-clause | 344 |
import logging
import urllib2
import re
import time
import gevent
from Config import config
from FileRequest import FileRequest
from Site import SiteManager
from Debug import Debug
from Connection import ConnectionServer
from util import UpnpPunch
class FileServer(ConnectionServer):
def __init__(self, ip=confi... | zebMcCorkle/ZeroNet | src/File/FileServer.py | Python | gpl-2.0 | 11,585 |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Nicolas Bessi
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | ovnicraft/geospatial | base_geoengine/geo_view/geo_raster_layer.py | Python | agpl-3.0 | 2,823 |
import codecs
import os
from setuptools import setup, find_packages
def read(*parts):
filename = os.path.join(os.path.dirname(__file__), *parts)
with codecs.open(filename, encoding='utf-8') as fp:
return fp.read()
VERSION = (0, 3, 9)
version = '.'.join(map(str, VERSION))
setup(
name='python-qu... | emburse/python-quickbooks | setup.py | Python | mit | 1,374 |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | laosiaudi/tensorflow | tensorflow/contrib/linear_optimizer/python/ops/sharded_mutable_dense_hashtable_test.py | Python | apache-2.0 | 4,000 |
# -* coding: utf-8 *-
from PyQt4 import QtGui
from collector.ui.gen.im_export import Ui_Dialog
from collector.ui.views import Dialog
from collector.ui.helpers.customtoolbar import CustomToolbar
from collector.core.controller import get_manager
from collector.core.plugin import PluginExporter, PluginImporter
import logg... | arielvb/collector | collector/ui/views/im_export.py | Python | gpl-2.0 | 2,612 |
import unittest
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
sub... | dbrattli/RxPY | tests/test_observable/test_scan.py | Python | apache-2.0 | 6,084 |
from floppyforms import widgets
from django.template import loader
class DateTimeLocalInput(widgets.DateTimeInput):
input_type = "datetime-local"
class SplitDateTimeWidget(widgets.SplitDateTimeWidget):
"SplitDateTimeWidget with a custom template."
template_name = "floppyforms/splitdatetime.html"
de... | littleweaver/django-zenaida | zenaida/widgets.py | Python | bsd-3-clause | 534 |
# -*- coding: utf-8 -*-
# Keeping this in salt-extensions until https://github.com/saltstack/salt/pull/56146 is merged and released
'''
Consul sdb Module
:maintainer: SaltStack
:maturity: New
:platform: all
This module allows access to Consul using an ``sdb://`` URI
Like all sdb modules, the Consul modu... | mitodl/salt-extensions | extensions/_sdb/consul.py | Python | bsd-3-clause | 2,528 |
import seamless
from seamless.core import context, cell, transformer, unilink
ctx = context(toplevel=True)
ctx.cell1 = cell().set(1)
ctx.cell2 = cell().set(2)
ctx.result = cell()
ctx.tf = transformer({
"a": "input",
"b": "input",
"c": "output"
})
ctx.tf._debug = {
"direct_print": True,
"ide": "vsco... | sjdv1982/seamless | tests/lowlevel/simple-debug.py | Python | mit | 1,009 |
import ConfigParser
import os
config = ConfigParser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), 'setting\config.ini'))
print config.sections()
try:
USERNAME = config.get('LINE', 'USERNAME')
PASSWORD = config.get('LINE', 'PASSWORD')
GROUPNAME = config.get('LINE', 'GROUPNAME')
print USERNAME... | 5610110083/Safety-in-residential-project | cgi-bin/any/setting.py | Python | apache-2.0 | 390 |
# -*- coding: utf-8 -*-
"""
protocols.base
~~~~~~~~~~~~~~
:copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved.
:license: GPL3, see LICENSE for more details.
"""
import logging
import types
log = logging.getLogger('pox.protocols.base')
prot = None
name = ... | nict-isp/scn-openflow-driver | src/ncps_openflow/protocols/base.py | Python | gpl-3.0 | 1,076 |
# -*- coding: utf-8 -*-
import hashlib
import os
from datetime import datetime, timedelta
from django.conf import settings
import mock
from nose.tools import eq_
from pyquery import PyQuery
import amo
import amo.tests
from amo.urlresolvers import reverse
from addons.models import Addon
from addons.tests.test_views i... | jbalogh/zamboni | apps/versions/tests.py | Python | bsd-3-clause | 31,009 |
# Copyright (C) 2019-2021 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | repology/repology | repology/parsers/parsers/t2.py | Python | gpl-3.0 | 4,354 |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... | 111pontes/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_infra_objmgr_cfg.py | Python | apache-2.0 | 52,191 |
#@+leo-ver=5-thin
#@+node:2015.20140907143819.2142: * @file gear.py
#@@language python
#@@tabwidth -4
#@+<<declarations>>
#@+node:2015.20140907143819.2143: ** <<declarations>> (application)
#@@language python
import cherrypy
import os
import sys
# 這個程式要計算正齒輪的齒面寬, 資料庫連結希望使用 pybean 與 SQLite
# 導入 pybean 模組與所要使用的 Store 及... | chiamingyen/cp_project | wsgi/gear.py | Python | gpl-3.0 | 11,977 |
import abc
import six
import tensorflow as tf
from collections import Counter
from luminoth.tools.dataset.readers import BaseReader
class ObjectDetectionReader(BaseReader):
"""
Reads data suitable for object detection.
The object detection task needs the following information:
- images.
... | tryolabs/luminoth | luminoth/tools/dataset/readers/object_detection/object_detection_reader.py | Python | bsd-3-clause | 6,476 |
#! /usr/bin/env python3
"""
Usage:
python -m test [options] [test_name1 [test_name2 ...]]
python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
If no arguments or options are provided, finds all files matching
the pattern "test_*" in the Lib/test subdirectory and runs
them in alphabetical orde... | louietsai/python-for-android | python3-alpha/python3-src/Lib/test/regrtest.py | Python | apache-2.0 | 57,802 |
#!/usr/bin/python
from __future__ import print_function
import hourly
data = hourly.load("ottawa")
hours = []
for hour,hourdata in data.iteritems():
visibility = hourdata[hourly.VISIBILITY]
if len(visibility):
visibility = float(visibility)
#if visibility <= 0.2 and 'fog' in hourdata[hourly.W... | endlisnis/weather-records | visibility.py | Python | gpl-3.0 | 723 |
# -*- coding: utf-8 -*-
"""Unit and functional test suite for sample-ecommerce."""
from os import getcwd, path
from paste.deploy import loadapp
from webtest import TestApp
from gearbox.commands.setup_app import SetupAppCommand
from tg import config
from tg.util import Bunch
from sample_ecommerce import model
__all... | gasbasd/tgapp-stroller2 | sample-ecommerce/sample_ecommerce/tests/__init__.py | Python | mit | 2,248 |
""" Test Linux provider discovery
"""
# disable docstring checking
# pylint: disable=C0111
# disable checking no-self-use
# pylint: disable=R0201
# pylint: disable=W0212
# pylint: disable=W0201
# pylint: disable=F0401
from netshowlib.cumulus import provider_discovery
import mock
import os
import sys
from asserts import... | CumulusNetworks/netshow-cumulus-lib | tests/test_netshowlib/test_provider_discovery.py | Python | gpl-2.0 | 1,211 |
# coding=utf-8
# Author: Marvin Pinto <me@marvinp.ca>
# Author: Dennis Lutter <lad1337@gmail.com>
# Author: Aaron Bieber <deftly@gmail.com>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | pedro2d10/SickRage-FR | sickbeard/notifiers/telegram.py | Python | gpl-3.0 | 6,512 |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="family",
parent_name="histogram2dcontour.contours.labelfont",
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_... | plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2dcontour/contours/labelfont/_family.py | Python | mit | 559 |
'''
'''
import enum
import json
import os
from datatypes import VarInt, DATA_TYPE_REGISTRY
class NoSuchFieldException(RuntimeError):
pass
@enum.unique
class State(enum.Enum):
'''This represents the different game states that our client can be in.'''
HANDSHAKING = 'handshaking'
LOGIN = 'login'
... | smilechaser/mc-roboto | protocol.py | Python | apache-2.0 | 7,124 |
#!/usr/bin/env python
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | ycool/apollo | modules/tools/record_analyzer/lidar_endtoend_analyzer.py | Python | apache-2.0 | 3,542 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
# Flag to indicate if this migration is too risky
# to run online and needs to be coordinated for offline
... | mvaled/sentry | src/sentry/south_migrations/0401_auto__chg_field_projectdsymfile_uuid.py | Python | bsd-3-clause | 102,837 |
# -*- coding: utf-8 -*-
from txlib.utils import _logger
class _Registry(object):
"""A class to act as registry for the various objects used.
This is used to decouple various classes and allows finer-grained split of
responsibilities to classes.
"""
responsibilities = {}
def __getattr__(sel... | transifex/transifex-python-library | txlib/registry/registry.py | Python | lgpl-3.0 | 1,258 |
# This file is part of jukes-cantor.
# Copyright (C) 2014 Christopher Kyle Horton <chorton@ltu.edu>
# jukes-cantor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at you... | WarriorIng64/jukes-cantor | fasta_processing.py | Python | gpl-3.0 | 2,638 |
# coding=utf-8
"""Exceptions raised by Medusa providers."""
from __future__ import unicode_literals
class ProviderError(Exception):
"""A generic provider exception occurred."""
class AuthenticationError(ProviderError):
"""Provider authentication failed."""
class ParsingError(ProviderError):
"""Provi... | FireBladeNooT/Medusa_1_6 | medusa/providers/exceptions.py | Python | gpl-3.0 | 343 |
# -*- coding: utf-8 -*-
from decimal import Decimal as D, InvalidOperation, ROUND_UP
from .models import Currency as C
from .conf import SESSION_KEY
def get_active_currencies_qs():
return C.active.defer('info').all()
def calculate(price, to_code, **kwargs):
"""Converts a price in the default currency to ano... | racitup/django-currencies | currencies/utils.py | Python | bsd-3-clause | 1,619 |
# Radioco - Broadcasting Radio Recording Scheduling system.
# Copyright (C) 2014 Iago Veloso Abalo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at yo... | txenoo/django-radio | radioco/apps/schedules/admin.py | Python | gpl-3.0 | 4,680 |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from models import *
from rapidsms.message import StatusCodes
from apps.reporters.models import *
from apps.form.formslogic import FormsLogic
import re
class BednetsFormsLogic(FormsLogic):
''' This class will hold the nigeria-specific forms logic.
I'm not... | takinbo/rapidsms-borno | apps/bednets/formslogic.py | Python | lgpl-3.0 | 8,351 |
"""Test the National Weather Service (NWS) config flow."""
from unittest.mock import patch
import aiohttp
from homeassistant import config_entries
from homeassistant.components.nws.const import DOMAIN
async def test_form(hass, mock_simple_nws_config):
"""Test we get the form."""
hass.config.latitude = 35
... | jawilson/home-assistant | tests/components/nws/test_config_flow.py | Python | apache-2.0 | 3,482 |
import logging
import struct
from copy import deepcopy
from pymoku._oscilloscope import _CoreOscilloscope
from pymoku._instrument import to_reg_signed
from pymoku._instrument import from_reg_signed
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument i... | liquidinstruments/pymoku | pymoku/_iirfilterbox.py | Python | mit | 32,876 |
from __future__ import unicode_literals
import calendar
import json
import pytz
import random
import datetime
from dateutil.parser import parse
from decimal import Decimal
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import connection, transaction
from dja... | Stanford-Legal-Tech-Design/legaltech-rapidpro | temba/utils/__init__.py | Python | agpl-3.0 | 11,356 |
from PyQt4 import QtGui
class AboutLabel(QtGui.QLabel):
def __init__(self, parent=None):
QtGui.QLabel.__init__(self, parent)
self.setStyleSheet("color: white; border-radius: 5px;")
self.setMargin(20)
self.setWordWrap(True)
self.setText("About RedCenter"
... | fortharris/RedCenter | Extensions/AboutLabel.py | Python | gpl-3.0 | 853 |
# coding=utf-8
"""Docstring for this file."""
__author__ = 'ismailsunni'
__project_name = 'watchkeeper'
__filename = 'movement'
__date__ = '5/11/15'
__copyright__ = 'imajimatika@gmail.com'
__doc__ = ''
from django.contrib.gis.db import models
from django.utils import timezone
from django.core.exceptions import ObjectD... | MariaSolovyeva/watchkeeper | django_project/event_mapper/models/movement.py | Python | bsd-2-clause | 3,699 |
#encoding:utf-8
subreddit = 'privacy'
t_channel = '@r_privacy'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| Fillll/reddit2telegram | reddit2telegram/channels/~inactive/r_privacy/app.py | Python | mit | 137 |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
""" Blue Spider UI's code. In real need of refactoring, but seems to work. """
# If I keep trying, this code will end up looking as messy as elite map's!
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
try:
import Image
import ImageQt
except Impor... | Yepoleb/blue-spider | bluespider/mapped_gui.py | Python | gpl-3.0 | 42,744 |
import codecs
import collections
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def make_keywords_dicts(file):
keyword_dict = dict()
tfidf_dict = dict()
max_kw_lenght=0
for line in codecs.open(file, 'r', "utf-8"):
splitted_line = line.split('\t')
tokens=spl... | anonymous-conferences/keyphrase_clustering | kpaggregator/functions.py | Python | apache-2.0 | 11,628 |
# logcmdutil.py - utility for log-like commands
#
# Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import itertools
import os
import ... | smmribeiro/intellij-community | plugins/hg4idea/testData/bin/mercurial/logcmdutil.py | Python | apache-2.0 | 42,713 |
"""Utilities for accessing and working with JSON schemas."""
import abc
from collections import namedtuple, OrderedDict
from functools import wraps
import importlib
import json
import os.path
import pkgutil
import jsl
import jsonschema
def added_in(role):
"""Provide helper for schema fields added in a particula... | miteshvp/fabric8-analytics-worker | f8a_worker/schemas.py | Python | gpl-3.0 | 15,518 |
# Configurable hooks in the build system. Can be used by various platforms
# to customize the build process.
################################################################################
# Hooks for the various parts of the build process
# Internal mapping of hooks per tool
_hooks = {}
# Internal mapping of runni... | mnlipp/mbed | workspace_tools/hooks.py | Python | apache-2.0 | 4,790 |
import numpy as np
import chainladder as cl
from rpy2.robjects.packages import importr
from rpy2.robjects import r
CL = importr("ChainLadder")
def test_mcl_paid():
df = r("MunichChainLadder(MCLpaid, MCLincurred)").rx("MCLPaid")
p = cl.MunichAdjustment(paid_to_incurred=("paid", "incurred")).fit(
cl.De... | jbogaardt/chainladder-python | chainladder/development/tests/test_munich.py | Python | mit | 1,554 |
from django.contrib import admin
from . import models as m
class CompanyAdmin(admin.ModelAdmin):
model = m.Company
list_display = ['name', 'slug', 'bank_account_no']
admin.site.register(m.Company, CompanyAdmin)
| guoqiao/django-nzpower | nzpower/admin.py | Python | mit | 222 |
# -*- coding: utf-8 -*-
# RelayBot - Simple VNC Relay Service, core/config.py
#
# Copyright (C) 2021 Matthew Beeching
#
# This file is part of RelayBot.
#
# RelayBot is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... | jobe1986/relaybot | core/config.py | Python | gpl-3.0 | 3,360 |
import os
#from distutils.core import setup
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname )).read()
#with open('README.rst') as file:
# long_description = file.read()
setup(name='spacegrids',
version='1.9',
author='Willem Sijp'... | willo12/spacegrids | setup.py | Python | bsd-3-clause | 1,211 |
# 205 - Isomorphic Strings (Easy)
# https://leetcode.com/problems/isomorphic-strings/
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
# Check if the characters from s can be replaced consistently to
# obtai... | zubie7a/Algorithms | LeetCode/01_Easy/lc_205.py | Python | mit | 1,442 |
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | tensorflow/probability | tensorflow_probability/python/glm/proximal_hessian_test.py | Python | apache-2.0 | 15,178 |
# coding: utf-8
#
# drums-backend a simple interactive audio sampler that plays vorbis samples
# Copyright (C) 2009 C.D. Immanuel Albrecht
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Fou... | immo/pyTOM | df/df_reinitialize_generators.py | Python | gpl-3.0 | 8,374 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | mavenlin/tensorflow | tensorflow/python/grappler/memory_optimizer_test.py | Python | apache-2.0 | 8,770 |
import pytz
from django.conf import settings
from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.translation import gettext as _
# Wagtail languages with >=90% coverage
# This list is manually maintained
WAGTAILADMIN_PROVIDED_LANGUAGES = [
('ar', 'Arabic'),
('ca', 'Catalan'),
... | gasman/wagtail | wagtail/admin/localization.py | Python | bsd-3-clause | 4,210 |
import dont_tread_on_memes
import click
@click.command()
@click.option("--message", prompt="Don't _____ me",
help=("A message to use as a caption for the flag"),
metavar="<caption>")
@click.option("--format/--no-format", default=True,
help=("Whether to format the provided mes... | controversial/dont-tread-on-memes | dont_tread_on_memes/__main__.py | Python | mit | 1,006 |
# Author: Samuel Genheden samuel.genheden@gmail.com
"""
Program to calculate bond force constant with the Seminario method
for specific bonds
Ref:
JM Seminario, Int. J. Quant. Chem. 1996, 60(7), 1271-1277
Examples:
seminario.py -f model.fchk -s model.gro -b 1:N-4:CU 1:ND1-4:CU 2:NE2-4:CU
"""
import argparse
import ... | SGenheden/Scripts | Mol/seminario.py | Python | mit | 3,971 |
import unittest
from katas.kyu_7.noobcode_4_hot_singles import hot_singles
class HotSinglesTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(hot_singles(
['tartar', 'blanket', 'domino'], ['blanket']
), ['tartar', 'domino'])
def test_equal_2(self):
self... | the-zebulan/CodeWars | tests/kyu_7_tests/test_noobcode_4_hot_singles.py | Python | mit | 859 |
"""
Model.
Author: Mikhail Kita, 471
"""
import math
similar_for_user = {}
def get_user_vector(data, user, songs_set):
"""
Returns songs vector, which contains only elements from the songs_set.
"""
vector = {}
if user in data:
items = list(data[user].keys() & songs_set)
vector ... | MaKToff/SPbSU_Homeworks | Semester 7/Recommender system/model.py | Python | mit | 2,218 |
"""Recurrent Neural Network estimators."""
# Copyright 2015-present Scikit Flow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/l... | panmari/tensorflow | tensorflow/contrib/skflow/python/skflow/estimators/rnn.py | Python | apache-2.0 | 10,434 |
# Copyright 2017 Google Inc.
#
# 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, s... | thenenadx/forseti-security | google/cloud/security/scanner/scanners/groups_scanner.py | Python | apache-2.0 | 9,663 |
"""Provides the HTTP request handling interface."""
import requests
from .const import __version__, TIMEOUT
from .exceptions import InvalidInvocation, RequestException
class Requestor(object):
"""Requestor provides an interface to HTTP requests."""
def __getattr__(self, attribute):
"""Pass all undefi... | RuiNascimento/krepo | plugin.video.sparkle/resources/lib/modules/prawcore/requestor.py | Python | gpl-2.0 | 2,016 |
# -*- coding: utf-8 -*-
from .skeleton import Skeleton
from .fake_data import dict_driver
from APITaxi.models.taxis import Driver
from json import dumps, loads
from copy import deepcopy
from APITaxi.extensions import db
from cStringIO import StringIO
class TestDriverPost(Skeleton):
url = '/drivers/'
role = 'op... | odtvince/APITaxi | tests/drivers_tests.py | Python | agpl-3.0 | 1,827 |
#!/usr/bin/env python3
"""This example shows some graphic capabilities of the EVE Click wrapper of the
LetMeCreate library. You can find more documentation about these commands in
the programmer guide available on FTDI website:
http://www.ftdichip.com/Support/Documents/ProgramGuides/FT800%20Programmers%20Guide.pdf
It ... | francois-berder/PyLetMeCreate | examples/eve_example_3.py | Python | bsd-3-clause | 2,225 |
# Copyright (C) 2020 Red Hat, Inc., Jake Hunsaker <jhunsake@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU Gen... | TurboTurtle/sos | sos/policies/init_systems/systemd.py | Python | gpl-2.0 | 1,563 |
"""
Testing computing partial volume of the contact binary
"""
import libphoebe
def test_contact_vol(plot=False):
x=0.7 # where we cut it
choice = 0 # 0 for left and 1 for right
q=0.1
Omega0=1.9
d=1.
res = libphoebe.roche_contact_partial_area_volume(x, q, d, Omega0, choice)
larea0 = 4.5870285... | phoebe-project/phoebe2 | tests/nosetests/test_contacts/test_vol.py | Python | gpl-3.0 | 580 |
"""
YAML serializer.
Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
"""
import decimal
import yaml
import sys
from io import StringIO
from django.db import models
from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Serializer as PythonSe... | edisonlz/fruit | web_project/base/site-packages/django/core/serializers/pyyaml.py | Python | apache-2.0 | 2,633 |
# -*- coding:utf-8 -*-
import mock
import unittest
from passlib.hash import bcrypt
from mockbcrypt import plugin
from nose_parameterized import parameterized
class TestMockBcryptPlugin(unittest.TestCase):
def setUp(self):
super(TestMockBcryptPlugin, self).setUp()
self.plugin = plugin.MockBcryptP... | boneyao/mockbcrypt | tests/test_plugin.py | Python | mit | 827 |
import unittest
import numpy.testing as testing
import numpy as np
import fitsio
from numpy import random
from redmapper.fitters import EcgmmFitter
from redmapper.fitters import MedZFitter
from redmapper.fitters import RedSequenceFitter
from redmapper.fitters import CorrectionFitter
from redmapper.fitters import Error... | erykoff/redmapper | tests/test_fitters.py | Python | apache-2.0 | 9,418 |
# -*- encoding: utf-8 -*-
from abjad.tools.rhythmmakertools.BooleanPattern import BooleanPattern
class NullMask(BooleanPattern):
r'''A sustain mask.
.. container:: example
::
>>> mask = rhythmmakertools.NullMask(
... indices=[0, 1, 7],
... period=16,
... | mscuthbert/abjad | abjad/tools/rhythmmakertools/NullMask.py | Python | gpl-3.0 | 612 |
__author__ = 'Ahmad Syarif'
import Data
from Data import DataHandler
import Command
from Command import CommandHandler
from multiprocessing import Process
from pydispatch import dispatcher
command = None
def startWelcomingBehavior():
VISUAL_FACE_DETECTION = Data.VISUAL_FACE_DETECTION
AVATAR_DATA_TACTILE = Data.... | ahmadsyarif/Python-Agent | welcoming.py | Python | apache-2.0 | 923 |
# Copyright 2019 Aerospike, Inc.
#
# 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, ... | aerospike/aerospike-admin | lib/view/sheet/decleration.py | Python | apache-2.0 | 30,217 |
from .comic_page_handler import (ComicPageHandlerDoublePage,
ComicPageHandlerSinglePage)
class ComicPageHandlerFactory():
read_mode = {
False: ComicPageHandlerSinglePage,
True: ComicPageHandlerDoublePage,
}
@staticmethod
def create_handler(page_read_mo... | mstuttgart/pynocchio-comic-reader | pynocchio/comic_page_handler_factory.py | Python | gpl-3.0 | 491 |
import re
import logging
import mappings
logger = logging.getLogger('dragnet.nacp_normaliser')
def iterate_ugly_dict(parent):
if not isinstance(parent, dict):
return []
for key in parent:
if key == 'empty' or not isinstance(parent[key], dict):
continue
yield key
def no... | excieve/dragnet | utils/nacp_normaliser.py | Python | mit | 11,115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.