code stringlengths 1 199k |
|---|
import time
import unittest
from locust.core import HttpLocust, TaskSet, task
from locust.inspectlocust import get_task_ratio_dict
from locust.rpc.protocol import Message
from locust.stats import CachedResponseTimes, RequestStats, StatsEntry, diff_response_time_dicts, global_stats
from six.moves import xrange
from .tes... |
def paramsChecker(payload):
Temperature_Unit=["K","C","F","R"]
Pressure_Unit=["MPa","bar","atm","torr","psia"]
Density_Unit=["mol/l","mol/m3","g/ml","kg/m3","lb-mole/ft3","lbm/ft3"]
Energy_Unit=["kJ/mol","kJ/kg","kcal/mol","Btu/lb-mole","kcal/g","Btu/lbm"]
Velocity_Unit=["m/s","ft/s","mph"]
Viscosity_Unit=["uPa*s... |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import requests
import traceback
from typing import Dict, Any
requests.packages.urllib3.disable_warnings() # pylint: disable=no-member
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 format with UTC, def... |
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtCore, QtGui
class ScribbleArea(QtGui.QWidget):
def __init__(self, parent=None):
super(ScribbleArea, self).__init__(parent)
self.setAttribute(QtCore.Qt.WA_StaticContents)
self.modified = False
self.scrib... |
import lsh.utils.strings_utils as string_utils
from nose import tools as nt
def test_remove_all_whitespace():
# set up
test_str = 'a b c d'
expected_results = 'abcd'
# execution
actual_results = string_utils.remove_all_whitespace(test_str)
# asserts
nt.eq_(expected_results, actual_results)
d... |
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
import uuid
from .. import models
class FirewallRulesOperations(object):
"""FirewallRulesOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:p... |
__author__ = 'Ke Chen'
__email__ = "kec003@ucsd.edu"
try:
from urllib.request import urlopen
from urllib.request import build_opener
from urllib.request import HTTPCookieProcessor
from urllib.parse import urlparse
from urllib.parse import urlencode
except ImportError:
from urlparse import urlpar... |
#!/usr/bin/env python3
"""Dummy Socks5 server for testing."""
import socket
import threading
import queue
import logging
logger = logging.getLogger("TestFramework.socks5")
class Command:
CONNECT = 0x01
class AddressType:
IPV4 = 0x01
DOMAINNAME = 0x03
IPV6 = 0x04
def recvall(s, n):
"""Receive n byte... |
"""Internal support module for sre"""
import _sre, sys
import sre_parse
from sre_constants import *
assert _sre.MAGIC == MAGIC, "SRE module mismatch"
if _sre.CODESIZE == 2:
MAXCODE = 65535
else:
MAXCODE = 0xFFFFFFFFL
_LITERAL_CODES = set([LITERAL, NOT_LITERAL])
_REPEATING_CODES = set([REPEAT, MIN_REPEAT, MAX_RE... |
from matplotlib import pyplot as plt
from pandas import read_csv,DataFrame
data = read_csv('GISTEMPData2.csv')
frame = DataFrame(data).ix[:,['Year','Glob','NHem','SHem']]
frame.plot(x='Year',title='Deviation')
plt.savefig('GISTEMP.png') |
"""
Created on Mon Jun 11 22:49:47 2012
@author: cyb
"""
import csv
CORPUS = "E:/data/facebook/Data/"
def base_mode(DIR):
r = open(CORPUS + DIR + 'train.csv','r')
edges = set()
for edge in r:
[u1, u2] = edge.split()
edges.add((u1, u2))
missing_edges = set()
for edge in edges:
... |
from functools import partial
import os
from PyQt5 import (
QtCore,
QtGui,
QtWidgets,
)
from picard import (
config,
log,
)
from picard.ui import PicardDialog
class LogViewDialog(PicardDialog):
defaultsize = QtCore.QSize(570, 400)
def __init__(self, title, parent=None):
super().__ini... |
import rhythmdb, rb
import gobject
import gtk
import gconf, gnome
import gnomekeyring as keyring
import urllib
import zipfile
import sys, os.path
import xml
import datetime
import string
from MagnatuneSource import MagnatuneSource
popup_ui = """
<ui>
<popup name="MagnatuneSourceViewPopup">
<menuitem name="AddToQu... |
import logging
log = logging.getLogger("Thug")
def Seturl(self, val):
self.__dict__['url'] = val
log.ThugLogging.log_exploit_event(self._window.url,
"RediffBolDownloader ActiveX",
"Overflow in url property")
log.DFT.check_shellcode(... |
import gpgme
from StringIO import StringIO
ctx = gpgme.Context()
ctx.armor = True
key = ctx.get_key('B10A449E4CFB9A60A2DB996701AF93D991CFA34D')
plain = StringIO('Hello World\n')
cipher = StringIO()
ctx.encrypt([key], 0, plain, cipher)
print cipher.getvalue() |
__authors__ = "Marco Rizzuto, Daniel Kesler, Krios Mane"
__license__ = "GPL - https://opensource.org/licenses/GPL-3.0"
__version__ = "1.0"
import os
import json
from fabtotum.utils.translation import _, setLanguage
from fabtotum.fabui.macros.common import set_lights, getPosition
def initial_prism_homing(app, args=None,... |
from spacewalk.common.rhnLog import log_debug, log_error
from spacewalk.common.rhnConfig import CFG
from spacewalk.common.rhnException import rhnFault
from spacewalk.common.rhnTranslate import _
from spacewalk.common.RPC_Base import RPC_Base
from spacewalk.server import rhnServer
class rhnHandler(RPC_Base):
def __i... |
from wx.lib.iewin import IEHtmlWindow
class IE(IEHtmlWindow):
"""
Internet broser
"""
def setUrl(self, url):
try:
self.Navigate2(url or 'about:blank')
except AttributeError:
self.Navigate(url or 'about:blank') |
"""
Scientific methods for the TimeSeries dataTypes.
.. moduleauthor:: Stuart A. Knock <Stuart@tvb.invalid>
"""
import tvb.datatypes.time_series_data as time_series_data
class TimeSeriesScientific(time_series_data.TimeSeriesData):
"""
This class exists to add scientific methods to TimeSeriesData.
"""
__... |
from __future__ import print_function
from unicorn import *
from unicorn.sparc_const import *
SPARC_CODE = "\x86\x00\x40\x02" # add %g1, %g2, %g3;
ADDRESS = 0x10000
def hook_block(uc, address, size, user_data):
print(">>> Tracing basic block at 0x%x, block size = 0x%x" %(address, size))
def hook_code(uc, address... |
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
**************... |
from twisted.internet import reactor
from uo.entity import *
from gemuo.simple import simple_run
from gemuo.defer import deferred_nearest_reachable_item, deferred_skills
from gemuo.engine import Engine
from gemuo.engine.messages import PrintMessages
from gemuo.engine.guards import Guards
from gemuo.engine.watch import ... |
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from apps.admin.utils.decorator import access_required
from apps.seller.models.product import Product
@access_required('admin')
def home(request):
return render(request, 'research.html', {})
@access_required('admin')
def google... |
__doc__ = """JuniperBGPMap
Gather table information from Juniper BGP tables
"""
import re
from Products.DataCollector.plugins.CollectorPlugin import SnmpPlugin, GetMap, GetTableMap
class JuniperBGPMap(SnmpPlugin):
"""Map Juniper BGP table to model."""
maptype = "JuniperBGPMap"
modname = "ZenPacks.ZenSystems... |
from turbogears import testutil
from pkgdb.controllers import Root
import cherrypy
cherrypy.root = Root()
def test_method():
"the index method should return a string called now"
import types
result = testutil.call(cherrypy.root.index)
assert type(result["now"]) == types.StringType
def test_indextitle():... |
"""
Null output --- :mod:`MDAnalysis.coordinates.null`
==================================================
The :class:`NullWriter` provides a Writer instance that behaves like
any other writer but effectively ignores its input and does not write
any output files. This is similar to writing to ``/dev/null``.
This class e... |
import pyre.geometry.solids
from AbstractNode import AbstractNode
class Sphere(AbstractNode):
tag = "sphere"
def notify(self, parent):
sphere = pyre.geometry.solids.sphere(radius=self._radius)
parent.onSphere(sphere)
return
def __init__(self, document, attributes):
AbstractNo... |
from gandalf.analysis.facade import *
import numpy as np
import matplotlib.pyplot as plt
import sys
class DriftVelocitySolution(object):
def __init__(self, K, vg, vd, eps=None, rho=1):
self._K = K
self._vg0 = vg
self._vd0 = vd
self._dv0 = vd - vg
self._rho = rho
if e... |
from app import app
app.run(debug=True, host='0.0.0.0') |
import pandas as pd
import csv
import base64
from collections import defaultdict
import xml.etree.ElementTree as et
def decode(s):
s = base64.decodestring(s)
# Each number stored as a 4-chr representation (ascii value, not character)
l = []
for i in range(0, len(s), 4):
c = s[i:i + 4]
va... |
import collections
from abjad.tools import indicatortools
from abjad.tools import instrumenttools
from abjad.tools import scoretools
from abjad.tools.topleveltools import attach
from abjad.tools.abctools.AbjadValueObject import AbjadValueObject
class StringOrchestraScoreTemplate(AbjadValueObject):
r'''String orches... |
import dbus
import os
import struct
import weakref
import errno
import gobject
from blueman.main.Mechanism import Mechanism
from blueman.Functions import dprint
import stat
class RFKillType:
ALL = 0
WLAN = 1
BLUETOOTH = 2
UWB = 3
WIMAX = 4
WWAN = 5
GPS = 6
class RFKillOp:
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sessao', '0017_auto_20180316_0731'),
]
operations = [
migrations.RemoveField(
model_name='registrovotacao',
name='data_hora_atualizacao',... |
from plt_testing import *
t = get_example_trace('anon-v4.pcap')
n = nfp = 0; offset = 12
for pkt in t:
n += 1
if pkt.udp and (pkt.udp.src_port == 53 or pkt.udp.dst_port == 53):
nfp += 1
test_println("%4d:" % (n), get_tag())
print_udp(pkt.udp, offset, get_tag("n:"+str(n)))
test_p... |
from typing import Iterator
from dedop.model.l1a_processing_data import L1AProcessingData
from ...conf import ConstantsFile, CharacterisationFile, ConfigurationFile
from math import radians, isclose
class InputDataset:
def __init__(self, dataset, cst: ConstantsFile, chd: CharacterisationFile, cnf: ConfigurationFile... |
import re
import requests
from bs4 import BeautifulSoup
from cloudbot import hook
from cloudbot.util import web, formatting
steam_re = re.compile(r'.*://store.steampowered.com/app/([0-9]+)?.*', re.I)
API_URL = "http://store.steampowered.com/api/appdetails/"
STORE_URL = "http://store.steampowered.com/app/{}/"
def format... |
"""sqlalchemy.orm.interfaces.LoaderStrategy
implementations, and related MapperOptions."""
from .. import exc as sa_exc, inspect
from .. import util, log, event
from ..sql import util as sql_util, visitors
from . import (
attributes, interfaces, exc as orm_exc, loading,
unitofwork, util as orm_util
... |
"""
Wrap on-disk CD images based on the .cue file.
"""
import os
from whipper.common import encode
from whipper.common import common
from whipper.image import cue, table
from whipper.extern.task import task
from whipper.program.soxi import AudioLengthTask
import logging
logger = logging.getLogger(__name__)
class Image:... |
r"""
*******************************************************
**espressopp.integrator.GeneralizedLangevinThermostat**
*******************************************************
.. function:: espressopp.integrator.GeneralizedLangevinThermostat(system)
:param system:
:type system:
.. function:: espressopp.integrator.Gene... |
"""alphat class."""
from foamfile import FoamFileZeroFolder, foam_file_from_file
from collections import OrderedDict
class Alphat(FoamFileZeroFolder):
"""alphat class."""
# set default valus for this class
__default_values = OrderedDict()
__default_values['dimensions'] = '[0 2 -1 0 0 0 0]'
__default... |
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import os, re
from io import BytesIO
from functools import partial
from calibre import force_unicode, walk
from calibre.consta... |
from __future__ import with_statement
import os.path
import xml.etree.cElementTree as etree
import re
import sickbeard
from sickbeard import helpers
from sickbeard.metadata import helpers as metadata_helpers
from sickbeard import logger
from sickbeard import encodingKludge as ek
from sickbeard.exceptions import ex
from... |
try:
from setuptools import setup, find_packages, Extension
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages, Extension
import glob
import sys
from distutils import cmd, sysconfig
from distutils.command.build import build as _build
from distutils.... |
import numpy
from LOTlib.Hypotheses.LOTHypothesis import LOTHypothesis
from LOTlib.Miscellaneous import Infinity, beta, attrmem
from LOTlib.FunctionNode import FunctionNode
from collections import defaultdict
def get_rule_counts(grammar, t):
"""
A list of vectors of counts of how often each nonterminal ... |
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
import warnings
from article import *
from urlpath import *
if not 'mptt' in django_settings.INSTALLED_APPS:
raise ImproperlyConfigured('django-wiki: needs mptt in INSTALLED_APPS')
if not 'sekizai' in django_... |
"""
DBGET entry
"""
from __future__ import absolute_import
import warnings
from collections import defaultdict
from . import fields
from .parser import DBGETEntryParser
__all__ = ["parser", "fields"]
def entry_decorate(cls):
"""
Decorate the DBEntry subclass with properties for accessing
the fields through ... |
from sqlalchemy import exc, TypeDecorator, CHAR, String, create_engine, MetaData, bindparam
from sqlalchemy.engine import reflection
import warnings
import sys
import os
import argparse
import uuid
exec(open(os.path.dirname(os.path.realpath(__file__)) + os.path.sep + 'DataTypes.py').read())
try:
parser = argparse.A... |
from abjad import *
def test_mathtools_all_are_pairs_of_types_01():
assert mathtools.all_are_pairs_of_types([('a', 1), ('b', 2), ('c', 3), ('derp', 666)], str, int)
assert mathtools.all_are_pairs_of_types([], str, int)
def test_mathtools_all_are_pairs_of_types_02():
assert not mathtools.all_are_pairs_of_typ... |
from launcher.util.stack_config import StackConf
from test_library import run_playbook_test
import pytest
@pytest.fixture(scope="function")
def valid_service():
return {
'services': [{
'name': 'test_service',
'repo': 'test/repo',
'pull': False
}]
}
def test_pu... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = '''
---
module: iptables
short_description: Modify iptables rules
version_added: "2.... |
from wx import TreeItemData
from wxPython import wx, stc
import vb2py.custom.comctllib
from vb2py.targets.pythoncard.controlclasses import VBWrapped, VBWidget
import vb2py.logger
log = vb2py.logger.getLogger("VBTreeView")
from PythonCard.components import tree
from wxPython import wx
import sys
from PythonCard import e... |
from __future__ import print_function
from __future__ import unicode_literals
import os.path
import sys
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import unittest
from configobj import ConfigOb... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_tenant_span_src_group
short_description: Manage SPAN sourc... |
from __future__ import unicode_literals
import frappe
from erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings import get_shopping_cart_settings
from erpnext.shopping_cart.cart import get_debtors_account
from frappe.utils.nestedset import get_root_of
def set_default_role(doc, method):
'''Set cu... |
"""
``genomeCoverageBed`` :sup:`*`
-----------------------------------------------------------------
:Authors: Menachem Sklarz
:Affiliation: Bioinformatics core facility
:Organization: National Institute of Biotechnology in the Negev, Ben Gurion University.
A module for running bedtools genomecov:
The module builds a b... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('index', '0014_auto_20150903_0312'),
]
operations = [
migrations.RemoveField(
model_name='database',
name='instance',
),
... |
from stetl.output import Output
from stetl.util import Util
from stetl.packet import FORMAT
log = Util.get_log('standardoutput')
class StandardOutput(Output):
"""
Print any input to standard output.
consumes=FORMAT.any
"""
def __init__(self, configdict, section):
Output.__init__(self, config... |
from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from electrum.util import base_units
from electrum.i18n import languages
from electrum_gui.kivy.i18n import _
from electrum.plugins import run_hook
from electrum import coinchooser
from ele... |
from ansible.module_utils.arvados_common import process
def main():
additional_argument_spec={
"uuid": dict(required=True, type="str"),
"name": dict(required=True, type="str"),
"key_type": dict(required=False, type="str", default="SSH"),
"authorized_user_uuid": dict(required=True, ty... |
import datetime
import json
import logging
import os
from argparse import ArgumentParser
import cProfile
import requests
from redo import retry
from sqlalchemy import update, and_
from database.models import JobPriorities
from database.config import session, engine
from update_runnablejobs import update_job_priority_ta... |
import os, sys
import freesound as fs
import json
Key = "????????????"
descriptors = [ 'lowlevel.spectral_centroid.mean',
'lowlevel.spectral_centroid.var',
'lowlevel.mfcc.mean',
'lowlevel.mfcc.var',
'lowlevel.pitch_salience.mean',
'lowlevel... |
"""UDP Client-Server."""
import socket
target_host = "127.0.0.1"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.bind((target_host, target_port))
client.sendto("AAABBBCCC",(target_host,target_port))
data, addr = client.recvfrom(4096)
print(data) |
import mock
from contextlib import contextmanager
from odoo.tests.common import TransactionCase
from ..controllers import main
IMPORT = 'odoo.addons.password_security.controllers.main'
class EndTestException(Exception):
""" It allows for isolation of resources by raise """
class TestPasswordSecuritySession(Transact... |
import datetime
from django.db import migrations
from django.utils import timezone
from base.models.enums.academic_calendar_type import AcademicCalendarTypes
def change_exam_enrollment_calendar(apps, shema_editor):
AcademicYear = apps.get_model('base', 'academicyear')
AcademicCalendar = apps.get_model('base', '... |
import pytest
from django.db import transaction
from django.test import override_settings
from shuup.admin.modules.categories import CategoryModule
from shuup.admin.modules.categories.forms import (
CategoryBaseForm, CategoryProductForm
)
from shuup.admin.modules.categories.views import (
CategoryCopyVisibility... |
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from iati.models import Activity
from api.v3.resources.helper_resources import TitleResource, DescriptionResource, FinanceTypeResource
from api.cache import NoTransformCache
from api.v3.resour... |
from shinken_test import *
class TestLinkifyTemplate(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/nagios_linkify_template.cfg')
def test_linkify_template(self):
svc = self.conf.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
b = svc.is_correct()
sel... |
import os
import unittest
from queue import Queue
from clang.cindex import TranslationUnitLoadError
from bears.c_languages.codeclone_detection.ClangASTPrintBear import (
ClangASTPrintBear)
from tests.BearTestHelper import generate_skip_decorator
from coalib.settings.Section import Section
@generate_skip_decorator(C... |
"""
Test basic outgoing and incoming call handling
"""
from gabbletest import exec_test
from servicetest import call_async, assertEquals, assertNotEquals
from jingletest2 import JingleProtocol031
import constants as cs
from callutils import *
from config import VOIP_ENABLED
if not VOIP_ENABLED:
print "NOTE: built w... |
"""
Soap related methods and classes.
@author: ilgar
"""
from pyzimbra import zconstant, sconstant
from pyzimbra.base import ZimbraClientTransport
from pyzimbra.soap_soappy import parseSOAP, SoapHttpTransport
import SOAPpy
import logging
class SoapTransport(ZimbraClientTransport):
"""
Soap transport.
"""
... |
import sys
sys.path.append('Formats')
import Formats
class OrdMapper:
def __init__(self):
self.formats = []
for format in Formats.__formats__:
self.formats.append(format.__fileformat_desc__)
def generateMap(self, filename):
in_file = self.read(filename)
if not in_file:
return 0
for exp in in_file.symb... |
from base_ports import *
class Test_CPP_Int8(BaseVectorPort):
def __init__(self, methodName='runTest', ptype='Int8', cname='CPP_Ports' ):
BaseVectorPort.__init__(self, methodName, ptype, cname )
pass
class Test_CPP_Int16(BaseVectorPort):
def __init__(self, methodName='runTest', ptype='Int16', c... |
"""
This module provides simple session handling and WSGI Middleware.
You should instantiate SessionStore, and pass it to WSGI middleware
along with next WSGI application in chain.
Example:
>>> environ = {}
>>>
>>> def my_start_response(status, headers):
... environ['HTTP_COOKIE'] = headers[0][1]
...
>>> def my_app... |
{
'name' : 'Product lot',
'version' : '1.0.1',
'author' : 'IT-Projects LLC, Ivan Yelizariev',
'category' : 'Point Of Sale',
'website' : 'https://yelizariev.github.io',
'images': ['images/product-form.png'],
'depends' : ['product', 'stock'],
'data':[
'views.xml',
],
'i... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from resources.datatables import FactionStatus
from java.util import Vector
def addTemplate(core... |
"""File used to unit test the pacifica archive interface."""
from json import loads
import unittest
import time
from pacifica.archiveinterface.archive_utils import un_abs_path, get_http_modified_time
from pacifica.archiveinterface.id2filename import id2filename, filename2id
from pacifica.archiveinterface.exception impo... |
from glob import glob
import os
from bead.test import TestCase
from .test_robot import Robot
from bead.tech.timestamp import timestamp
from bead.workspace import Workspace
class Test_shared_box(TestCase):
# fixtures
def box(self):
return self.new_temp_dir()
def timestamp(self):
return timest... |
import os
COMPAT_MODE_HOST = os.environ.get('COMPAT_MODE_HOST', 'cpm.filmfest.by')
def compat_mode(request):
return {'in_compat_mode': request.get_host() == COMPAT_MODE_HOST} |
from metrics_consumer import * |
from ..azure_common import BaseTest, arm_template, cassette_name
from mock import patch
class HdinsightTest(BaseTest):
def test_hdinsight_schema_validate(self):
p = self.load_policy({
'name': 'test-hdinsight-schema-validate',
'resource': 'azure.hdinsight',
'actions': [
... |
import unittest, time, sys, json, re
sys.path.extend(['.','..','py'])
import h2o, h2o_hosts
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
localhost = h2o.decide_if_localhost()
if (localhost):
h2o.build... |
import os
import numpy
import pylab
pylab.ion()
from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import linkage, dendrogram
import crosscat.utils.general_utils as gu
import crosscat.utils.file_utils as fu
def save_current_figure(filename, dir='./', close=True, format=None):
if filename is not N... |
from __future__ import print_function
import paddle
import paddle.fluid as fluid
import contextlib
import math
import sys
import numpy
import unittest
import os
import numpy as np
paddle.enable_static()
def resnet_cifar10(input, depth=32):
def conv_bn_layer(input,
ch_out,
... |
"""Handle intents with scripts."""
import copy
import logging
import voluptuous as vol
from homeassistant.helpers import intent, template, script, config_validation as cv
DOMAIN = "intent_script"
CONF_INTENTS = "intents"
CONF_SPEECH = "speech"
CONF_ACTION = "action"
CONF_CARD = "card"
CONF_TYPE = "type"
CONF_TITLE = "t... |
import itertools
import random
from hashlib import sha1
from loremipsum import get_paragraphs, get_sentences
from uuid import uuid4
from changes.config import db
from changes.constants import Status, Result
from changes.db.utils import get_or_create
from changes.models import (
Project, Repository, Author, Revision... |
import novaclient.v2.client as nvclient
from system_tests.openstack_handler import OpenstackHandler
class OpenstackNovaNetHandler(OpenstackHandler):
# using the Config Readers of the regular OpenstackHandler - attempts
# of reading neutron-related data may fail but shouldn't happen from
# nova-net tests in ... |
import json
from flask import Flask, Response, request, render_template
from movies import movies_db, Movie
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/movies', methods=['GET', 'POST'])
def movies():
# We can ask the current request what method it is. If ... |
from __future__ import print_function
from bcc import BPF
from socket import inet_ntop, AF_INET, AF_INET6
from struct import pack
import argparse
import ctypes as ct
examples = """examples:
./tcpaccept # trace all TCP accept()s
./tcpaccept -t # include timestamps
./tcpaccept -p 181 # onl... |
import io
import re
import tokenize
from unittest import mock
import testtools
from neutron.hacking import checks
from neutron.tests import base
CREATE_DUMMY_MATCH_OBJECT = re.compile('a')
class HackingTestCase(base.BaseTestCase):
def assertLinePasses(self, func, line, *args, **kwargs):
with testtools.Expec... |
import six
from tempest.api.network import base
from tempest.common import utils
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators
class AllowedAddressPairTestJSON(base.BaseNetworkTest):
"""Tests the Neutron Allowed Address Pair API ex... |
from datetime import datetime
from typing import Any, Dict, Optional
from urllib import parse
from sqlalchemy.engine.url import URL
from superset.db_engine_specs.base import BaseEngineSpec
from superset.utils import core as utils
class DrillEngineSpec(BaseEngineSpec):
"""Engine spec for Apache Drill"""
engine =... |
"""Tests for tensorflow.ops.tf.Assign*."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow... |
"""
Pdb debugger class.
Modified from the standard pdb.Pdb class to avoid including readline, so that
the command line completion of other programs which include this isn't
damaged.
In the future, this class will be expanded with improvements over the standard
pdb.
The code in this file is mainly lifted out of cmd.py i... |
from openstackinabox.models.base_model import BaseModel
class ModelDbBase(BaseModel):
def __init__(self, name, master, db):
super(ModelDbBase, self).__init__(name)
self.__master = master
self.__db = db
@property
def master(self):
return self.__master
@property
def dat... |
import core.editor
class INIDoc(core.editor.EditorDocument):
def __init__(self):
core.editor.EditorDocument.__init__(self)
self._iniobj = None
class INIView(core.editor.EditorView):
pass |
"""
You won't need this unless you're trying to use it on 6.X
""" |
from __future__ import absolute_import
import numpy
import os
import glob
import tifffile as tiff
def load(tiff_filename):
"""
Import a TIFF file into a numpy array.
Arguments:
tiff_filename: A string filename of a TIFF datafile
Returns:
A numpy array with data from the TIFF file
""... |
"""
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 ... |
import sys, os
sys.path.insert(0, os.path.abspath('..'))
from config.all import *
language = 'ru' |
"""
A multi-heart Heartbeat system using PUB and ROUTER sockets. pings are sent out on the PUB,
and hearts are tracked based on their DEALER identities.
Authors:
* Min RK
"""
from __future__ import print_function
import time
import uuid
import zmq
from zmq.devices import ThreadDevice, ThreadMonitoredQueue
from zmq.even... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.