code stringlengths 1 199k |
|---|
f = open('mysql_knob.txt','r+')
data = f.readlines()
f.close()
f = open('mysql_knobs.json','w')
f.write("[\n")
l = 0
for x in data:
x = x.replace("\n","")
l += 1
f.write(" {\n \"model\":\"website.KNOB_PARAMS\",\n \"fields\":{\n")
f.write(" \""+"db_type"+ "\":\"" +"MYSQL" + "\",\n")
f.wri... |
import jsonschema
from rally.benchmark.scenarios import base
from rally.benchmark.scenarios.cinder import utils as cinder_utils
from rally.benchmark.scenarios.nova import utils
from rally.benchmark.scenarios import utils as scenario_utils
from rally.benchmark import types as types
from rally.benchmark import validation... |
from .base import FunctionalTest
def compute_view(request):
if request.verify_request(scopes=["compute"]) is True:
result = {'status': 'success'}
else:
result = {'status': 'not allowed'}
return result
class OAuth2AppTests(FunctionalTest):
def setUp(self):
super(OAuth2AppTests, se... |
import cStringIO
import gzip
import unittest
import time
import os
import json
import mock
import requests.exceptions
import plugins_manager
from base_crawler import BaseFrame
from capturing import Capturing
from emitters_manager import EmittersManager
from plugins.emitters.file_emitter import FileEmitter
from plugins.... |
"""Tests for the Wemo standalone/non-bridge light entity."""
import pytest
from pywemo.exceptions import ActionException
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, Platform
from homeassis... |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import uuid
import migrate
from oslo_config import cfg
from oslo_db.sqlalchemy import migration
from oslo_log import log
from oslo_log import versionutils
from oslo_serialization import jsonutils
import pbr.version
from ke... |
import logging
import time
from airflow.contrib.hooks.gcp_dataproc_hook import DataProcHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.version import version
from googleapiclient.errors import HttpError
class DataprocClusterCreateOperator(BaseOperator):
... |
"""Defines interface for DB access.
Functions in this module are imported into the nova.db namespace. Call these
functions from nova.db namespace, not the nova.db.api namespace.
All functions in this module return objects that implement a dictionary-like
interface. Currently, many of these objects are sqlalchemy object... |
"""Beautiful Soup Elixir and Tonic - "The Screen-Scraper's Friend".
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup uses a pluggable XML or HTML parser to parse a
(possibly invalid) document into a tree representation. Beautiful Soup
provides methods and Pythonic idioms that make it easy to navigate,
searc... |
"""Heartbeat service.
This is the internal thread responsible for sending heartbeat events
at regular intervals (may not be an actual thread).
"""
from __future__ import absolute_import, unicode_literals
from celery.signals import heartbeat_sent
from celery.utils.sysinfo import load_average
from .state import SOFTWARE_... |
from __future__ import print_function
import os
import sys
import timeit
import numpy
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from utilis import shared_dataset_x, shared_dataset_y
class HiddenLayer(object):
def __init__(self, rng, input, n_in, n_... |
"""Test the Logitech Harmony Hub remote."""
from datetime import timedelta
from aioharmony.const import SendCommandDevice
from homeassistant.components.harmony.const import (
DOMAIN,
SERVICE_CHANGE_CHANNEL,
SERVICE_SYNC,
)
from homeassistant.components.harmony.remote import ATTR_CHANNEL, ATTR_DELAY_SECS
fro... |
"""Core classes and core ops for LabeledTensor.
Core ops are ops which will eventually be called by LabeledTensor methods,
and ops which a core op depends upon.
For example, `add` is a core op because we'll eventually support the `+`
operator.
Non-core ops should go in `ops.py`.
"""
from __future__ import absolute_impo... |
"""Upgrader for Python scripts from 1.* TensorFlow to 2.0 TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ast
import copy
import functools
import sys
import pasta
import six
from tensorflow.tools.compatibility import all_renames_v2
from ... |
from sqlalchemy import Boolean, String, DateTime, Integer
from sqlalchemy import MetaData, Column, ForeignKey, Table
from nova import log as logging
meta = MetaData()
aggregates = Table('aggregates', meta,
Column('created_at', DateTime(timezone=False)),
Column('updated_at', DateTime(timezone=False))... |
"""
Misc tests for helper functions.
"""
from __future__ import unicode_literals
from __future__ import print_function
import os
from shutil import rmtree
from tempfile import mkdtemp
from unittest import TestCase
from xbundle import mkdir
class TestXBundle(TestCase):
"""
Misc tests for helper functions.
""... |
import fnmatch
import os
__author__ = 'kocsen'
import xml.etree.ElementTree as ET
class AndroidApp():
"""
Class representation of the app.
Contains all sorts of infromationa bout the app including
name and the parseable xml for the Manifest
"""
def __init__(self, name, location_root):
se... |
import numpy as Math
import pylab as Plot
import matplotlib.colors as colors
from featurevectors import *
def Hbeta(D = Math.array([]), beta = 1.0):
"""Compute the perplexity and the P-row for a specific value of the precision of a Gaussian distribution."""
# Compute P-row and corresponding perplexity
P = Math.exp(-... |
import os.path as op
from functools import partial
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
import pytest
from mne import (read_evokeds, read_proj, make_fixed_length_events, Epochs,
compute_proj_evoked)
from mne.io.proj import make_eeg_average_ref_proj
from mne.io i... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Option.last_updated'
db.add_column(
'sentry_option',
'last_updated',
self.gf('djang... |
import views
urlpatterns = ('upload.views',
# Root view
(r'^$', 'index'),
# Upload url
(r'^(?P<folder>\d+)/$', 'upload'),
#Zipping url
(r'zip/(?P<folder>\d+)/$', 'zip'),
# Get zip
(r'^(?P<zip>\d+\.\w+)$', 'getzip'),
#Send mail + sms
(r'send/(?P<file>\d+\..+)/(?P<email>.+)/(?P<pho... |
from numpy import *
def iahwt(f):
from iahaarmatrix import iahaarmatrix
f = asarray(f).astype(float64)
if len(f.shape) == 1: f = f[:,newaxis]
(m, n) = f.shape
A = iahaarmatrix(m)
if (n == 1):
F = dot(A, f)
else:
B = iahaarmatrix(n)
F = dot(dot(A, f), transpose(B))
... |
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Add-KeePassConfigTrigger',
# list of o... |
__version__ = '0.9.11' # pragma: nocover
default_app_config = 'filer.apps.FilerConfig' |
"""Contains on-disk caching functionality."""
import logging
import os
import shutil
from chromite.lib import cros_build_lib
from chromite.lib import locking
from chromite.lib import osutils
def EntryLock(f):
"""Decorator that provides monitor access control."""
def new_f(self, *args, **kwargs):
# Ensure we don... |
from __future__ import annotations
from datetime import datetime
import gc
import numpy as np
import pytest
from pandas._libs import iNaT
from pandas._libs.tslibs import Timestamp
from pandas.core.dtypes.common import (
is_datetime64tz_dtype,
is_float_dtype,
is_integer_dtype,
is_unsigned_integer_dtype,
... |
from . import cube, maps, modelcube, spaxel
from .cube import Cube
from .image import Image
from .maps import Maps
from .modelcube import ModelCube
from .plate import Plate
from .rss import RSS, RSSFiber
from .spaxel import Spaxel |
import json
import logging
import os
import shutil
import subprocess
class RefineLDA(object):
"""
modelPath = Folder for storing all output files
numIters = Other parameters
mustLinkConstraints = a list of lists of words
cannotLinkConstraints = a list of lists of words
keepTerms = a dict where the keys are topic ... |
"""NDG Security ndg namespace package
NERC DataGrid Project
This is a setuptools namespace_package. DO NOT place any other
code in this file! There is no guarantee that it will be installed
with easy_install. See:
http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
... for details.
"""
__author__ =... |
"""
Adapted code from "Contrast Limited Adaptive Histogram Equalization" by Karel
Zuiderveld <karel@cv.ruu.nl>, Graphics Gems IV, Academic Press, 1994.
http://tog.acm.org/resources/GraphicsGems/gems.html#gemsvi
The Graphics Gems code is copyright-protected. In other words, you cannot
claim the text of the code as your... |
import os
import subprocess
import sys
import tempfile
import unittest
from test import support
from test.support.script_helper import (
spawn_python, kill_python, assert_python_ok, assert_python_failure,
interpreter_requires_environment
)
Py_DEBUG = hasattr(sys, "gettotalrefcount")
def _kill_python_and_exit_co... |
from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
parameter_list = [[traindat,testdat,10,3,1.0],[traindat,testdat,10,4,1.0]]
def kernel_sparse_poly (fm_train_real=traindat,fm_test_real=testdat,
cache_size... |
from pyrax.object_storage import DEFAULT_CDN_TTL
from django.conf import settings
CUMULUS = {
"API_KEY": None,
"AUTH_URL": "us_authurl",
"AUTH_VERSION": "2.0",
"AUTH_TENANT_NAME": None,
"AUTH_TENANT_ID": None,
"REGION": "DFW",
"CNAMES": None,
"CONTAINER": None,
"CONTAINER_URI": None,... |
"""Code to flatten a swarming config, specifically the buildbucket builders.
There are several features in the proto that can be used to reduce code
verbosity:
* builder defaults
* builder mixins
* recipe properties (instead of properties_j)
This code exercises those features and produces a flattened config proto... |
"""
Query subclasses which provide extra functionality beyond simple data retrieval.
"""
from django.core.exceptions import FieldError
from django.db import connections
from django.db.models.constants import LOOKUP_SEP
from django.db.models.fields import DateField, FieldDoesNotExist
from django.db.models.sql.constants ... |
'''
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[... |
from django import forms, template
from django.db.models import ObjectDoesNotExist
from django.template.loader import render_to_string
import plata
import plata.context_processors
register = template.Library()
@register.simple_tag(takes_context=True)
def load_plata_context(context):
"""
Conditionally run plata'... |
from io import BytesIO
from typing import Dict, Set, Union
from urllib.parse import urlparse
from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image
from prices import Money
from saleor.product.models import Product, ProductVariant
def get_url_path(url):
parsed_url = urlparse(url)
re... |
from .rec_layers import \
LSTMLayer, \
RecurrentLayer, \
RecurrentMultiLayer, \
RecurrentMultiLayerInp, \
RecurrentMultiLayerShortPath, \
RecurrentMultiLayerShortPathInp, \
RecurrentMultiLayerShortPathInpAll
from .rconv_layers import RecursiveConvolutionalLayer
f... |
import logging
import csv
import os
from StringIO import StringIO
from projects.exceptions import ProjectImportError
from vcs_support.backends.github import GithubContributionBackend
from vcs_support.base import BaseVCS, VCSVersion
log = logging.getLogger(__name__)
class Backend(BaseVCS):
supports_tags = True
s... |
import CGIHTTPServer
import SimpleHTTPServer
import BaseHTTPServer
import SocketServer
class MyRequestHandler( CGIHTTPServer.CGIHTTPRequestHandler):
def end_headers(self):
self.send_header("Pragma", "no-cache")
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.sen... |
"""=============================================
该脚本用于手工维护表更新:只更新非空值,剔除空值
Created on 2016年6月28日
@author: lujian
================================================"""
import os
import sys
import csv
import mysql.connector
from ..SqlPack.SQLModel import get_DataBaseConn
def cur_file_dir():
# 获取脚本路径
path = sys.path[... |
from dice import d
from fifth.backgrounds import Background
from fifth.race import Race
from fifth.processor import CharacterProcessor
class Attributes(CharacterProcessor):
""" Takes an empty character and adds D&D attributes. """
def roll_attribute(self):
""" 4d6 drop the lowest """
return sum(... |
__author__ = 'Danyang'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# ascending
def insertionSortList_TLE(self, head):
"""
Time Limit Exceded
"""
comparator = lambda x, y: cmp(x.val, y.val)
# open set & closed se... |
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
class Component(ApplicationSession):
"""
An application component calling the different backend procedures.
"""
@inlineCallbacks
def onJoin(self, details):
pr... |
from collections import defaultdict
import math
import scipy.constants as const
from pymatgen.core.periodic_table import Element, Specie
from pymatgen.core.structure import Composition
__author__ = "Anubhav Jain"
__copyright__ = "Copyright 2011, The Materials Project"
__credits__ = ["Shyue Ping Ong", "Geoffroy Hautier"... |
import argparse
import os
import importlib
parser = argparse.ArgumentParser(description='Generate C files from ssot.')
parser.add_argument('module', help='the module to process')
parser.add_argument('cdir', help='the output C directory name')
parser.add_argument('hdir', help='the output header directory name')
args = p... |
import os
import sys
from binascii import hexlify, unhexlify
from base64 import b64encode
from decimal import Decimal, ROUND_DOWN
import json
import random
import shutil
import subprocess
import time
import re
import errno
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
COVERAGE_DIR = N... |
import unittest
from datetime import date, timedelta
from rollcall.func_json import gen_dict, update_status, format_date
from rollcall.exce import NoField
class Testadd(unittest.TestCase):
"""
tests the update_status function in func_json module
"""
def setUp(self):
self.today = date.today()
... |
from collections import defaultdict
from operator import attrgetter
from flask import flash, request
from werkzeug.exceptions import NotFound
from indico.core.plugins import PluginCategory, plugin_engine
from indico.core.plugins.views import WPPlugins
from indico.modules.admin import RHAdminBase
from indico.util.i18n i... |
from flask import jsonify, request, session
from werkzeug.exceptions import BadRequest
from indico.core.db import db
from indico.modules.events.registration import logger
from indico.modules.events.registration.controllers.management.sections import RHManageRegFormSectionBase
from indico.modules.events.registration.mod... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-hivemindrpc"))
import json
import shutil
import subprocess
import tempfile
import traceback
from hivemindrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
def check_array_result(object_array, t... |
"""QGIS Unit tests for QgsSpatialiteProvider
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Vincent... |
""" The implementation of tizen IVI communication"""
import os
import time
import socket
import threading
import re
import sys
from shutil import copyfile
from testkitlite.util.log import LOGGER
from testkitlite.util.autoexec import shell_command, shell_command_ext
from testkitlite.util.killall import killall
from test... |
'''
This module has two classes, Turn and TurnSequence. A Turn represents a
single move that can be used to manipulate a cube with any arbitrary
side length > 1. A TurnSequence is a list object that specifically holds
Turn objects and can produce their own inverses, i.e., a given TurnSequence
A can return a TurnSequenc... |
"""
Monitor a mount on the filesystem and all of it sub mounts
"""
from optparse import OptionParser
import subprocess
import os.path
def parse_args():
parser = OptionParser()
parser.add_option('-p', '--path', dest='path', type='string', help='absolute path to check', metavar="FILE")
parser.add_option('-w',... |
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
**************... |
"""QGIS Unit tests for QgsComposerMap.
.. note. This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '(C) 2012 by Dr... |
""" DIRAC FileCatalog mix-in class to manage directory metadata
"""
__RCSID__ = "$Id$"
import os
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.Time import queryTime
class DirectoryMetadata:
def __init__(self, database=None):
self.db = database
def setDatabase(self, database):
self.db = database
... |
import base64
import logging
from cloudbot import hook
from cloudbot.util import async_util
logger = logging.getLogger("cloudbot")
@hook.on_cap_available("sasl")
def sasl_available(conn):
sasl_conf = conn.config.get('sasl')
return bool(sasl_conf and sasl_conf.get('enabled', True))
@hook.on_cap_ack("sasl")
async... |
""" :mod: FTSCleaningAgent
=======================
.. module: FTSCleaningAgent
:synopsis: cleaning old FTS
.. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com
Cleaning of the procesed requests in TransferDB.
:deprecated:
"""
__RCSID__ = "$Id $"
from DIRAC import S_OK
from DIRAC.Core.Base.AgentModul... |
def tests_event_handler():
from bigchaindb.events import (EventTypes, Event, EventHandler,
setup_events_queue)
# create and event
event_data = {'msg': 'some data'}
event = Event(EventTypes.BLOCK_VALID, event_data)
# create the events queue
events_queue = setup_... |
"""Allows beets to embed album art into file metadata."""
import os.path
import logging
import imghdr
from beets.plugins import BeetsPlugin
from beets import mediafile
from beets import ui
from beets.ui import decargs
from beets.util import syspath, normpath, displayable_path
from beets.util.artresizer import ArtResize... |
"""Wrapper script for running jobs in Taskcluster
This is intended for running test jobs in Taskcluster. The script
takes a two positional arguments which are the name of the test job
and the script to actually run.
The name of the test job is used to determine whether the script should be run
for this push (this is in... |
from optparse import OptionParser
import operator
import os
import subprocess
DEVNULL = open('/dev/null', 'w')
def inspect(dir_name):
"""Get font information from PDFs.
Recursively iterate over all the pdfs in a directory. For each found,
extract the font information and throw it in a dictionary with a coun... |
from pyload.core.utils.misc import random_string
def get_default_config(develop):
return DevelopmentConfig if develop else ProductionConfig
class BaseConfig:
DEBUG = False
TESTING = False
SESSION_COOKIE_SAMESITE = "Lax"
#: Extensions
# BCRYPT_LOG_ROUNDS = 13
# DEBUG_TB_ENABLED = False
DE... |
from openerp import models, api
class StockQuant(models.Model):
_inherit = 'stock.quant'
@api.multi
def _mergeable_domain(self):
"""Return the quants which may be merged with the current record"""
self.ensure_one()
return [('id', '!=', self.id),
('product_id', '=', se... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from shuup.core.fields import QuantityField
from shuup.utils.analog import define_log_model
class SuppliedProduct(models.Model):
supplier = models.ForeignKey("Supplier", on_delete=models.CASCADE, verbose_name=_("supplier"))
pro... |
from ast import literal_eval
import functools
import itertools
import logging
import psycopg2
from odoo import api, fields, models
from odoo import SUPERUSER_ID, _
from odoo.exceptions import ValidationError, UserError
from odoo.tools import mute_logger
_logger = logging.getLogger('base.partner.merge')
class MergePartn... |
from openerp import models, fields, api, exceptions, _
class MrpProduction(models.Model):
_inherit = 'mrp.production'
@api.one
@api.depends('analytic_line_ids', 'analytic_line_ids.estim_std_cost',
'product_qty')
def get_unit_std_cost(self):
self.std_cost = -(sum([line.estim_std_... |
import llnl.util.tty as tty
from spack import *
import spack.architecture
import os
class Openssl(Package):
"""OpenSSL is an open source project that provides a robust,
commercial-grade, and full-featured toolkit for the Transport
Layer Security (TLS) and Secure Sockets Layer (SSL) protocols.
I... |
class NumpyDocTools(object):
"""
Helper class to combine several orthogonal numpydocs
It can read numpy docstrings for multiple sources and combine these into one numpydoc
string. This mainly used for th features mixin to make sure the docstring of the
combined class is accurate.
Attributes
... |
from spack import *
class PyLzstring(PythonPackage):
"""lz-string for python."""
homepage = "https://github.com/gkovacs/lz-string-python"
url = "https://pypi.io/packages/source/l/lzstring/lzstring-1.0.3.tar.gz"
version('1.0.3', sha256='d54dd5a5f86837ccfc1343cc9f1cb0674d2d6ebd4b49f6408c35104f0a996cb... |
from django.views.generic.base import ContextMixin
from django.template.loader import render_to_string
class InlineView(ContextMixin):
template_name = None
def __init__(self, request, parent_view, parent_instance):
self.request = request
self.parent_view = parent_view
self.parent_instanc... |
import gettext
version_info = (0, 0, 5)
version = __version__ = ".".join(map(str, version_info))
gettext.install('asana') |
"""Classes and functions used to construct graphs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import linecache
import re
import sys
import threading
import six
from six.moves import xrange # pylint: disable=redefined-bu... |
import sys
import itertools
import uuid
from optparse import OptionParser
from urlparse import urlparse
import random
import six
from swift.common.manager import Manager
from swift.common import utils, ring
from swift.common.storage_policy import POLICIES
from swift.common.http import HTTP_NOT_FOUND
from swiftclient im... |
"""Test class for Ironic SeaMicro driver."""
import uuid
import mock
from seamicroclient import client as seamicro_client
from seamicroclient import exceptions as seamicro_client_exception
from ironic.common import boot_devices
from ironic.common import driver_factory
from ironic.common import exception
from ironic.com... |
from pyflink.java_gateway import get_gateway
from pyflink.table.types import _to_java_type
from pyflink.util import utils
__all__ = ['TableSink', 'CsvTableSink', 'WriteMode']
class TableSink(object):
"""
A :class:`TableSink` specifies how to emit a table to an external system or location.
"""
def __init... |
from mock import Mock
from mock import patch
from trove.common import pagination
from trove.guestagent.common import guestagent_utils
from trove.tests.unittests import trove_testtools
class TestGuestagentUtils(trove_testtools.TestCase):
def test_update_dict(self):
data = [{
'dict': {}, 'update':... |
import os
import os.path
import glob
import re
import logging
import fnmatch
from pyVim import vmconfig
from pyVmomi import vim
import pyVim
from pyVim.invt import GetVmFolder, FindChild
from error_code import *
import threadutils
import vmdk_ops
import auth_data_const
import auth
import auth_api
import log_config
from... |
from __future__ import unicode_literals
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
def template_failure(request, status=403, **kwargs):
""" Renders a SAML-specific template with general authentication error description. """
return render(request, 'djangosaml2/login_e... |
class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0 |
from st2common.util.monkey_patch import monkey_patch
monkey_patch()
from kombu import Exchange
from kombu.serialization import pickle
import os
import json
import pytest
import zstandard as zstd
from st2common.models.db.liveaction import LiveActionDB
from st2common.transport import publishers
from common import FIXTURE... |
from __future__ import absolute_import, division, print_function, unicode_literals
import codecs
import collections
import email
import os
import re
import stat
from .builder import BuilderBase, CMakeBuilder
WheelNameInfo = collections.namedtuple(
"WheelNameInfo", ("distribution", "version", "build", "python", "abi... |
"""
Unit tests for the sumatra.web module
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from builtins import object
import unittest
from datetime import datetime
class MockDataKey(object):
def __init__(self, path):
self.path = path
self.digest = "mock"
se... |
"""
Unspecified error handling tests
"""
import numpy as np
import os
from numba import jit, njit, typed, int64, types
from numba.core import errors
import numba.core.typing.cffi_utils as cffi_support
from numba.experimental import structref
from numba.extending import (overload, intrinsic, overload_method,
... |
from __future__ import print_function, unicode_literals
import os
import os.path as path
import tempfile
import unittest
import voodoo.configuration as ConfigurationManager
import voodoo.configuration as ConfigurationErrors
module1_code = """
mynumber = 5
mystr = "hello world"
"""
module2_code = """
mynumber = 6
mystr ... |
"""
@package mi.dataset.parser.mopak_o_dcl
@file marine-integrations/mi/dataset/parser/mopak_o_dcl.py
@author Emily Hahn
@brief Parser for the mopak_o_dcl dataset driver
Release notes:
initial release
"""
import ntplib
import struct
from mi.core.log import get_logger
from mi.core.common import BaseEnum
from mi.core.ins... |
from rest_framework.renderers import BaseRenderer
from rest_framework.renderers import BrowsableAPIRenderer
from rest_framework_json_api.renderers import JSONRenderer
class NoHTMLFormBrowsableAPIRenderer(BrowsableAPIRenderer):
"""Renders the browsable api, but excludes the forms."""
def get_context(self, *args,... |
""" Tests of XML Serializer tools """
from unittest import TestCase
from pythonzimbra.tools import xmlserializer
from xml.dom import minidom
from pythonzimbra.tools.xmlserializer import dom_to_dict
class TestXmlSerializer(TestCase):
def test_dict_to_dom(self):
""" Test xml serialization using dict_to_dom me... |
import ranger.api
from ranger.core.linemode import LinemodeBase
from .devicons import *
@ranger.api.register_linemode
class DevIconsLinemode(LinemodeBase):
name = "devicons"
uses_metadata = False
def filetitle(self, file, metadata):
return devicon(file) + ' ' + file.relative_path
@ranger.api.register_linemode... |
import functools
import numpy as np
from scipy.stats import norm as ndist
import regreg.api as rr
from selection.tests.instance import gaussian_instance
from selection.learning.utils import full_model_inference, pivot_plot
from selection.learning.core import normal_sampler, gbm_fit_sk
from selection.learning.learners i... |
'''
Usage:
diff-clang-format.py [--file-extension=<arg>...] [options] <path>...
Option:
-h --help Show this screen
-q --quiet Do not print the diff
--file-extension=<arg> Filename extension with a dot [default: .hpp .cpp]
--style=<style> Coding style sup... |
import logging
import time
from common import chrome_proxy_metrics
from common import network_metrics
from common.chrome_proxy_metrics import ChromeProxyMetricException
from telemetry.page import page_test
from telemetry.value import scalar
class ChromeProxyMetric(network_metrics.NetworkMetric):
"""A Chrome proxy tim... |
"""`Configuration` provider alias example."""
from dependency_injector import containers, providers
from environs import Env
class Container(containers.DeclarativeContainer):
config = providers.Configuration()
if __name__ == "__main__":
env = Env()
container = Container()
with container.config.some_plug... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
# Flag to indicate if this migration is too risky
# to run online and needs to be coordinated for offline
is_dangerous = True
def... |
from __future__ import absolute_import
from django.http import HttpRequest
from sentry.testutils import TestCase
from sentry.utils.session_store import RedisSessionStore
class RedisSessionStoreTestCase(TestCase):
def test_store_values(self):
request = HttpRequest()
request.session = {}
store... |
from django.db.models.loading import cache
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from imagekit.models import ImageModel
from imagekit.specs import ImageSpec
class Command(BaseCommand):
help = ('Clears all ImageKit cached files.')
args = '[apps]'
r... |
import sys
import warnings
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy import sparse
from .base import LinearModel, _pre_fit
from ..base import RegressorMixin
from .base import _preprocess_data
from ..utils import check_array, check_X_y
from ..utils.validation import check_random_state
from ..... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.