code stringlengths 1 199k |
|---|
import sys
if sys.version_info[0] >= 3:
basestr = str
else:
basestr = basestring
from .converters import (LanguageConverter, LanguageReverseConverter, LanguageEquivalenceConverter, CountryConverter,
CountryReverseConverter)
from .country import country_converters, COUNTRIES, COUNTRY_MATRIX, Country
from .ex... |
from exchanges.bitfinex import Bitfinex
import re
def bitcoinValue(msg):
val = Bitfinex().get_current_price()
formattedVal = "$" + "{:,.2f}".format(val)
if re.search(r"(?i)moon", msg):
return "To the moon! " + formattedVal
else:
return "Bitcoin: " + formattedVal |
def caught(pyn, fpyn):
fx, fy = fpyn.xy()
return pyn.distance(fx, fy) <= 1 |
import os, sys, time
from reportlab.graphics.barcode.common import *
from reportlab.graphics.barcode.code39 import *
from reportlab.graphics.barcode.code93 import *
from reportlab.graphics.barcode.code128 import *
from reportlab.graphics.barcode.usps import *
from reportlab.graphics.barcode.usps4s import USPS_4State
fr... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('libreosteoweb', '0021_therapeutsettings_siret'),
]
operations = [
migrations.AddField(
model_name='therapeutsettings',
name='invo... |
"""
poller-wrapper A small tool which wraps around the poller and tries to
guide the polling process with a more modern approach with a
Queue and workers
Authors: Job Snijders <job.snijders@atrato.com>
Orsiris de Jong <contact@netpower.fr>
Date: Oct 2019... |
import copy
import secrets
races = {}
colors = {
'πΆ': 0xccd6dd,
'π±': 0xffcb4e,
'π': 0x99aab5,
'π°': 0x99aab5,
'π': 0x9266cc,
'π ': 0xffcc4d,
'π¦': 0xf4900c,
'π¦': 0xbe1931,
'πΈ': 0x77b255,
'π§': 0xf5f8fa
}
names = {
'πΆ': 'dog',
'π±': 'cat',
'π': 'mouse',
'π°... |
"""Extra SQLAlchemy ORM types"""
__all__ = ['JSONEncodeDict']
import cjson
from sqlalchemy.types import TypeDecorator, String
from sqlalchemy.ext.mutable import Mutable
from pynojo.exc import PynojoRuntimeError
class JSONEncodeDict(TypeDecorator):
"""Represents an mutable python *dict* as a json-encoded string."""
... |
"""An FTP client class and some helper functions.
Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
Example:
>>> from ftplib import FTP
>>> ftp = FTP('ftp.python.org') # connect to host, default port
>>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
'230 Guest login ok, acces... |
from __future__ import division
import numpy as np
import pytest
import odl
from odl.trafos.backends import pyfftw_call, PYFFTW_AVAILABLE
from odl.util import (
is_real_dtype, complex_dtype)
from odl.util.testutils import (
all_almost_equal, simple_fixture)
pytestmark = pytest.mark.skipif(not PYFFTW_AVAILABLE,
... |
from __future__ import unicode_literals
import base64
import calendar
import datetime
import re
import sys
import unicodedata
from binascii import Error as BinasciiError
from email.utils import formatdate
from django.utils import six
from django.utils.datastructures import MultiValueDict
from django.utils.encoding impo... |
from datetime import date, timedelta
from django.conf import settings
date_in_near_future = date.today() + timedelta(days=14)
FOUR_YEARS_IN_DAYS = 1462
election_date_before = lambda r: {
'DATE_TODAY': date.today()
}
election_date_on_election_day = lambda r: {
'DATE_TODAY': date_in_near_future
}
election_date_af... |
"""
XBlock runtime services for LibraryContentModule
"""
from django.core.exceptions import PermissionDenied
from opaque_keys.edx.locator import LibraryLocator
from xmodule.library_content_module import ANY_CAPA_TYPE_VALUE
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodule.capa_module import Capa... |
from PyQt4 import QtCore, QtGui
import os
class ConfigPage(QtGui.QWizardPage):
def __init__(self, templates, parent=None):
super(ConfigPage, self).__init__(parent)
#self.setTitle("Configuration")
#self.setSubTitle("Alter configuration and build your own platform.")
#self.setPixmap(Qt... |
import platform
import shutil
import sys
import os
from spack import *
class Namd(MakefilePackage):
"""NAMDis a parallel molecular dynamics code designed for
high-performance simulation of large biomolecular systems."""
homepage = "http://www.ks.uiuc.edu/Research/namd/"
url = "file://{0}/NAMD_2.12_... |
from twisted.internet import defer
from twisted.spread import pb
from flumotion.common import testsuite
from flumotion.test import realm
from flumotion.twisted import pb as fpb
from flumotion.worker import medium
class TestWorkerAvatar(fpb.PingableAvatar):
def __init__(self, avatarId, mind):
fpb.PingableAva... |
from spack import *
class PyLocalcider(PythonPackage):
"""Tools for calculating sequence properties of disordered proteins"""
homepage = "http://pappulab.github.io/localCIDER"
url = "https://pypi.io/packages/source/l/localcider/localcider-0.1.14.tar.gz"
version('0.1.14', sha256='54ff29e8a011947cca5... |
"""distutils.unixccompiler
Contains the UnixCCompiler class, a subclass of CCompiler that handles
the "typical" Unix-style command-line C compiler:
* macros defined with -Dname[=value]
* macros undefined with -Uname
* include search directories specified with -Idir
* libraries specified with -lllib
* library ... |
from __future__ import division
import sys, os, re
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'SpiffWorkflow'
copyright = '2012 ' + ', '.join(open('../AUTHORS'... |
"""
Management class for basic VM operations.
"""
import functools
import os
from oslo.config import cfg
from nova.api.metadata import base as instance_metadata
from nova import exception
from nova.openstack.common import excutils
from nova.openstack.common.gettextutils import _
from nova.openstack.common import import... |
from foam.sfa.util.xrn import urn_to_hrn
from foam.sfa.trust.credential import Credential
from foam.sfa.trust.auth import Auth
class Start:
def __init__(self, xrn, creds, **kwargs):
hrn, type = urn_to_hrn(xrn)
valid_creds = Auth().checkCredentials(creds, 'startslice', hrn)
origin_hrn = Crede... |
from datetime import datetime
class AliveSquidsCSV(object):
##
# Write a line to text file.
# @param self The Object Pointer.
# @param record Record (text)
#
def write_record(self, file, record):
try:
csv_file = open(file, "a")
csv_file.write(record)
... |
import os
import sys
import argparse
import subprocess
import random
from os.path import join as pjoin
DIMENSIONS = '150x150' # Dimensions of the resized image (<width>x<height>)
GEOMETRY = '+4+4' # How to arrange images (+<rows>+<columns>)
TO_CREATE_DIRS = ['resized/', 'final/']
def setup(output_path):
"""
C... |
ο»Ώ# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
from clr import AddReference
AddReference("System.Core")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Algorithm")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import QCAlgorithm
from QuantConnect.Data.U... |
import json
import os
import re
import cherrypy
import mako
from girder import constants
from girder.models.setting import Setting
from girder.settings import SettingKey
from girder.utility import config
class WebrootBase:
"""
Serves a template file in response to GET requests.
This will typically be the ba... |
from sahara.service.edp import base_engine
from sahara.utils import edp
class FakeJobEngine(base_engine.JobEngine):
def cancel_job(self, job_execution):
pass
def get_job_status(self, job_execution):
pass
def run_job(self, job_execution):
return 'engine_job_id', edp.JOB_STATUS_SUCCEED... |
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
class Net(neutron.NeutronResource):
PROPERTIES = (
NAME, VALUE_SPECS, ADMIN_STATE_UP, TENANT_ID, SHARED,
DH... |
input = """
% Guess colours.
chosenColour(N,C) | notChosenColour(N,C) :- node(N), colour(C).
% At least one color per node.
:- #count{ C : chosenColour(X,C) } > 1, node(X).
:- #count{ C : chosenColour(X,C) } < 1, node(X).
% No two adjacent nodes have the same colour.
:- link(X,Y), X<Y, chosenColour(X,C), chosenColour(... |
"""
Unit tests for :py:obj:`OpenSSL.rand`.
"""
from unittest import main
import os
import stat
from OpenSSL.test.util import TestCase, b
from OpenSSL import rand
class RandTests(TestCase):
def test_bytes_wrong_args(self):
"""
:py:obj:`OpenSSL.rand.bytes` raises :py:obj:`TypeError` if called with the... |
from binascii import hexlify
import mock
import socket
import unittest
from networking_cisco.plugins.cisco.cpnr.cpnr_client import UnexpectedError
from networking_cisco.plugins.cisco.cpnr.cpnr_dns_relay_agent import (
DnsRelayAgent)
from networking_cisco.plugins.cisco.cpnr.cpnr_dns_relay_agent import cfg
from netwo... |
import os
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='gcc'
BSP_LIBRARY_TYPE = None
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if os.getenv('RTT_ROOT'):
RTT_ROOT = os.getenv('RTT_ROOT')
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = r'C:\Users\XXYYZZ'
elif CROSS_TOOL == 'keil':
P... |
"""Unique operator"""
from tvm import te, tir
from ..te import hybrid
from .scan import cumsum
from .sort import sort, argsort
def _calc_adjacent_diff_ir(data, output, binop=tir.Sub):
"""Low level IR to calculate adjacent difference in an 1-D array.
Parameters
----------
data : Buffer
Input 1-D ... |
def this_is_the_outer_lib():
print 'For imports test' |
from tempest.api.orchestration import base
from tempest.common.utils import data_utils
from tempest.openstack.common import log as logging
from tempest.test import attr
LOG = logging.getLogger(__name__)
class StacksTestJSON(base.BaseOrchestrationTest):
_interface = 'json'
empty_template = "HeatTemplateFormatVer... |
"""This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_terminate_job_flow`."""
import warnings
from airflow.providers.amazon.aws.operators.emr_terminate_job_flow import EmrTerminateJobFlowOperator # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.amazon.a... |
"""
WSGI config for mdotproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... |
import os, sys, re, urllib, json, subprocess
import time
import urllib.request
import smtplib
from email.mime.text import MIMEText
def getJSON(url, creds = None, cookie = None):
headers = {}
if creds and len(creds) > 0:
xcreds = creds.encode(encoding='ascii', errors='replace')
auth = base64.enco... |
import os
import signal
import subprocess
import logging
import socket
import time
import redis
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
redis_ver = '2.6.13'
redis_bdir = '/tmp/cache/' + os.environ['USER'] + '/systemless_test'
redis_url = redis_bdir + '... |
import logging
from shotgun.settings import LOG_FILE
def configure_logger():
"""Configures shotgun logger
"""
logger = logging.getLogger('shotgun')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s %(levelname)s %(process)d (%(module)s) %(message)s',
"%Y-%m-%... |
import mock
from oslo_config import cfg
from ryu.services.protocols.bgp import bgpspeaker
from ryu.services.protocols.bgp.rtconf.neighbors import CONNECT_MODE_ACTIVE
from neutron.services.bgp.agent import config as bgp_config
from neutron.services.bgp.driver import exceptions as bgp_driver_exc
from neutron.services.bgp... |
import optparse
import StringIO
import webkitpy.thirdparty.unittest2 as unittest
from webkitpy.common.host_mock import MockHost
from webkitpy.layout_tests import lint_test_expectations
class FakePort(object):
def __init__(self, host, name, path):
self.host = host
self.name = name
self.path =... |
from oslo_config import cfg
cfg.CONF.import_opt('stack_scheduler_hints', 'heat.common.config')
class SchedulerHintsMixin(object):
'''
Utility class to encapsulate Scheduler Hint related logic shared
between resources.
'''
HEAT_ROOT_STACK_ID = 'heat_root_stack_id'
HEAT_STACK_ID = 'heat_stack_id'
... |
"""Utilities and helper functions."""
import abc
import contextlib
import datetime
import functools
import hashlib
import inspect
import logging as py_logging
import os
import pyclbr
import random
import re
import shutil
import socket
import stat
import sys
import tempfile
import time
import types
from xml.dom import m... |
import sys
import bottle
import commands
from bottle import route, send_file, template
@route('/')
def index():
bottle.TEMPLATES.clear() # For rapid development
return template("index", master_port = master_port)
@route('/framework/:id#[0-9-]*#')
def framework(id):
bottle.TEMPLATES.clear() # For rapid development... |
from requestbuilder import Arg
from requestbuilder.response import PaginatedResponse
from euca2ools.commands.iam import IAMRequest, arg_account_name
from euca2ools.commands.iam.getaccountpolicy import GetAccountPolicy
class ListAccountPolicies(IAMRequest):
DESCRIPTION = ('[Eucalyptus only] List one or all policies ... |
from typing import List
import numpy as np
from scipy import signal
from cerebralcortex.data_processor.signalprocessing.dataquality import Quality
from cerebralcortex.kernel.datatypes.datapoint import DataPoint
from cerebralcortex.kernel.datatypes.datastream import DataStream
def filter_bad_ecg(ecg: DataStream,
... |
from .apitask import APITask
from thing.models import RefType
class RefTypes(APITask):
name = 'thing.ref_types'
def run(self, url, taskstate_id, apikey_id, zero):
if self.init(taskstate_id, apikey_id) is False:
return
# Fetch the API data
if self.fetch_api(url, {}, use_auth=F... |
from django.conf import settings as dsettings
from django.contrib.auth import models as authModels
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponse, Http404
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template import Requ... |
import sys
from collections import namedtuple
import poppler
import cairo
from os.path import abspath
Point = namedtuple('Point', ['x', 'y'])
Line = namedtuple('Line', ['start', 'end'])
Polygon = namedtuple('Polygon', 'points')
Rectangle = namedtuple('Rectangle', ['top_left', 'bottom_right'])
AnnotationGroup = namedtup... |
"""
Maximum likelihood covariance estimator.
"""
import warnings
import numpy as np
from scipy import linalg
from ..base import BaseEstimator
from ..utils import check_array
from ..utils.extmath import fast_logdet
from ..metrics.pairwise import pairwise_distances
def log_likelihood(emp_cov, precision):
"""Computes ... |
import sys
bsd = '''
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 of conditions and the following disclaimer.
* Redistributio... |
"""Makes sure that files include headers from allowed directories.
Checks DEPS files in the source tree for rules, and applies those rules to
"#include" commands in source files. Any source file including something not
permitted by the DEPS files will fail.
The format of the deps file:
First you have the normal module-... |
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies other than the
Python S... |
""" lazy generator of 2D pharmacophore signature data
"""
from __future__ import print_function
from rdkit.Chem.Pharm2D import SigFactory, Matcher
raise NotImplementedError('not finished yet')
class Generator(object):
"""
Important attributes:
- mol: the molecules whose signature is being worked with
- sigFac... |
import pickle
import unittest
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing im... |
from w3lib.url import parse_data_uri
from scrapy.http import TextResponse
from scrapy.responsetypes import responsetypes
from scrapy.utils.decorators import defers
class DataURIDownloadHandler(object):
lazy = False
def __init__(self, settings):
super(DataURIDownloadHandler, self).__init__()
@defers
... |
from functools import partial
from .primitives import EMPTY
__all__ = ['identity', 'constantly', 'caller',
'partial', 'rpartial', 'func_partial',
'curry', 'rcurry', 'autocurry',
'iffy']
def identity(x):
return x
def constantly(x):
return lambda *a, **kw: x
def caller(*a, **kw):
... |
"""Tools for solving inequalities and systems of inequalities. """
from __future__ import print_function, division
from sympy.core import Symbol
from sympy.sets import Interval
from sympy.core.relational import Relational, Eq, Ge, Lt
from sympy.sets.sets import FiniteSet, Union
from sympy.core.singleton import S
from s... |
import Tkinter as tk
root = tk.Tk()
def noop(): pass
menubar = tk.Menu(root)
filemenu = tk.Menu(menubar)
filemenu.add_command(label="Open", command=noop)
filemenu.add_command(label="Save", command=noop)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu... |
"""Test interact and interactive."""
from __future__ import print_function
from collections import OrderedDict
import nose.tools as nt
import IPython.testing.tools as tt
from IPython.kernel.comm import Comm
from IPython.html import widgets
from IPython.html.widgets import interact, interactive, Widget, interaction
from... |
"""
EasyBuild support for MyMediaLite, implemented as an easyblock
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
from distutils.version import Loo... |
import karamba
drop_txt = None
def initWidget(widget):
# this resets the text to "" so we know we've never
# received anything yet from the other theme
name = karamba.getPrettyThemeName(widget)
print "2.py name: ", name
karamba.setIncomingData(widget, name, "")
karamba.redrawWidget(widget)
expec... |
import sys
import os
print "-------------------------"
print "StegHide Options"
print "-------------------------"
print "Usage Example :"
print ""
print"To embed emb.txt in cvr.jpg: steghide embed -cf cvr.jpg -ef emb.txt"
print ""
print "To extract embedded data from stg.jpg: steghide extract -sf stg.jpg"
cmd1 = os.sy... |
"""BibObject Module providing BibObject prividing features for documents containing text (not necessarily as the main part of the content)"""
import os
import re
from datetime import datetime
from invenio.config import CFG_BIBINDEX_PERFORM_OCR_ON_DOCNAMES
from invenio.legacy.bibdocfile.api import BibDoc, InvenioBibDocF... |
"""Rest alarm notifier with trusted authentication."""
from keystoneclient.v3 import client as keystone_client
from oslo.config import cfg
from six.moves.urllib import parse
from ceilometer.alarm.notifier import rest
cfg.CONF.import_opt('http_timeout', 'ceilometer.service')
cfg.CONF.import_group('service_credentials', ... |
import gtk
import pango
import gobject
from radialnet.bestwidgets.boxes import *
from radialnet.bestwidgets.expanders import BWExpander
from radialnet.bestwidgets.labels import *
from radialnet.bestwidgets.textview import *
import zenmapCore.I18N
PORTS_HEADER = [
_('Port'), _('Protocol'), _('State'), _('Service... |
from robottelo.decorators.func_shared.shared import ( # noqa
shared,
SharedFunctionError,
SharedFunctionException,
) |
from __future__ import with_statement
import os.path
import time
import urllib
import re
import threading
import datetime
import random
import locale
from Cheetah.Template import Template
import cherrypy.lib
import sickbeard
from sickbeard import config, sab
from sickbeard import clients
from sickbeard import history, ... |
import codecs
from ConfigParser import ConfigParser
import os
import subprocess
import sys
import six
import twiggy
from twiggy import log
from twiggy.levels import name2level
from xdg import BaseDirectory
def asbool(some_value):
""" Cast config values to boolean. """
return six.text_type(some_value).lower() in... |
from datetime import datetime, timedelta
import factory
import pytz
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyText
from oauth2_provider.models import AccessToken, Application, RefreshToken
from openedx.core.djangoapps.oauth_dispatch.models import ApplicationAccess
from common.djangoap... |
from spack import *
class Sleef(CMakePackage):
"""SIMD Library for Evaluating Elementary Functions,
vectorized libm and DFT."""
homepage = "http://sleef.org"
url = "https://github.com/shibatch/sleef/archive/3.2.tar.gz"
version('3.2', '459215058f2c8d55cd2b644d56c8c4f0') |
import httplib as http
import mock
from nose.tools import * # noqa
from boto.exception import S3ResponseError
from framework.auth import Auth
from tests.base import get_default_metaschema
from tests.factories import ProjectFactory, AuthUserFactory
from website.addons.base import testing
from website.addons.s3.tests.ut... |
import os
import time
import unittest
from multiprocessing import Process
import signal
import numpy
import paddle.fluid as fluid
import paddle.fluid.layers as layers
from paddle.fluid.layers.io import ListenAndServ
from paddle.fluid.layers.io import Recv
from paddle.fluid.layers.io import Send
import paddle.fluid.laye... |
import re
from django import template
from django import forms
register = template.Library()
def _process_field_attributes(field, attr, process):
# split attribute name and value from 'attr:value' string
params = attr.split(':', 1)
attribute = params[0]
value = params[1] if len(params) == 2 else ''
... |
import mock
import six
from designateclient import exceptions as designate_exceptions
from designateclient import v1 as designate_client
from heat.common import exception as heat_exception
from heat.engine.clients.os import designate as client
from heat.tests import common
class DesignateDomainConstraintTest(common.Hea... |
from __future__ import absolute_import, division, print_function
from lxml import etree
import os
def open_xml_file(filename, mode):
"""Opens an XML file for use.
:param filename: XML file to create file from
:param mode: file mode for open
:return:
"""
base = os.path.dirname(__file__) + '/xml_t... |
class EmptyResult(object):
'''
Null Object pattern to prevent Null reference errors
when there is no result
'''
def __init__(self):
self.status = 0
self.body = ''
self.msg = ''
self.reason = ''
def __nonzero__(self):
return False
class HapiError(ValueError... |
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from help.models import ConditionsChapter, FAQ
def faqs(request):
extra_context = {}
extra_context['faqs'] = FAQ.objects.all()
return render_to_response('help/faqs.html',
extra_co... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pants.backend.jvm.tasks.jvm_tool_task_mixin import JvmToolTaskMixin
from pants.base.exceptions import TaskError
from pants.java import util
from pants.ja... |
"""Tests for supervisor.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import os
import shutil
import time
import uuid
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.core.protobuf ... |
import six
import webob
from nova.api.openstack.compute.schemas.v3 import flavors_extraspecs
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import exception
from nova.i18n import _
from nova import objects
from nova import utils
ALIAS = 'os-flavor... |
"""Bayesian NN using factorized VI (Bayes By Backprop. Blundell et al. 2014).
See https://arxiv.org/abs/1505.05424 for details.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from absl import flags
from bandits.... |
r"""Reverses xxd dump from to binary file
This script is used to convert models from C++ source file (dumped with xxd) to
the binary model weight file and analyze it with model visualizer like Netron
(https://github.com/lutzroeder/netron) or load the model in TensorFlow Python
API
to evaluate the results in Python.
The... |
from tests import BaseTestCase
import mock
import time
from redash.models import User
from redash.authentication.account import invite_token
from tests.handlers import get_request, post_request
class TestInvite(BaseTestCase):
def test_expired_invite_token(self):
with mock.patch('time.time') as patched_time:... |
"""
==============
Blob Detection
==============
Blobs are bright on dark or dark on bright regions in an image. In
this example, blobs are detected using 3 algorithms. The image used
in this case is the Hubble eXtreme Deep Field. Each bright dot in the
image is a star or a galaxy.
Laplacian of Gaussian (LoG)
---------... |
from optparse import make_option
from webkitpy.common.host import Host
from webkitpy.tool.multicommandtool import MultiCommandTool
from webkitpy.tool import commands
class WebKitPatch(MultiCommandTool, Host):
global_options = [
make_option("-v", "--verbose", action="store_true", dest="verbose", default=Fals... |
"""
Filters bad words on outgoing messages from the bot, so the bot can't be made
to say bad words.
"""
import supybot
import supybot.world as world
__version__ = ""
__author__ = supybot.authors.jemfinch
__contributors__ = {}
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we'r... |
project_slug = '{{ cookiecutter.project_slug }}'
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!' |
"""
This plugin handles various plugin-related things, such as getting help for
a plugin, getting a list of the loaded plugins, and searching and downloading
plugins from supybot.com.
"""
import supybot
import supybot.world as world
__version__ = "%%VERSION%%"
__author__ = supybot.authors.jemfinch
__contributors__ = {
... |
from datetime import datetime
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
Series,
_testing as tm,
)
def test_split(any_string_dtype):
values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
result = values.str.s... |
import sys, re
import cairo
import numpy
import threading
import math
from io import BytesIO
from ginga import ImageView
from ginga.cairow.CanvasRenderCairo import CanvasRenderer
class ImageViewCairoError(ImageView.ImageViewError):
pass
class ImageViewCairo(ImageView.ImageViewBase):
def __init__(self, logger=No... |
"""
logbook._fallback
~~~~~~~~~~~~~~~~~
Fallback implementations in case speedups is not around.
:copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
from itertools import count
from logbook.helpers import get_iterator_next_method
from logbook.concur... |
from twisted.python import log
from twisted.internet import reactor, defer
from buildbot import util
if False: # for debugging
debuglog = log.msg
else:
debuglog = lambda m: None
class BaseLock:
"""
Class handling claiming and releasing of L{self}, and keeping track of
current and waiting owners.
... |
"""Entry point for running stress tests."""
import argparse
import threading
from grpc.beta import implementations
from six.moves import queue
from src.proto.grpc.testing import metrics_pb2
from src.proto.grpc.testing import test_pb2
from tests.interop import methods
from tests.qps import histogram
from tests.stress im... |
from __future__ import print_function
import unittest
import numpy as np
import pydrake
import os.path
class TestRBTCoM(unittest.TestCase):
def testCoM0(self):
r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(),
"examples/Pendulum/Pendulum.urdf"))
... |
import unittest
from mock import Mock
from biicode.common.model.content import Content
from biicode.common.model.content import ContentDeserializer
from biicode.common.model.content import content_diff
from biicode.common.exception import BiiSerializationException
from biicode.common.model.id import ID
class ContentTes... |
from kolibri.auth.api import KolibriAuthPermissions, KolibriAuthPermissionsFilter
from kolibri.content.api import OptionalPageNumberPagination
from rest_framework import filters, viewsets
from .models import ContentRatingLog, ContentSessionLog, ContentSummaryLog, UserSessionLog
from .serializers import ContentRatingLog... |
import logging
from pycsw.core import util
from pycsw.core.etree import etree
LOGGER = logging.getLogger(__name__)
class OAIPMH(object):
"""OAI-PMH wrapper class"""
def __init__(self, context, config):
LOGGER.debug('Initializing OAI-PMH constants')
self.oaipmh_version = '2.0'
self.namesp... |
"""
Menu utilities.
"""
from fnmatch import fnmatch
from django.utils.importlib import import_module
from django.core.urlresolvers import reverse
from wpadmin.utils import (
get_wpadmin_settings, get_admin_site, get_admin_site_name)
def get_menu_cls(menu, admin_site_name='admin'):
"""
menu - menu name ('top... |
import email.utils
import errno
import hashlib
import mimetypes
import os
import re
import base64
import binascii
import math
from hashlib import md5
import boto.utils
from boto.compat import BytesIO, six, urllib, encodebytes
from boto.exception import BotoClientError
from boto.exception import StorageDataError
from bo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.