code stringlengths 1 199k |
|---|
from django.utils import unittest
from restclients.test.uwnetid.subscription import EmailForwardingTest
from restclients.test.util.date_formator import formatorTest
from restclients.test.hfs.idcard import HfsTest
from restclients.test.library.mylibinfo import MyLibInfoTest
from restclients.test.digitlib.curric import D... |
'''
Extension to scipy.linalg module developed for PBC branch.
'''
import numpy as np
import scipy.linalg
def davidson_nosymm(matvec,size,nroots,Adiag=None):
'''Davidson diagonalization method to solve A c = E c
when A is not Hermitian.
'''
# We don't pass args
def matvec_args(vec, args):
re... |
import os
import glob
import unittest
import pysmile
import json
__author__ = 'Jonathan Hosmer'
class PySmileTestDecode(unittest.TestCase):
def setUp(self):
curdir = os.path.dirname(os.path.abspath(__file__))
self.smile_dir = os.path.join(curdir, 'data', 'smile')
self.json_dir = os.path.join... |
from quantum.openstack.common import log as logging
from quantum.plugins.services.agent_loadbalancer.drivers.vedge.vmware.vshield.vseapi import VseAPI
from quantum.plugins.services.agent_loadbalancer.drivers.vedge.lbapi import LoadBalancerAPI
from quantum.plugins.services.agent_loadbalancer.drivers.vedge import (
c... |
"""Facilities for creating multiple test combinations.
Here is an example of testing various optimizers in Eager and Graph mode:
class AdditionExample(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(mode=["graph", "eager"],
optimizer=[AdamOptimizer()... |
"""
Rules
for *.py files
* if the changed file is __init__.py, and there is a side-band test/ dir, then test the entire test/functional directory
the reason for this is that the init files are usually organizing collections
and those can affect many different apis if they break
* if the filename is test_*.p... |
__author__ = 'thauser'
from argh import arg
import logging
from pnc_cli import utils
from pnc_cli.swagger_client.apis import BuildconfigurationsetsApi
from pnc_cli.swagger_client.apis import BuildconfigsetrecordsApi
sets_api = BuildconfigurationsetsApi(utils.get_api_client())
bcsr_api = BuildconfigsetrecordsApi(utils.g... |
class Solution:
def maxProfit(self, prices, fee):
dp = [[-prices[0]], [0]]
for i in range(1, len(prices)):
dp[0].append(max(dp[0][i-1], dp[1][i-1]-prices[i]))
dp[1].append(max(dp[0][i-1]+prices[i]-fee, dp[1][i-1]))
return dp[1][-1]
print(Solution().maxProfit([1, 3, 2,... |
bl_info = {
"name": "AeonGames Skeleton Format (.skl)",
"author": "Rodrigo Hernandez",
"version": (1, 0, 0),
"blender": (2, 80, 0),
"location": "File > Export > Export AeonGames Skeleton",
"description": "Exports an armature to an AeonGames Skeleton (SKL) file",
"warning": "",
"wiki_url"... |
from __future__ import absolute_import
import time
from threading import Thread
from pyface.tasks.action.schema import SToolBar
from pyface.tasks.task_layout import TaskLayout, PaneItem, Splitter, VSplitter
from pyface.ui.qt4.tasks.advanced_editor_area_pane import EditorWidget
from traits.api import Any, Instance, on_t... |
import basepage
class NavigationBars(basepage.BasePage):
def expand_project_panel(self):
elm = self.driver.find_element_by_css_selector(
'a[data-target="#sidebar-accordion-project"]')
state = elm.get_attribute('class')
if 'collapsed' in state:
elm.click()
else... |
import os
import re
import sys
import yaml_util
from run import check_run_quick
class Processor(object):
def __init__(self, config, environ_path, yml_path, aws_path):
with open(environ_path, 'r') as f:
self.__environ_content = f.read()
if not self.__environ_content.endswith('\n'):
... |
"""Tests for the single_task_evaluator."""
from mint.ctl import single_task_evaluator
from mint.ctl import single_task_trainer
from third_party.tf_models import orbit
import tensorflow as tf
import tensorflow_datasets as tfds
class SingleTaskEvaluatorTest(tf.test.TestCase):
def test_single_task_evaluation(self):
... |
class User(object):
def __init__(self, username=None, password=None, email=None):
self.username = username
self.password = password
self.email = email
@classmethod
def admin(cls):
return cls(username="admin", password="admin")
#random values for username and password
... |
import logging
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon_lib import tables
from openstack_horizon import api
from openstack_horizon.dashboards.identity.g... |
"""
Created on Thu Oct 12 22:25:38 2017
@author: sitibanc
"""
import math
import numpy as np
def entropy(p1, n1): # postive, negative
if p1 == 0 and n1 == 0:
return 1
value = 0
pp = p1 / (p1 + n1)
pn = n1 / (p1 + n1)
if pp > 0:
value -= pp * math.log2(pp)
if pn > 0:
... |
import time, sys
import zmq
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.zmq import ZmqServerTransport
from tinyrpc.server import RPCServer
from tinyrpc.dispatch import RPCDispatcher
class Server(object):
def __init__(self, req_callback):
# print 'initializing Rpc'
s... |
from nw.providers.Provider import Provider
import subprocess
import re
from logging import getLogger
_data_available = [
'status', # returns the status code (integer) of ping command execution: 0 = success, other = error occurred
'ping_response', # returns the whole std output of p... |
import lean
import lang.expr as expr
class DeclView(lean.declaration):
def __init__(self, decl):
self.decl = decl
def destruct(self):
# type: DeclView -> (lean.name, ?, ?, lean.expr, lean.expr)
return (self.decl.get_name(),
self.decl.get_univ_params(),
sel... |
import logging
import os
import sys
import time
import json
import jsonschema
import pprint
import pytest
import requests
from ray._private.test_utils import (
format_web_url,
wait_for_condition,
wait_until_server_available,
)
from ray.dashboard import dashboard
from ray.dashboard.tests.conftest import * #... |
import argparse
import datetime
import getpass
import json
import logging
import logging.config
import os
import re
import sys
import tabulate
import uuid
from critsapi.critsapi import CRITsAPI
from critsapi.critsdbapi import CRITsDBAPI
from lib.pt.common.config import Config
from lib.pt.common.constants import PT_HOME... |
import json
from pecan import rest
from pecan import abort
from wsme import types as wtypes
import wsmeext.pecan as wsme_pecan
from mistral import exceptions as ex
from mistral.api.controllers.v1 import task
from mistral.openstack.common import log as logging
from mistral.api.controllers import resource
from mistral.db... |
import logging
from sys import exc_info
from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM, SHUT_RD, SOL_SOCKET, SO_REUSEADDR, error as socketError
from traceback import format_exception
from struct import Struct
from .common import *
from .models import *
from .exceptions import *
class ClientHost():
def ... |
import logging
from event_consumer.conf import settings
from event_consumer.errors import PermanentFailure
from event_consumer.handlers import message_handler
_logger = logging.getLogger(__name__)
class IntegrationTestHandlers(object):
"""
Basic message handlers that log or raise known exceptions to allow
i... |
import string
import copy
import os
import gzip
import gtk
import commands
try:
from backports import lzma
except ImportError:
from lzma import LZMAFile as lzma
import singletons
from common import *
import common; _ = common._
from Source import *
from Package import *
from Category import *
def czfind(istr):
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
import os
import pkgutil
import threading
import xml.etree.ElementTree as ET
from abc import abstractmethod
from builtins import object, open, str
from collections import defaultdict, namedtuple
from functools ... |
from oslo_config import cfg
OPTS = {"benchmark": [
# prepoll delay, timeout, poll interval
# "start": (0, 300, 1)
cfg.FloatOpt("nova_server_%s_prepoll_delay" % "start",
default=float(0),
help="Time to sleep after %s before polling"
" for status" % "sta... |
'''
Created on Mar 12, 2012
@author: moloch
Copyright 2012
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 ap... |
import os
import logging
import logging.handlers
log = logging.getLogger('imc')
console = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
def enable_file_logging(filename="imcsdk.log"):
file_handler = logging.handlers... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
baseUrl = "https://www.expedia.es"
driver = webdriver.Firefox()
driver.maximize_window()
driver.get(baseUrl)
driver.implicitly_wait(10) |
"""This library provides a set of classes and functions that helps train models.
The Optimizer base class provides methods to compute gradients for a loss and
apply gradients to variables. A collection of subclasses implement classic
optimization algorithms such as GradientDescent and Adagrad.
You never instantiate th... |
"""
author: sanja7s
---------------
plot the distribution
"""
import os
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from collections import defaultdict
from matplotlib import colors
from pylab import MaxNLocator
import pylab as pl
from mpl_toolkits.a... |
"""
lexical chain module for text tiling
"""
from tile_reader import TileReader
from scoring import boundarize, depth_scoring, window_diff
class LexicalChains(object):
def __init__(self):
self.sentences = []
self.actives = {}
self.gap_scores = []
self.boundary_vector = []
def ana... |
"""Actions related to task commands."""
import time
from drydock_provisioner.cli.action import CliAction
from drydock_provisioner.cli.const import TaskStatus
class TaskList(CliAction): # pylint: disable=too-few-public-methods
"""Action to list tasks."""
def __init__(self, api_client):
"""Object initial... |
"""
Helper functions for use by mac modules
.. versionadded:: 2016.3.0
"""
import logging
import os
import plistlib
import subprocess
import time
import xml.parsers.expat
import salt.grains.extra
import salt.modules.cmdmod
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platform
... |
import logging
from src import util
from src import etherscan
from src import messages
from crypto.prices import *
logger = logging.getLogger("node")
def nodeAdd(bot, update, args):
response = "*Add*\n\n"
chatId = update.message.chat_id
logger.warning("add - args " + " ".join(args))
logger.warning("add ... |
"""Tests for metadata utils."""
import os
import tensorflow.compat.v1 as tf
from explainable_ai_sdk.metadata.tf.v1 import utils
class UtilsTest(tf.test.TestCase):
def test_save_graph_model_explicit_session(self):
sess = tf.Session(graph=tf.Graph())
with sess.graph.as_default():
x = tf.placeholder(shape=... |
import os
import subprocess
from nodes import storage_nodes as ips
def generate_rings():
print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"]
print (os.environ["PATH"])
dev = 'sdb1'
ETC_SWIFT='/etc/swift'
if not os.path.exists(ETC_SWIFT):
... |
from __future__ import absolute_import
from __future__ import print_function
from contextlib import contextmanager
from typing import (cast, Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional,
Sized, Tuple, Union, Text)
from django.core.urlresolvers import resolve
from django.conf impo... |
import atexit
import sys
def all_done():
print('all_done()')
print('Registering')
atexit.register(all_done)
print('Registered')
print('Exiting...')
sys.exit() |
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.http import HttpResponse
from django.shortc... |
import mock
import tuskarclient.tests.utils as tutils
from tuskarclient.v1 import resource_classes
class ResourceClassManagerTest(tutils.TestCase):
def setUp(self):
super(ResourceClassManagerTest, self).setUp()
self.api = mock.Mock()
self.rcm = resource_classes.ResourceClassManager(self.api)... |
import sys, os
sys.path.insert(0, os.path.abspath('..'))
extensions = ['sphinx.ext.todo','jsonext']
templates_path = ['_templates/sphinxdoc']
source_suffix = '.rst'
master_doc = 'index'
project = u'Baobab'
copyright = u'2010, Riccardo Attilio Galli'
version = '1.3.1'
release = '1.3.1'
exclude_patterns = []
pygments_sty... |
from functools import partial
from jarvis_cli.client.common import _get_jarvis_resource, _post_jarvis_resource, \
_put_jarvis_resource, query
def _construct_log_entry_endpoint(event_id):
return "events/{0}/logentries".format(event_id)
def get_log_entry(event_id, conn, log_entry_id):
return _get_jarvis_resou... |
"""Keras initializer serialization / deserialization."""
import tensorflow.compat.v2 as tf
import threading
from tensorflow.python import tf2
from keras.initializers import initializers_v1
from keras.initializers import initializers_v2
from keras.utils import generic_utils
from keras.utils import tf_inspect as inspect
... |
import os
import sys
import falcon_config as fc
import subprocess
cmd = sys.argv[0]
prg, base_dir = fc.resolve_sym_link(os.path.abspath(cmd))
service_stop_cmd = os.path.join(base_dir, 'bin', 'service_stop.py')
subprocess.call(['python', service_stop_cmd, 'prism']) |
"""Simple wave robot WSGI application and forwarding middleware."""
import webob
import webob.exc
from api import robot_abstract
import logging
class RobotMiddleware(object):
"""WSGI middleware that routes /_wave/ requests to a robot wsgi app."""
def __init__(self, robot_app, main_app):
self._robot_app = robot_... |
from kuryr.schemata import commons
ENDPOINT_DELETE_SCHEMA = {
u'links': [{
u'method': u'POST',
u'href': u'/NetworkDriver.DeleteEndpoint',
u'description': u'Delete an Endpoint',
u'rel': u'self',
u'title': u'Delete'
}],
u'title': u'Delete endpoint',
u'required': [u'... |
"""Tests for greeneye_monitor sensors."""
from unittest.mock import AsyncMock, MagicMock
from homeassistant.components.greeneye_monitor.sensor import (
DATA_PULSES,
DATA_WATT_SECONDS,
)
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_r... |
from migrate.changeset import UniqueConstraint
from migrate import ForeignKeyConstraint
from sqlalchemy import Boolean, BigInteger, Column, DateTime, Enum, Float
from sqlalchemy import dialects
from sqlalchemy import ForeignKey, Index, Integer, MetaData, String, Table
from sqlalchemy import Text
from sqlalchemy.types i... |
import tornado.ioloop
from functools import partial
from tornado.testing import AsyncTestCase
from elasticsearch_tornado import ClusterClient
try:
# python 2.6
from unittest2 import TestCase, SkipTest
except ImportError:
from unittest import TestCase, SkipTest
class ClusterClientTest(AsyncTestCase):
... |
extensions = [
'sphinx.ext.autodoc',
'sphinxcontrib.apidoc',
'openstackdocstheme',
]
openstackdocs_repo_name = 'openstack/oslo.privsep'
openstackdocs_bug_project = 'oslo.privsep'
openstackdocs_bug_tag = ''
source_suffix = '.rst'
master_doc = 'index'
copyright = u'2014, OpenStack Foundation'
add_function_par... |
from colordetection import *
topColors(992780587437103) |
import copy
import logging
import random
import time
from oslo.config import cfg
import six
from sahara.openstack.common._i18n import _, _LE, _LI
periodic_opts = [
cfg.BoolOpt('run_external_periodic_tasks',
default=True,
help='Some periodic tasks can be run in a separate process. '
... |
"""Tests for the SmartThings component init module."""
from uuid import uuid4
from aiohttp import ClientConnectionError, ClientResponseError
from asynctest import Mock, patch
from pysmartthings import InstalledAppStatus, OAuthToken
import pytest
from homeassistant.components import cloud, smartthings
from homeassistant... |
"""Remote process implementation."""
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import untrusted_runner_pb2
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import process_handler
from . import protobuf_utils
def process_result_to_proto(process... |
import gevent
import gevent.pool
import uuid
import logging
def get_trace(greenlet=None):
greenlet = greenlet or gevent.getcurrent()
if not hasattr(greenlet, '_iris_trace'):
greenlet._iris_trace = {}
return greenlet._iris_trace
def spawn(*args, **kwargs):
greenlet = gevent.Greenlet(*args, **kwar... |
default_app_config = 'leonardo.apps.LeonardoConfig'
__import__('pkg_resources').declare_namespace(__name__)
try:
from leonardo.base import leonardo # noqa
except ImportError:
import warnings
def simple_warn(message, category, filename, lineno, file=None, line=None):
return '%s: %s' % (category.__na... |
from .common import BaseTest
import jmespath
class TestApacheAirflow(BaseTest):
def test_airflow_environment_value_filter(self):
session_factory = self.replay_flight_data('test_airflow_environment_value_filter')
p = self.load_policy(
{
"name": "airflow-name-filter",
... |
'''
Created on Aug 29, 2015
@author: kevinchien
'''
import datetime
from tornado.gen import Task, Return
from tornado.gen import coroutine
from src.common.logutil import get_logger |
"""Tests for the Google Drive database plugin."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import gdrive as _ # pylint: disable=unused-import
from plaso.lib import definitions
from plaso.parsers.sqlite_plugins import gdrive
from tests.parsers.sqlite_plugins import test_lib
class Go... |
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_cor... |
from boten.core import BaseBot
import payloads
class TestBot(BaseBot):
def command_arg_bot(self, user_name):
yield "hello {}".format(user_name)
def command_no_arg_bot(self):
yield "hello"
def command_optional_arg_bot(self, optional="default"):
yield "hello {}".format(optional)
de... |
import posixpath
import random
import math
from bin.shared import ray_cast
from bin.shared import csp
from direct.actor.Actor import Actor
from direct.interval.IntervalGlobal import *
from direct.interval.ActorInterval import ActorInterval
from panda3d.core import *
from panda3d.ode import *
class SimpleWeapon:
"""Pr... |
__source__ = 'https://leetcode.com/problems/balanced-binary-tree/#/description'
import unittest
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
... |
import os
import sys
import argparse
import subprocess
import signal
import re
boost_tests = [
'futures_test',
'memcached/test_ascii_parser',
'sstring_test',
'output_stream_test',
'httpd',
]
other_tests = [
'smp_test',
]
last_len = 0
def print_status_short(msg):
global last_len
print('\r... |
"""
Manages information about the guest.
This class encapsulates libvirt domain provides certain
higher level APIs around the raw libvirt API. These APIs are
then used by all the other libvirt related classes
"""
from lxml import etree
from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_uti... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cd_subscription', '0004_auto_20161125_1901'),
]
operations = [
migrations.AlterField(
model_name='cdsubscription',
name='badgelen... |
import abc
import dataclasses
from typing import Iterable, List, Optional
import cirq
from cirq.protocols.circuit_diagram_info_protocol import CircuitDiagramInfoArgs
@dataclasses.dataclass
class SymbolInfo:
"""Organizes information about a symbol."""
labels: List[str]
colors: List[str]
@staticmethod
... |
import optparse
import subprocess
from maas_common import metric
from maas_common import metric_bool
from maas_common import print_output
from maas_common import status_err
from maas_common import status_ok
import requests
OVERVIEW_URL = "http://%s:%s/api/overview"
NODES_URL = "http://%s:%s/api/nodes"
CONNECTIONS_URL =... |
"""
Authors: Tim Hessels
UNESCO-IHE 2017
Contact: t.hessels@unesco-ihe.org
Repository: https://github.com/wateraccounting/wa
Module: Collect/JRC
Description:
This module downloads JRC water occurrence data from http://storage.googleapis.com/global-surface-water/downloads/.
Use the JRC.Occurrence function to
do... |
def handle(controller_slice):
from core.models import ControllerSlice, Slice
try:
my_status_code = int(controller_slice.backend_status[0])
try:
his_status_code = int(controller_slice.slice.backend_status[0])
except:
his_status_code = 0
if (my_status_code n... |
import datetime
import logging
import sys
import uuid
import fixtures
from oslo_serialization import jsonutils
from oslo_utils import strutils
from oslo_utils import timeutils
from stevedore import dispatch
from stevedore import extension
import testscenarios
import yaml
import oslo_messaging
from oslo_messaging.notify... |
from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models.jobplan import JobPlan
from changes.utils.http import build_web_uri
from .base import ArtifactHandler, ArtifactParseError
class CollectionArtifactHandler(ArtifactHandler):
"""
... |
from citrination_client.search.pif.query.chemical.chemical_field_operation import ChemicalFieldOperation
from citrination_client.search.pif.query.core.base_object_query import BaseObjectQuery
from citrination_client.search.pif.query.core.field_operation import FieldOperation
class CompositionQuery(BaseObjectQuery):
... |
"""Unit tests for SPASSWORD checker."""
from keystone import tests
from keystone import exception
import keystone_spassword.contrib.spassword.checker
class TestPasswordChecker(tests.BaseTestCase):
def test_checker(self):
new_password = "stronger"
self.assertRaises(exception.ValidationError,
... |
import unittest
import mock
from airflow.providers.google.cloud.operators.dataflow import (
CheckJobRunning, DataflowCreateJavaJobOperator, DataflowCreatePythonJobOperator,
DataflowTemplatedJobStartOperator,
)
from airflow.version import version
TASK_ID = 'test-dataflow-operator'
JOB_NAME = 'test-dataflow-pipel... |
import wasp
def onConflict():
"""
Optional.
A conflict happened during the solving
"""
pass
def onDeletion():
"""
Optional.
The method for deleting clauses is invoked.
"""
pass
def onLearningClause(lbd, size, *lits):
"""
Optional.
When a clause is learnt.
:param l... |
"""Compare a txt file of predictions with gold targets from a TSV file."""
from absl import app
from absl import flags
from language.compgen.nqg.tasks import tsv_utils
from tensorflow.io import gfile
FLAGS = flags.FLAGS
flags.DEFINE_string("gold", "", "tsv file containing gold targets.")
flags.DEFINE_string("prediction... |
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers
from google.api_core import gapic_v1
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials... |
"""
Usage: kafka_to_mysql.py <kafka_topic> <kafka_broker> <mysql-ip> <mysql-port> <mysql-user> <mysql-password> <mysql_table>
"""
import json
import MySQLdb
from kafka import KafkaClient, KafkaConsumer
import sys
def usage():
print __doc__
sys.exit(1)
def main():
# R0915: "too many statements in function (>... |
from __future__ import division
import datetime as dt
missing = object()
try:
import numpy as np
except ImportError:
np = None
def int_to_rgb(number):
"""Given an integer, return the rgb"""
number = int(number)
r = number % 256
g = (number // 256) % 256
b = (number // (256 * 256)) % 256
... |
legalProperties = {"bid", "ask", "change", "percentChange", "lastTradeSize"}
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import cgi # Better way now?
import json
import urllib2
import urllib
import re
PORT = 6666
def protest (response, message):
response.send_response(200)
response.send_header(... |
import os
from torch.utils.ffi import create_extension
sources = ["src/lib_cffi.cpp"]
headers = ["src/lib_cffi.h"]
extra_objects = ["src/bn.o"]
with_cuda = True
this_file = os.path.dirname(os.path.realpath(__file__))
extra_objects = [os.path.join(this_file, fname) for fname in extra_objects]
ffi = create_extension(
... |
from __future__ import absolute_import
import logging
import yaml
import netaddr
import os
import re
import collections
import itertools
import shutil
import gevent
import gevent.queue
import gevent.event
import pan.xapi
from . import base
from . import actorbase
from . import table
from .utils import utc_millisec
LOG ... |
from django.contrib.staticfiles import storage
class TTStaticFilesStorage(storage.StaticFilesStorage):
def __init__(self, *args, **kwargs):
kwargs['file_permissions_mode'] = 0o644
kwargs['directory_permissions_mode'] = 0o755
super(TTStaticFilesStorage, self).__init__(*args, **kwargs) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tocayoapp', '0007_gender_description'),
]
operations = [
migrations.AlterField(
model_name='gender',
name='description',
... |
import logging
import os
import os.path
import shutil
import subprocess
import tempfile
import time
from six.moves import urllib
import uuid
from six.moves.urllib.parse import urlparse # pylint: disable=E0611,F0401
from test.service import ExternalService, SpawnedService
from test.testutil import get_open_port
log = lo... |
"""
Volume driver library for NetApp 7/C-mode block storage systems.
"""
import math
import sys
import uuid
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import units
import six
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder.volume.drivers.netapp.... |
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" execution ... |
"""Tests for no_pivot_ldl."""
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.experimental.linalg.no_pivot_ldl import no_pivot_ldl
from tensorflow_probability.python.experimental.linalg.no_pivot_ldl import simple_robustified_cholesky
from tensorflow_probability.python.internal im... |
from __future__ import print_function
import sys
import time
from catkin_pkg.package import InvalidPackage
from catkin_tools.argument_parsing import add_context_args
from catkin_tools.argument_parsing import add_cmake_and_make_and_catkin_make_args
from catkin_tools.common import format_time_delta
from catkin_tools.comm... |
from oslo_utils import uuidutils
from nova import context
from nova import exception
from nova.objects import cell_mapping
from nova.objects import instance_mapping
from nova import test
from nova.tests import fixtures
sample_mapping = {'instance_uuid': '',
'cell_id': 3,
'project_id'... |
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from crate.client.sqlalchemy.types import Object, ObjectArray
from crate.client.cursor import Cursor
from unittest import TestCase
from unittest.mock import patch, MagicMock
fake_cursor = MagicMock(name='fake_cursor')
FakeCursor = MagicMock... |
import numpy as np
import matplotlib.pyplot as plt #Used for graphing audio tests
import pyaudio as pa
import wave
from time import sleep
CHUNK = 1024
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # Must match rate at which mic actually samples sound
RECORD_TIMEFRAME = 1.0 #Time in seconds
OUTPUT_FILE = "sample.wav"
TE... |
from __future__ import print_function
import numpy as np
from ctypes import POINTER, c_double, c_int64
from pyscf.nao.m_libnao import libnao
libnao.ao_eval.argtypes = (
POINTER(c_int64), # nmult
POINTER(c_double), # psi_log_rl
POINTER(c_int64), # nr
POINTER(c_double), # rhomin_jt
POINTER(c_double), # dr_jt
... |
import sys
sys.path.append("env\Lib\site-packages")
import logging
import logging.config
from datetime import datetime
import config
from database import DataStore
from ifttt import IFTTT
logging.config.fileConfig('log.config')
logger = logging.getLogger(config.logger_name)
def myExceptionHook(exctype, value, traceback... |
from urllib import request
from tests.integrated import base
class StatusTestCase(base.IntegrationTest):
def _get_config(self):
port = base.get_free_port()
self.url = "http://localhost:%s" % port
conf = {
"service": {
"name": "status",
... |
from abc import ABCMeta
from abc import abstractmethod
import six
@six.add_metaclass(ABCMeta)
class CryptographicEngine(object):
"""
The abstract base class of the cryptographic engine hierarchy.
A cryptographic engine is responsible for generating all cryptographic
objects and conducting all cryptograp... |
from django.db import models
import reversion
from base.model_utils import TimeStampedModel
from base.singleton import SingletonModel
from block.models import (
Page,
PageSection,
Section,
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.