code stringlengths 1 199k |
|---|
"""OpenStack logging handler.
This module adds to logging functionality by adding the option to specify
a context object when calling the various log methods. If the context object
is not specified, default formatting is used. Additionally, an instance uuid
may be passed as part of the log message, which is intended t... |
import abc
import codecs
import functools
import os.path
import re
import sys
import weakref
import ldap
import ldap.filter
import ldappool
import six
from keystone import exception
from keystone.i18n import _
from keystone.openstack.common import log
LOG = log.getLogger(__name__)
LDAP_VALUES = {'TRUE': True, 'FALSE': ... |
import cv2
import numpy as np
import time
window_name = 'Mask'
cv2.namedWindow(window_name)
cv2.createTrackbar('min_1', window_name, 0, 255, lambda x: None)
cv2.createTrackbar('max_1', window_name, 0, 255, lambda x: None)
cv2.createTrackbar('min_2', window_name, 0, 255, lambda x: None)
cv2.createTrackbar('max_2', windo... |
import base64
import copy
import datetime
import functools
import iso8601
import os
import string
import tempfile
import fixtures
from oslo.config import cfg
from nova.api.ec2 import cloud
from nova.api.ec2 import ec2utils
from nova.api.ec2 import inst_state
from nova.api.metadata import password
from nova.compute impo... |
from __future__ import absolute_import
import pdb
try:
import pam
except ImportError:
pam = None
import PAM
from keystone import identity
from keystone import identity
import pdb
from .cas_dance import *
from urlparse import urlparse, urlunparse, urljoin
from urllib import urlencode
import urllib2
from urll... |
"""pa link unique
Revision ID: 3101ec185bdf
Revises: 51dd553fdf8b
Create Date: 2015-11-11 08:17:53.589389
"""
revision = '3101ec185bdf'
down_revision = '51dd553fdf8b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_unique_constr... |
from setuptools import setup
setup(
name='fedora-api',
version='1.0.3',
packages=['fedora', 'fedora.rest'],
url='https://github.com/dans-er/fedora-rest',
license='Apache License Version 2.0',
author='hvdb',
author_email='',
description='scripting fedora commons',
install_requires=['r... |
__author__="panos"
__date__ ="$Jun 29, 2016 6:10:32 PM$"
import pika, json
import os, threading, time, signal, sys
if __name__ == "__main__":
def fail():
sys.stdout.write("False")
sys.stdout.flush()
os._exit(0)
threading.Timer(120, fail).start()
credentials = pika.PlainCredentials('g... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from FrontEnd import api
from FrontEnd import views
from FrontEnd import postviews
from FrontEnd import sitemaps
from FrontEnd import tasks
from django.http import HttpResponse
admin.autodiscover()
sitemaps = {
'staticpages': sitem... |
import pytest
import sys
from .test_base_class import TestBaseClass
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
from aerospike import exception as e
except:
print("Please install aerospike python client.")
sys.exit(1)
class TestOperateOrdered(object):
def setup_class(cls):
... |
"""
An example demonstrating bisecting k-means clustering.
Run with:
bin/spark-submit examples/src/main/python/ml/bisecting_k_means_example.py
"""
from __future__ import print_function
from pyspark.ml.clustering import BisectingKMeans
from pyspark.ml.evaluation import ClusteringEvaluator
from pyspark.sql import Spark... |
DJANGO_APPS = ['pig']
NICE_NAME = 'Pig Editor'
MENU_INDEX = 12
ICON = '/pig/static/art/icon_pig_48.png'
REQUIRES_HADOOP = False
IS_URL_NAMESPACED = True |
from UI import *
from iohandler import *
GAME_WIDTH = 100
GAME_HEIGHT = 20
class Terrain():
SIDE_LIMIT = '|'
HORIZON_LIMIT = '-'
MIDDLE = ' '
def generate(self,x,y):
map = {}
for trow in range(0,y):
col = {}
for tcol in range(0,x):
if trow == 0 or ... |
import livescores-base
from bs4 import BeautifulSoup
class LSTennis(LSBase):
def fetch_page(self):
u="http://www.livescore.com/tennis/"
s = super(LSTennis, self).fetch_page(u)
return s
def process_query(self,query):
html=self.fetch_page()
#attempt to search single query first
def search_page(self,html):
... |
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
from itertools import chain
from ..._compat import unicode_compatible
from ...utils import cached_property
from ._sentence import Sentence
@unicode_compatible
class Paragraph(object):
__slots__ = (
"_sen... |
"""Module containing data providers for TextProperty.
"""
from soc.modules.seeder.logic.providers.string import StringProvider
from soc.modules.seeder.logic.providers.string import RandomPhraseProvider
import random
class TextProvider(StringProvider):
"""Base class for all data providers that return text.
"""
pas... |
class Solution:
"""
@param A : a list of integers
@param target : an integer to be searched
@return : an integer
"""
def search(self, A, target):
# write your code here
length = len(A)
if length == 0:
return -1
start = 0
end = length - 1
... |
"""
Implementation of the shifted beta geometric (sBG) model from "How to Project Customer Retention" (Fader and Hardie 2006)
http://www.brucehardie.com/papers/021/sbg_2006-05-30.pdf
Apache 2 License
"""
from math import log
import numpy as np
from scipy.optimize import minimize
from scipy.special import hyp2f1
__autho... |
"""
mothership.kv
Package for interacting with the KV store in mothership
"""
from sqlalchemy import or_, desc, MetaData
import mothership
from mothership.mothership_models import *
class KVError(Exception):
pass
def new(fqdn, key, value):
"""
Constructor that takes a host.realm.site style fqdn.
... |
"""
Cloud-Custodian Lambda Entry Point
Mostly this serves to load up the policy and dispatch
an event.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import uuid
import logging
import json
from c7n.policy import PolicyCollection
from c7n.resources import load_resources
... |
for jj in [5,4,3,2,1] :
print jj
print 'Blastoff, JJ!' |
from oslo.config import cfg
import taskflow.engines
from taskflow.patterns import linear_flow
from taskflow.utils import misc
from cinder import exception
from cinder import flow_utils
from cinder.i18n import _
from cinder.openstack.common import log as logging
from cinder.openstack.common import timeutils
from cinder.... |
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon'
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'slackpack'
copyright = u'2015, slackpack authors'
author = u'slackpack authors'
version = '1.0.0'
release = '1.0.0'
language = None
exclude_patterns = ['_build']
p... |
from sqlalchemy import *
meta = MetaData()
stacks = Table(
'stacks', meta,
Column('id', String(36), primary_key=True),
Column('tenant', String(255)),
Column('stack_id', String(36)),
Column('supported', Boolean)
)
def upgrade(migrate_engine):
meta.bind = migrate_engine
stacks.create()
def dow... |
import collections
import re
import testtools
from tempest.common import debug
from tempest.common.utils import data_utils
from tempest import config
from tempest import exceptions
from tempest.openstack.common import log as logging
from tempest.scenario import manager
from tempest.services.network import resources as ... |
from .formatado import ServicoEmailFormatado
from .gmail import ServicoEmailGmail
from .formatadores import *
formatadores = [
usuario_cadastrado,
usuario_alterado,
usuario_removido,
recurso_inutilizavel,
agendamento_confirmado,
agendamento_cancelado
]
class ServicoEmailConsole(ServicoEmailForma... |
import json
from django.test import override_settings
from orchestra.models import Step
from orchestra.models import Task
from orchestra.models import Project
from orchestra.models import TaskAssignment
from orchestra.tests.helpers import OrchestraTransactionTestCase
from orchestra.tests.helpers.fixtures import setup_m... |
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='notification.p... |
from __future__ import absolute_import
from traits.api import Dict
import os
from pychron.paths import paths
from pychron.core.helpers.filetools import unique_path
from pychron.managers.manager import Manager
from pychron.core.helpers.datetime_tools import generate_datetimestamp, time_generator
class DataManager(Manage... |
try:
import httplib
except ImportError:
import http.client as httplib
try:
import urllib.parse as urllib
except ImportError:
import urllib
import sys
import os
def main(args):
server = os.environ.get("SERVER", "localhost:8888")
for arg in args:
if arg.endswith('.js'):
path = '/js'
... |
import argparse
import datetime
import os, sys
import tensorflow as tf
from disparitynet import DisparityNet
from posenet import PoseNet
from utils import pixel_coord, ssim_loss, smooth_loss, bilinear_sampler, forwardproject, backproject, disp_to_depth
parser = argparse.ArgumentParser(description="Disparity Project")
p... |
import json
from falcon import HTTP_200
from oslo_config import cfg
from oslo_log import log as logging
from armada.handlers.tiller import Tiller as tillerHandler
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class Status(object):
def on_get(self, req, resp):
'''
get tiller status
'''
... |
"""Helper classes for Google Assistant integration."""
from __future__ import annotations
from abc import ABC, abstractmethod
from asyncio import gather
from collections.abc import Mapping
import logging
import pprint
from aiohttp.web import json_response
from homeassistant.components import webhook
from homeassistant.... |
"""
Device level CLI commands
"""
from optparse import make_option
from cmd2 import Cmd, options
from simplejson import dumps
from cli.table import print_pb_as_table, print_pb_list_as_table
from cli.utils import print_flows, pb2dict, enum2name
from voltha.protos import third_party
_ = third_party
from voltha.protos imp... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
import numpy
try:
numpy_include = numpy.get_include()
except AttributeError:
numpy_include = numpy.get_numpy_include()
try:
from Cython.Distutils import build_ext
use_... |
import random
import copy
import threading
from collections import defaultdict
import logging
import boto3
import botocore
from botocore.config import Config
from ray.autoscaler.node_provider import NodeProvider
from ray.autoscaler.tags import TAG_RAY_CLUSTER_NAME, TAG_RAY_NODE_NAME, \
TAG_RAY_LAUNCH_CONFIG, TAG_RA... |
"""Raspberry Pi GPIO Sensor for AntEvents.
Allows digital (1/0 output) sensors to be connected straight to the
Raspberry Pi (ADC needed for the Pi to take analogue output).
This sensor class can only be used with sensors which send their output straight
to the Raspberry Pi GPIO pins. For sensors which use I2C or SPI, w... |
from model import Model
from datetime import datetime, date, timedelta
from random import randint
from google.cloud import datastore
class Courses(Model):
def __init__(self, cid=-1):
self.cid = cid
self.now = datetime.time(datetime.now())
self.today = date.today()
self.ds = self.get_... |
from sqlalchemy.orm import subqueryload
from wsme.exc import ClientSideError
from storyboard._i18n import _
from storyboard.common import exception as exc
from storyboard.db.api import base as api_base
from storyboard.db.api import users
from storyboard.db import models
def _entity_get(id, session=None):
if not ses... |
"""Support to interface with Sonos players."""
import asyncio
import datetime
import functools as ft
import logging
import socket
import urllib
import async_timeout
import requests
import voluptuous as vol
from homeassistant.components.media_player import (
PLATFORM_SCHEMA, MediaPlayerDevice)
from homeassistant.com... |
from parler.tests import * |
import datetime
import sys
from PyPDF2 import PdfFileWriter, PdfFileReader
__author__ = 'Leonardo F. Cardoso'
verbose_mode = False # Used for debug
def debug(param):
try:
if verbose_mode:
tstamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
print("[{0}] [DEBUG]\t{1}".fo... |
import logger
import sh
import sys
import codes
lgr = logger.init()
class Handler():
def get_gems(self, gems, dir, rbenv=False):
"""downloads a list of ruby gems
:param list gems: gems to download
:param string dir: directory to download gems to
"""
gem = sh.Command('{0}/bin/... |
from __future__ import absolute_import, division, print_function, unicode_literals
class HGVSError(Exception):
pass
class HGVSParseError(HGVSError):
pass
class HGVSInvalidIntervalError(HGVSError):
pass
class HGVSInvalidVariantError(HGVSError):
pass
class HGVSValidationError(HGVSError):
pass
class HG... |
extensions = [
'reno.sphinxext',
'openstackdocstheme',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Zaqar Release Notes'
copyright = u'2015, Zaqar Developers'
version = ''
release = ''
exclude_patterns = []
pygments_style = 'native'
html_theme = 'openstackdocs'
htmlh... |
from urllib.parse import urlparse
url = 'http://netloc/path;param?query=arg#frag'
parsed = urlparse(url)
print(parsed) |
"""Distribution adapters for (soft) round functions."""
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_compression.python.distributions import deep_factorized
from tensorflow_compression.python.distributions import helpers
from tensorflow_compression.python.distributions import uniform_noi... |
from nova.scheduler.filters import isolated_hosts_filter
from nova import test
from nova.tests.scheduler import fakes
class TestIsolatedHostsFilter(test.NoDBTestCase):
def setUp(self):
super(TestIsolatedHostsFilter, self).setUp()
self.filt_cls = isolated_hosts_filter.IsolatedHostsFilter()
def _d... |
__author__ = 'lqrz'
import codecs
import logging
import glob
import sys
logger = logging.getLogger('')
hdlr = logging.FileHandler('decompoundingEvaluation.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
if _... |
"""
Copyright 2017 Deepgram
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distribut... |
try:
import argcomplete
except ImportError:
argcomplete = None
import argparse
import os.path
from . import parse_template
DESCRIPTION = 'Converts an HTML5 boilerplate template into a Jinja2 template.'
if argcomplete:
def directory_completer(prefix, **kwargs):
dirname = os.path.dirname(prefix)
... |
"""
SQLAlchemy models for baremetal data.
"""
import json
import urlparse
from oslo.config import cfg
from sqlalchemy import Column, ForeignKey
from sqlalchemy import Integer, Index
from sqlalchemy import schema, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import TypeDecorator, ... |
import os
import logging
log = logging.getLogger(__name__)
def action(ns):
"""
Create base image with lvm.
"""
if not ns.force and os.path.isfile(ns.image_path):
raise Exception("path already exists: {0}".format(ns.image_path))
with open(ns.image_path, "w") as f:
f.truncate(ns.size.s... |
import os
from distutils.command.build import build
from django.core import management
from setuptools import setup, find_packages
try:
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
except Exception:
long_description = ''
class Custo... |
"""Test the allgather API on a distributed Ray cluster."""
import pytest
import ray
import numpy as np
import torch
from ray.util.collective.types import Backend
from ray.util.collective.tests.cpu_util import create_collective_workers, \
init_tensors_for_gather_scatter
@pytest.mark.parametrize("backend", [Backend.G... |
"""
WSGI config for storyboard project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... |
from __future__ import print_function
import os
import sys
import textwrap
from tracing import Tracing
from buck_tool import BuckTool, JAVA_MAX_HEAP_SIZE_MB, platform_path
from buck_tool import BuckToolException, RestartBuck
from subprocutils import check_output, which
import buck_version
RESOURCES = {
"abi_process... |
import pytest
import pytz
from datetime import date, datetime, time
from django.utils import timezone
from contact.tests.factories import ContactFactory
from crm.tests.factories import TicketFactory
from dateutil.relativedelta import relativedelta
from invoice.models import InvoiceError, TimeRecord
from invoice.tests.f... |
"""
This module implements clipboard handling on Windows using ctypes.
"""
import time
import contextlib
import ctypes
from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar
from .exceptions import PyperclipWindowsException
class CheckedCall(object):
def __init__(self, f):
super(CheckedCall, sel... |
"""
Produce the k-mer abundance distribution for the given file, without
loading a prebuilt k-mer counting table.
% python scripts/abundance-dist-single.py <data> <histout>
Use '-h' for parameter help.
"""
import os
import sys
import khmer
import threading
import textwrap
from khmer.khmer_args import (build_counting_ar... |
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-01-14
Last_modify: 2016-01-14
******************************************
'''
'''
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the ran... |
import functools, glob, librosa
import scipy.io as sio
from scikits.audiolab import Sndfile, Format
%cd stan/
import samples_parser
specshow = functools.partial(imshow, cmap=cm.hot_r, aspect='auto', origin='lower', interpolation='nearest')
fig = functools.partial(figure, figsize=(16,4))
def logspec(X, amin=1e-10, dbdow... |
import itertools
import os
import re
import stat
import tempfile
from mock import call, patch
from oslo_concurrency.processutils import UnknownArgumentError
from testtools import ExpectedException
from trove.common import exception
from trove.common.stream_codecs import (
IdentityCodec, IniCodec, PropertiesCodec, Y... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from contextlib import contextmanager
from pants.fs.archive import archiver_for_path, create_archiver
from pants.util.contextutil import temporary_dir
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
cl... |
"""
Network extension implementations
"""
from cliff import hooks
from openstack.network.v2 import network as network_sdk
from openstack import resource
from openstackclient.network.v2 import network
from osc_lib.cli import parseractions
from openstackclient.i18n import _
_get_attrs_network_new = network._get_attrs_net... |
import os
import socket
import sys
from subprocess import CalledProcessError, check_call, check_output
def get_var_assert_set(name):
if name not in os.environ:
print('ERROR: "{}" must be set'.format(name))
sys.exit(1)
return os.environ[name]
def write_str(filename, contents):
with open(filen... |
import pytest
from fixture.application import Application
from fixture.db import DbFixture
import json
import jsonpickle
import os.path
import importlib
fixture = None
target = None
def load_config(file):
global target
if target is None:
config_file = os.path.join(os.path.dirname(os.path.abspath(__file_... |
import random
def byte_range(first, last):
return list(range(first, last+1))
first_values = byte_range(0x00, 0x7F) + byte_range(0xC2, 0xF4)
trailing_values = byte_range(0x80, 0xBF)
def _utf8_char():
first = random.choice(first_values)
if first <= 0x7F:
return bytes([first])
elif first <= 0xDF:
... |
"""
Logging module for the Topology Modular Framework.
"""
import logging
from abc import ABCMeta
from os.path import join
from inspect import stack
from collections import OrderedDict
from distutils.dir_util import mkpath
from weakref import WeakValueDictionary
from datetime import datetime
from six import add_metacla... |
from oslo_log import log as logging
import nova.conf
from nova import exception
from nova.i18n import _, _LI
import nova.image.download.base as xfer_base
import nova.virt.libvirt.utils as lv_utils
CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
class FileTransfer(xfer_base.TransferBase):
desc_required_keys ... |
"""Test http_helpers utility functions."""
import httplib2
import os
import unittest.mock as mock
import unittest.mock as mock
import unittest
from google.cloud.forseti.common.util import http_helpers
from tests.unittest_utils import ForsetiTestCase
DUMMY_URL = "http://127.0.0.1"
UA_KEY = "user-agent"
class MockRespons... |
from __future__ import print_function
systemd_template="""
[Unit]
Description={repo} {image} container
After=docker.service
Requires=docker.service
PartOf=docker.service
[Service]
TimeoutStartSec=0
ExecStartPre=/usr/bin/docker run --name {repo}-{image} -d {options} {repo}/{image}:{version}
ExecStart=/usr/bin/docker sta... |
"""Pooling modules."""
from jax import lax
import jax.numpy as jnp
import numpy as np
def pool(inputs, init, reduce_fn, window_shape, strides, padding):
"""Helper function to define pooling functions.
Pooling functions are implemented using the ReduceWindow XLA op.
NOTE: Be aware that pooling is not generally dif... |
from touchdown.tests.stubs.aws import SubnetStubber
from .fixture import AwsFixture
class SubnetFixture(AwsFixture):
def __init__(self, goal, vpc):
super(SubnetFixture, self).__init__(goal, vpc.account)
self.vpc = vpc
def __enter__(self):
self.subnet = self.fixtures.enter_context(
... |
"""TVM Runtime NDArray API.
tvm.ndarray provides a minimum runtime array API to test
the correctness of the program.
"""
from __future__ import absolute_import as _abs
import numpy as _np
from ._ffi.ndarray import TVMContext, TVMType, NDArrayBase
from ._ffi.ndarray import context, empty
from ._ffi.ndarray import _set_c... |
import logging
import os
import tokenize
from io import StringIO
from typing import Dict, Tuple
from pants.base.build_file_target_factory import BuildFileTargetFactory
from pants.base.exceptions import UnaddressableObjectError
from pants.base.parse_context import ParseContext
from pants.build_graph.build_file_aliases i... |
from os.path import dirname
import numpy as np
from ..log import get_logger
logger = get_logger()
from .. import os as xm_os
from ..imprt import preset_import
def text_as_image(
text, imsize=256, thickness=2, dtype='uint8', outpath=None,
quiet=False):
"""Rasterizes a text string into an image.
T... |
"""pptp vpn
Revision ID: 4117d142767a
Revises: 105e42d08d72
Create Date: 2014-02-24 19:55:31.809052
"""
revision = '4117d142767a'
down_revision = '105e42d08d72'
migration_for_plugins = [
'neutron.plugins.ml2.plugin.Ml2Plugin'
]
from alembic import op
import sqlalchemy as sa
from neutron.db import migration
def upgr... |
"""Define classes that describe external data sources.
These are used for both Table.externalDataConfiguration and
Job.configuration.query.tableDefinitions.
"""
from __future__ import absolute_import
import base64
import copy
from typing import FrozenSet, Iterable, Optional, Union
from google.cloud.bigquery._help... |
from .check_json import CheckJSON
class OrganizationData:
def __init__(self, location):
self.organization_data = CheckJSON('OrganizationData', location).key_valid()
# Full Response
def info(self):
"""Return all organization data as an object"""
return self.organization_data
# Individual Fields
def home(self)... |
import copy
import uuid
import mock
from testtools import matchers
from oslo_config import cfg
from oslotest import mockpatch
from keystone import exception
from keystone.tests import unit
from keystone.tests.unit.ksfixtures import database
CONF = cfg.CONF
class TestResourceManagerNoFixtures(unit.SQLDriverOverrides, un... |
'''
form L.P. page 980
'''
class Set:
def __init__(self, value = []):
self.data = []
self.concat(value)
def intersect(self, other):
res = []
for x in self.data:
if x in other:
res.append(x)
return Set(res)
def union(self, other):
re... |
import abc
from typing import Awaitable, Callable, Optional, Sequence, Union
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core ... |
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import descriptor_pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='proto_indexRequestInfo.proto',
package='',
serialized_pb='\n\x1cprot... |
"""
Support for Modbus switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.modbus/
"""
import logging
import voluptuous as vol
import homeassistant.components.modbus as modbus
from homeassistant.const import CONF_NAME, CONF_SLAVE
from homeassi... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0004_auto_20170824_2308'),
]
operations = [
migrations.AlterField(
model_name='article',
name='attachids',
fi... |
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('delivery', '0031_auto_20151026_1021'),
]
operations = [
migrations.AlterField(
model_name='delivery',
name='creat... |
"""Support for Sesame, by CANDY HOUSE."""
from typing import Callable
import pysesame2
import voluptuous as vol
from homeassistant.components.lock import PLATFORM_SCHEMA, LockEntity
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_ID,
CONF_API_KEY,
STATE_LOCKED,
STATE_UNLOCKED,
)
im... |
from django.db import models
from django.contrib.auth.models import User
import datetime
class Member(models.Model):
def __str__(self):
return str(self.user)
def name(self):
return self.user.username
user = models.OneToOneField(User, primary_key=True,
help_text='Basic account information, username, pa... |
from setuptools import setup, find_packages
setup(
name='csd',
version='0.0',
description='csd',
long_description='',
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Framework :: Pyramid"... |
import os
import sys
import logging as log
from getopt import getopt
import ex.util as eu
from OMOP import OMOP
import base
eu.InitLog()
def usage():
print('''summarize the OMOP data set
python summary.py --modifier={''} --folder={''} --simulated --help
''');
sys.exit(1);
try: options=dict(getopt(sys.ar... |
''' Manages server handler threading between Raspberry Pi, laptop and iPhone.
'''
import threading
import enum
class ThreadManager:
''' Manages the required threads for accessing devices using non-blocking
thread locks. Every device operation should go through the thread manager.
'''
def __init__(self):
''' Initi... |
class BTree:
class Node:
def __init__(self):
self.sons = []
self.keys = []
def __repr__(self):
return 'Node' + str(self.keys) + str(self.sons)
def _lower_bound(self, key):
b = 0
e = len(self.sons) - 1
while b < e:
... |
"""
OpenStack Cinder driver - interface to Open vStorage Edge
- uses qemu-img calls (requires qemu & libvirt-bin packages from openvstorage.com repo)
sudo mkdir -p /opt/OpenvStorage/
sudo git clone https://github.com/openvstorage/framework-cinder-plugin.git /opt/OpenvStorage/
cd /opt/OpenvStorage/
sudo git checkout ovs... |
"""ResNet model definition."""
import functools
from model.resnet_util import basic_stack1
from model.resnet_util import basic_stack2
from model.resnet_util import basic_stack3
from model.resnet_util import bottleneck_stack1
from model.resnet_util import bottleneck_stack2
from model.resnet_util import ResNet
from model... |
import argparse
import logging
import os
import sys
import re
import json
from collections import OrderedDict
def initialize_logger(logfile, args):
logger = logging.getLogger('clonotype_merge')
loglevel = logging.INFO
logger.setLevel(loglevel)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)... |
pkgs = {
"/usr/lib/ruby/gems/2.7.0/specifications/bundler-2.1.4.gemspec": {
"name": "bundler",
"lics": ["MIT"],
"versions": ["2.1.4"],
"latest": "2.1.4",
"origins": [
"André Arko",
"Samuel Giddins",
"Colby Swandale",
"Hiroshi Sh... |
from abc import ABCMeta, abstractmethod
class BaseAuthenticator(object):
__metaclass__ = ABCMeta
@abstractmethod
def authenticate(self):
pass |
from unittest import TestCase
from stock import Stock
class TestStock(TestCase):
stock = Stock(key='O', name='Realty Income', currency='USD')
fund = Stock(key='AVZ-ZRO', name='Avanza Zero', currency='SEK', is_stock=0)
def test_0_get_total_price(self):
self.assertEqual(self.stock.get_total_price(), 0... |
import urlparse
from dirtyfields import DirtyFieldsMixin
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from django.contrib.contenttypes.fields import GenericRelation
from framework.postcommit_tasks.handlers import enqueue_postcommit_task
from framewor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.