code stringlengths 1 199k |
|---|
from __future__ import absolute_import
from typing import Any, Dict, List, Optional, Text, Tuple
from django.utils.translation import ugettext as _
from django.db.models import Q
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from zerver.models import UserProfile, get_user_profile_by... |
"""MeCab based Segmenter.
Word segmenter module powered by `MeCab <https://github.com/taku910/mecab>`_.
You need to install MeCab to use this segmenter.
The easiest way to install MeCab is to run :code:`make install-mecab`. The
script will download source codes from GitHub and build the tool. It also setup
`IPAdic <htt... |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('admin', 'c0710204@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'admin.db', # Or path to database file ... |
from ..PulsePrimitives import *
from ..Compiler import compile_to_hardware
from ..PulseSequencePlotter import plot_pulse_files
from .helpers import create_cal_seqs
from itertools import product
import operator
from ..ControlFlow import *
from ..TdmInstructions import *
from functools import reduce
from typing import It... |
import sys
import StringIO
import argparse
from redmine import Redmine
from redmine import exceptions as redmine_exceptions
class ProjectTree(object) :
def __init__(self, allProjects ) :
self._projects = list(allProjects)
self._projectsByName = {} # name -> project
for project in self._proje... |
import unittest
import logging
from domaincrawl.link_aggregator import LinkAggregator
from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme
from domaincrawl.site_graph import SiteGraph
from domaincrawl.util import URLNormalizer, extract_domain_port
class LinkAggregatorTest(unittest.TestCase):
... |
"""Matrix compression operator.
Helper functions to have an automated process to take any matrix compression
algorithm and create a tensorflow operator that can be applied on a tensorflow
matrix variable to compress it on the fly during training.
The class MatrixCompressorInferface can be used to implement any matrix
c... |
import factory
from mobile_push.db import Session, Topic
class TopicFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta(object):
model = Topic
sqlalchemy_session = Session
name = factory.Sequence(lambda n: 'topic-%s' % n)
arn = factory.Sequence(lambda n: 'topic-arn-%s' % n) |
from setuptools import setup
setup(
name='soundcurl',
version='0.1.0',
description='A command line utility for downloading songs from SoundCloud.',
author='Jeremy McKibben-Sanders',
author_email='jmckib2+soundcurl@gmail.com',
url='https://github.com/jmckib/soundcurl',
package_dir={'': 'src'}... |
from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Column(Text, nullable=Fa... |
class stamp:
def __init__(this, time, weight):
this.time = long(time)
this.weight = long(weight)
def weighted_time(this):
return this.time * this.weight
def minimum(x, y):
if x < y:
return x
else:
return y
def maximum(x, y):
if x > y:
return x
else... |
'''
Create 2 VMs with same image. Then commit 2 new images from 2 VMs.
@author: Youyk
'''
import time
import os
import apibinding.inventory as inventory
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.op... |
from absl import app
from iree.tf.support import tf_test_utils
import numpy as np
import tensorflow.compat.v2 as tf
class LinspaceModule(tf.Module):
def __init__(self):
pass
@tf.function(input_signature=[
tf.TensorSpec([], tf.float32),
tf.TensorSpec([], tf.float32)
])
def linspace(self, start, s... |
"""Image operations."""
from __future__ import absolute_import as _abs
from . import _make
def resize(data,
size,
layout="NCHW",
method="bilinear",
align_corners=True,
out_dtype=None):
"""Image resize operator.
This operator takes data as input and does 2D ... |
from google.cloud import dialogflow_v2
async def sample_update_conversation_profile():
# Create a client
client = dialogflow_v2.ConversationProfilesAsyncClient()
# Initialize request argument(s)
conversation_profile = dialogflow_v2.ConversationProfile()
conversation_profile.display_name = "display_n... |
from asynctnt_queue import Queue, Tube
from tests import BaseTarantoolTestCase
class QueueTestCase(BaseTarantoolTestCase):
async def test__queue_create(self):
q = Queue(self.conn)
self.assertEqual(q.conn, self.conn, 'conn valid')
def test__queue_get_tube(self):
q = Queue(self.conn)
... |
import django
import sys
from itertools import chain
from django import forms
from django.conf import settings
from django.db.models.query import QuerySet
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.html import conditional_escape, escape
from django... |
import sys
from datetime import datetime
import calendar
import subprocess
import os.path
R = 'http://www.bom.gov.au/web03/ncc/www/awap'
WGET = '/usr/bin/wget'
vars = {
'rain/day' : R+'/rainfall/totals/daily/grid/0.05/history/nat',
'rain_rmse/day' : R+'/rainfall/rmse/daily/grid/0.05/history/nat',
'rain_recal/day'... |
# Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 ... |
"""
Forms for managing metadata.
"""
import json
from django.forms import ValidationError
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard.api import glance
from openstac... |
"""
URL routing for blogs, entries and feeds
"""
from django.conf.urls.defaults import patterns, url
from django.conf import settings
from feeds import LatestEntriesByBlog, LatestEntries #, EntryComments
from models import Blog
from views import generic_blog_entry_view, blog_detail
from viewpoint.settings import USE_CA... |
"""A module to deal with processes."""
import datetime
def uptime(asstr = False):
"""Get system uptime>"""
raw = ''
with open('/proc/uptime','r') as ut:
raw = ut.read()[:-1]
uts = list(map(lambda x: int(float(x)), raw.split(' ')))
if asstr:
uts = str(datetime.timedelta(seconds = uts[0]))
return uts |
from __future__ import annotations
from textwrap import dedent
from pants.backend.python import target_types_rules
from pants.backend.python.goals.lockfile import GeneratePythonLockfile
from pants.backend.python.subsystems.ipython import IPythonLockfileSentinel
from pants.backend.python.subsystems.ipython import rules ... |
"""Package version for dm_memorytasks.
Kept in separate file so it can be used during installation.
"""
__version__ = '1.0.3' # https://www.python.org/dev/peps/pep-0440/ |
"""The consistencygroups api."""
import webob
from webob import exc
from cinder.api import common
from cinder.api import extensions
from cinder.api.openstack import wsgi
from cinder.api.views import consistencygroups as consistencygroup_views
from cinder.api import xmlutil
from cinder import consistencygroup as consist... |
"""Unittests for the portpicker module."""
from __future__ import print_function
import errno
import os
import random
import socket
import sys
import unittest
from contextlib import ExitStack
if sys.platform == 'win32':
import _winapi
else:
_winapi = None
try:
# pylint: disable=no-name-in-module
from un... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
from cliff.command import Command as CliffCommand
from cliff.lister import Lister
from cliff.show import ShowOne
from fakturo.core import utils
class Command(CliffCommand):
api = None
action = None
@property
def name(self):
"""
The name of the command
api-action like account-crea... |
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import uuidutils
from sqlalchemy.orm import exc
from sqlalchemy.sql import expression as expr
from neutron.db import models_v2
from neutron.extensions import l3
from neutron_lib import constants as l3_constants
from neutron_lib import excep... |
import io
import os.path
import boto3.session
import botocore.exceptions
import freezegun
import pretend
import pytest
import redis
from zope.interface.verify import verifyClass
from warehouse.packaging.interfaces import IDownloadStatService, IFileStorage
from warehouse.packaging.services import (
RedisDownloadStat... |
import allure
from allure_commons_test.report import has_test_case
from allure_commons_test.result import with_status, with_message_contains, has_status_details
from hamcrest import assert_that
@allure.issue("376")
@allure.feature("Integration")
def test_pytest_check(allured_testdir):
"""
>>> import pytest_chec... |
__all__ = [
'get_pool',
'run_function',
'join_pool'
]
import os
import sys
try:
import gevent
gevent
gevent_available = True
except ImportError:
gevent_available = False
DEFAULT_BACKEND = 'noop'
BACKEND = DEFAULT_BACKEND
USE_GEVENT = os.getenv('RAXCLI_USE_GEVENT')
if USE_GEVENT and gevent_av... |
from django import forms
from utils.fields import SlugField
from utils.forms import (
BootstrapMixin,
JSONField,
SmallTextarea,
StaticSelect,
add_blank_choice,
)
from .enums import PasswordAlgorithm
from .models import Platform
class PlatformForm(BootstrapMixin, forms.ModelForm):
slug = SlugFiel... |
import sys, os, getopt, struct, unittest
from distutils.spawn import spawn
build = True
verbosity = 2
here = os.path.dirname(os.path.abspath(__file__))
os.chdir(here)
def bits():
"""determine if running on a 32 bit or 64 bit platform
"""
return struct.calcsize("P") * 8
try:
opts, args = getopt.getopt(sy... |
"""Unit test for cgroup_service - Treadmill cgroup service.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import tempfile
import unittest
import select
import shutil
import mock
import treadmill
from tre... |
import os
import stat
import time
from inaugurator import sh
class TargetDevice:
_found = None
@classmethod
def device(cls, candidates):
if cls._found is None:
cls._found = cls._find(candidates)
return cls._found
pass
@classmethod
def _find(cls, candidates):
... |
import collections
import random
random.seed(1)
d1 = collections.deque(maxlen=3)
d2 = collections.deque(maxlen=3)
for i in range(5):
n = random.randint(0, 100)
print('n =', n)
d1.append(n)
d2.appendleft(n)
print('D1:', d1)
print('D2:', d2) |
import contextlib
import json
from osprofiler import _utils as utils
from osprofiler.drivers.base import get_driver as profiler_get_driver
from osprofiler import notifier
from osprofiler import profiler
from osprofiler import web
from horizon.utils import settings as horizon_settings
ROOT_HEADER = 'PARENT_VIEW_TRACE_ID... |
"""This example adds ad groups to a given campaign.
To get ad groups, run get_ad_groups.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section... |
import pytest
import pytest
from cwltool.utils import onWindows
from .util import get_data, get_main_output, needs_docker
try:
from galaxy.tools import deps
except ImportError:
deps = None
@needs_docker
@pytest.mark.skipif(not deps, reason="galaxy-lib is not installed")
def test_biocontainers():
wflow = get... |
"""Transforms used in the Augmentation Policies.
Copied from AutoAugment: https://github.com/tensorflow/models/blob/master/research/autoaugment/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import numpy as np
from PIL import ImageOps, Ima... |
import logging
import sys
from gbpclient.gbp.v2_0 import groupbasedpolicy as gbp
from gbpclient.tests.unit import test_cli20
class CLITestV20NatPoolJSON(test_cli20.CLITestV20Base):
LOG = logging.getLogger(__name__)
def setUp(self):
super(CLITestV20NatPoolJSON, self).setUp()
def test_create_nat_pool_... |
import json
import os
from functools import wraps
from docker.utils.ports import split_port
from jsonschema import Draft4Validator
from jsonschema import FormatChecker
from jsonschema import ValidationError
from .errors import ConfigurationError
DOCKER_CONFIG_HINTS = {
'cpu_share': 'cpu_shares',
'add_host': 'ex... |
from common import BaseTest
class NetworkInterfaceTest(BaseTest):
def test_interface_subnet(self):
factory = self.replay_flight_data(
'test_network_interface_filter')
client = factory().client('ec2')
vpc_id = client.create_vpc(CidrBlock="10.4.0.0/16")['Vpc']['VpcId']
self... |
"""This API defines FeatureColumn abstraction.
FeatureColumns provide a high level abstraction for ingesting and representing
features. FeatureColumns are also the primary way of encoding features for
canned `tf.estimator.Estimator`s.
When using FeatureColumns with `Estimators`, the type of feature column you
should ch... |
"""Solum base exception handling.
Includes decorator for re-raising Solum-type exceptions.
"""
import functools
import pecan
import sys
from keystoneclient import exceptions as keystone_exceptions
from oslo.config import cfg
import six
import wsme
from solum.common import safe_utils
from solum.openstack.common import e... |
import subprocess
subprocess.call("""
adb -d shell am start -n com.android.gallery/com.android.camera.GalleryPicker
""") |
"""
Tools for sending email.
"""
import mimetypes
import os
import smtplib
import socket
import time
import random
from email import Charset, Encoders
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.Header import Header
from email.Utils im... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1, projection="3d")
x = np.linspace(-6 * np.pi, 6 * np.pi, 1000)
y = np.sin(x)
z = np.cos(x)
ax1.plot(x, y, z)
ax2 = fig.add_subplot(1, 2, 2, projection="3d")
X = np.arange(-2, 2, 0.... |
import itertools
import random
import pytest
import cirq
import cirq.contrib.acquaintance as cca
def random_part_lens(max_n_parts, max_part_size):
return tuple(random.randint(1, max_part_size) for _ in range(random.randint(1, max_n_parts)))
@pytest.mark.parametrize(
'left_part_lens,right_part_lens',
[tuple(... |
from elftools.dwarf.ranges import RangeEntry, BaseAddressEntry
from elftools.dwarf import constants
def get_die_offset_by_reference(referer_die, attrname, use_abstract_origin=True):
'''Return the offset of the DIE referred by the given attribute in the referrer DIE.'''
ref = referer_die.attributes.get(attrname,... |
"""Tests for model.builder."""
import os
from absl.testing import parameterized
import tensorflow as tf
from google.protobuf import text_format
from deeplab2 import config_pb2
from deeplab2.model import builder
from deeplab2.model.decoder import motion_deeplab_decoder
from deeplab2.model.encoder import axial_resnet_ins... |
import cherrypy
import mako
import os
from girder import constants
from girder.utility import config
class WebrootBase(object):
"""
Serves a template file in response to GET requests.
This will typically be the base class of any non-API endpoints.
"""
exposed = True
def __init__(self, templatePa... |
import json
import objects
from mifkit.util.mif_encoder import MifEncoder
from mifkit.util.case import keys_to_snake_case
from mifkit.util.case import to_capitalized_camel_case
def dump(mif_object, fp, **kwargs):
"""
Convert this object into a JSON-encoded string and save it in a file.
:param mif_object: Ob... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
def index(request):
template = loader.get_template('index.html')
res... |
from panda3d.core import CollideMask, CollisionHandler, CollisionHandlerEvent, CollisionNode, CollisionSphere, NodePath, Point3, TextNode, Texture
from direct.interval.MetaInterval import Sequence, Parallel, Track
from direct.interval.FunctionInterval import Func, Wait
from direct.interval.SoundInterval import SoundInt... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import tensorflow as tf
from deep_nn_model import DeepNNModel
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
class DeepMlpModel(De... |
import torch.nn as nn
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.models.registry import register_model
from .helpers import build_model_with_cfg
def _cfg(url='', **kwargs):
return {
'url': url,
'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': None,
... |
import imapclient
import account_settings
import utils
def get_all_folders(username, password):
server = utils.login_to_server(username, password)
all_folders = server.list_folders()
all_folders = [triple[2] for triple in all_folders]
return all_folders, server
def main():
all_folders_old, server_old = get_al... |
import six
from heat.common import exception
from heat.common.i18n import _
from heat.common import password_gen
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support
from heat.engine import translation
... |
import os
import job_search_commute_search
PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"]
def test_commute_search(tenant):
jobs = job_search_commute_search.search_jobs(PROJECT_ID, tenant)
for job in jobs:
assert "projects/" in job |
import sys
import os
from recommonmark.parser import CommonMarkParser
extensions = []
templates_path = ['_templates']
source_parsers = {
'.md': CommonMarkParser,
}
source_suffix = ['.rst', '.md']
master_doc = 'index'
project = u'Documentation DigitalSkills'
copyright = u'2017, DigitalSkills'
version = '0.0'
release... |
wsgi_app = "weasyl.wsgi:make_wsgi_app()"
proc_name = "weasyl"
preload_app = False
secure_scheme_headers = {
'X-FORWARDED-PROTO': 'https',
}
forwarded_allow_ips = '*' |
"""
Test suites for 'common' code used throughout the OpenStack HTTP API.
"""
import mock
from testtools import matchers
import webob
import webob.exc
from cinder.api import common
from cinder import test
NS = "{http://docs.openstack.org/compute/api/v1.1}"
ATOMNS = "{http://www.w3.org/2005/Atom}"
class LimiterTest(test... |
from tflite_runtime.interpreter import load_delegate
from tflite_runtime.interpreter import Interpreter
import glob
import os
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
inpu... |
"""AFF4 interface implementation.
This contains an AFF4 data model implementation.
"""
import __builtin__
import abc
import StringIO
import time
import zlib
import logging
from grr.lib import access_control
from grr.lib import config_lib
from grr.lib import data_store
from grr.lib import lexer
from grr.lib import rdfva... |
import pymongo
import json
cache = {}
client = pymongo.MongoClient()
try:
dbConf = json.load(open("./model/db.json","r"))
except:
try:
dbConf = json.load(open("./db.json","r"))
except:
dbConf = {"dbname": "voteview"}
db = client[dbConf["dbname"]]
def metaLookup(api = ""):
if not api:
retu... |
"""
aminator.plugins.blockdevice.base
=================================
Base class(es) for block device manager plugins
"""
import abc
import logging
from aminator.plugins.base import BasePlugin
__all__ = ('BaseBlockDevicePlugin',)
log = logging.getLogger(__name__)
class BaseBlockDevicePlugin(BasePlugin):
"""
B... |
delineator = "//"
hashtag = "#"
def generate_poems(filename):
g = []
# get to the first poem in the file
with open(filename, 'r') as f:
for line in f:
line = line.rstrip()
if line.startswith( delineator ) and g:
yield g
g = []
if li... |
"""Tests for the UserAssist Windows Registry plugin."""
import unittest
from plaso.formatters import winreg as winreg_formatter
from plaso.lib import eventdata
from plaso.lib import timelib_test
from plaso.parsers.winreg_plugins import test_lib
from plaso.parsers.winreg_plugins import userassist
class UserAssistPluginT... |
from __future__ import unicode_literals
import time
import pytest
@pytest.mark.selenium
def test_ui(selenium):
selenium.browser.get(selenium.url('/download'))
time.sleep(3) |
class FpsProcessor(object):
"""
Provides common object for processing surfaceFlinger output for frame
statistics.
This processor returns the four frame statistics below:
:FPS: Frames Per Second. This is the frame rate of the workload.
:frames: The total number of frames rendered during t... |
import argparse
import logging
import sys
from backup_monkey.core import BackupMonkey, Logging
from backup_monkey import __version__
from backup_monkey.exceptions import BackupMonkeyException
from boto.utils import get_instance_metadata
__all__ = ('run', )
log = logging.getLogger(__name__)
LIMIT_LABEL = 32 # Label is a... |
'''
Classes for using multipart form data from Python, which does not (at the
time of writing) support this directly.
To use this, make an instance of Multipart and add parts to it via the factory
methods field and file. When you are done, get the content via the get method.
@author: Stacy Prowell (http://stacyprowell... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
from django.utils import unittest
from spacescout_web.test.not_found import NotFound404Test
from spacescout_web.test.url_filtering import URLFiltering |
"""This example updates an expanded text ad.
To get expanded text ads, run get_expanded_text_ads.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information... |
import datetime
import dateutil.parser
import ofx
import ofxtools
import re
import sys
import xml.sax.saxutils as sax
from decimal import *
from ofx.builder import *
class CsvConverter:
def __init__(self, qif, colspec=None, fid="UNKNOWN", org="UNKNOWN",
bankid="UNKNOWN", accttype="UNKNOWN", acctid=... |
from abc import ABCMeta, abstractmethod, abstractproperty
from contextlib import contextmanager
from functools import wraps
import gzip
from inspect import getargspec
from itertools import (
combinations,
count,
product,
)
import operator
import os
from os.path import abspath, dirname, join, realpath
import... |
"""
WSGI config for websqlrunner 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.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... |
"""
v2 Neutron Plug-in API Quark Implementation
"""
from neutron.extensions import securitygroup as sg_ext
from neutron import neutron_plugin_base_v2
from neutron import quota
from oslo.config import cfg
from oslo_log import log as logging
from quark.api import extensions
from quark import ip_availability
from quark.pl... |
import os
import re
import yaml
try:
from packaging.version import parse as parse_version
except ImportError:
from pkg_resources import parse_version
from toolbox.config.common import BUTTON_CONFIG_KEYS, CRP_TYPES, CURRENT_MAX_VERSION, CURRENT_MIN_VERSION, PROTOCOLS
from .utils import counted_error, fatal_error... |
__author__ = 'mpetyx'
from django.db import models
from OPENiapp.APIS.Context.models import OpeniContextAwareModel
class OpeniCard(OpeniContextAwareModel):
# id is missing because it is the default
url = models.TextField()
object_type = models.TextField()
service = models.TextField()
From = models.T... |
import matplotlib.pyplot as plt
import argparse
import json
from pr_json_common import *
import sys
sys.path.append('../JSON_Common')
from json_dict_common import *
def plot_metrics_as_bar(fileList, metricList, labelList, threads, ylabel):
"""
Plot metrics on a bar char from the list of metrics supplied, where ... |
import ldap
import ldap.modlist
from oslo_config import cfg
from keystone import exception
from keystone import identity
from keystone.tests import unit as tests
from keystone.tests.unit import test_ldap_livetest
CONF = cfg.CONF
def create_object(dn, attrs):
conn = ldap.initialize(CONF.ldap.url)
conn.simple_bin... |
""" in this file, we describe the data type of fp-tree nodes and present
an algorithm to build a fp-tree from existing datasets """
import fpgrowth
import Queue
def supfilter(dataset, minsup):
"""
supfilter : scan the items and drop the infrequent elements
:param dataset: dataset could be in two available t... |
"""Create, get, update, execute and delete an AWS DataSync Task."""
import logging
import random
from typing import List, Optional
from airflow.exceptions import AirflowException, AirflowTaskTimeout
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.datasync import AWSDataSyncHook
class AWS... |
"""Numeric integration of data coming from a source sensor over time."""
from decimal import Decimal, DecimalException
import logging
import voluptuous as vol
from homeassistant.components.sensor import (
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER,
PLATFORM_SCHEMA,
STATE_CLASS_TOTAL,
SensorEntity,
)
fr... |
"""Pytorch Densenet implementation w/ tweaks
This file is a copy of https://github.com/pytorch/vision 'densenet.py' (BSD-3-Clause) with
fixed kwargs passthrough and addition of dynamic global avg/max pool.
"""
import re
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as nn... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from input_functions import get_input_fn
import tensorflow as tf
from tensorflow.contrib.keras.python.keras.datasets import imdb
from tensorflow.contrib.learn.python.learn import learn_runner
fro... |
"""
file: processing.py
author: Bryce Mecum (mecum@nceas.ucsb.edu)
Processes the scientific metadata documents in ./documents for person
and organization information. For each document, the script tries to find
the person in an existing list. Matches are currently made off of all
information ava... |
"""Unit tests for the pipeline options validator module."""
from __future__ import absolute_import
import logging
import unittest
from builtins import object
from hamcrest import assert_that
from hamcrest import contains_string
from hamcrest import only_contains
from hamcrest.core.base_matcher import BaseMatcher
from a... |
"""
Sphinx documentation builder
"""
project = 'Qiskit'
copyright = '2019, Qiskit Development Team' # pylint: disable=redefined-builtin
author = 'Qiskit Development Team'
version = ''
release = '0.12.0'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.napoleon',
'sphinx.ext.viewco... |
from starthinker.util.bigquery import table_create
from starthinker.util.data import get_rows
from starthinker.util.data import put_rows
from starthinker.util.google_api import API_DCM
from starthinker.util.cm import get_profile_for_api
from starthinker.util.discovery_to_bigquery import Discovery_To_BigQuery
from start... |
from org.myrobotlab.net import BareBonesBrowserLaunch
def outsideLights(value):
if value = 1
BareBonesBrowserLaunch.openURL("http://ip_address:3480/data_request?id=action&output_format=xml&DeviceNum=6&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=01")
else
BareBonesBrowserLau... |
from freight.models import App, Repository
from .base import Serializer
from .manager import add
@add(App)
class AppSerializer(Serializer):
def serialize(self, item, attrs):
env_map = {}
for env, env_data in list(item.environments.items()):
env_map[env] = {"defaultRef": env_data.get("def... |
from ydk.types import Empty
from ydk.providers import NetconfServiceProvider, CodecServiceProvider
from ydk.services import CRUDService, NetconfService, CodecService, Datastore
from ydk.models.openconfig import bgp
from ydk.models.openconfig.routing_policy import RoutingPolicy
from _config_builder import _get_bgp_confi... |
from setuptools import setup
import os
import codecs
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding option to open
return codecs.open(os.path.join(here, *parts), 'r').read()
setup(
name='cloudify-agent-packager',
version='3.5.2',
url='htt... |
"""Import Module Plotly To Ploting Graph"""
import plotly.plotly as py
import plotly.graph_objs as go
"""Open and Read CSV from database"""
data = open('Real_Final_database_02.csv')
alldata = data.readlines()
listdata = []
for i in alldata:
listdata.append(i.strip().split(','))
type_z = ['Flood', 'Epidemic', 'Droug... |
from flask_wtf import FlaskForm # type: ignore
from wtforms import ( # type: ignore
StringField,
TextAreaField,
SubmitField,
FieldList,
FormField,
IntegerField,
HiddenField,
BooleanField,
)
from wtforms import validators
from data.models import VulnerabilityGitCommits, VulnerabilityRes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.