code stringlengths 1 199k |
|---|
import contextlib
import io
from logging import WARNING
import os
from pathlib import Path
import pytest
from devicetree import edtlib
HERE = os.path.dirname(__file__)
@contextlib.contextmanager
def from_here():
# Convenience hack to minimize diff from zephyr.
cwd = os.getcwd()
try:
os.chdir(HERE)
... |
from selenium.webdriver.firefox.webdriver import WebDriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.contact import ContactHelper
class Application:
def __init__(self):
self.wd = WebDriver()
#self.wd.implicitly_wait(5)
self.session = SessionHelper(self)
self.... |
class MacroFunction(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwds):
raise RuntimeError("can't call macro's directly")
def macro_expand(self, form):
return self.func(form) |
Graphing interface data
import pygal
line_chart = pygal.Line()
line_chart.title = 'Input/Output Packets and Bytes'
line_chart.x_labels = ['5','10','15','20','25','30','35','40','45','50','55','60']
line_chart.add('InPackets', <<variable data list>>)
rinse and repeat
line_chart.render_to_file('test_svg') |
"""
Command Tools
~~~~~~~~~~~~~
"""
import asyncio
import shlex
from asyncio import subprocess
__all__ = ['execute']
@asyncio.coroutine
def execute(command):
"""Execute a command."""
command = shlex.split(command)
# Create the subprocess, redirect the standard output into a pipe
process = yield ... |
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <gabriel.becedillas@gmail.com>
"""
import datetime
from engine import strategy
from engine import bar
from engine import logger
from engine.barfeed import membf
class TestBarFeed(membf.BarFeed):
def barsHaveAdjClose(self):
raise NotImplementedError()
clas... |
"""
Procfs for Win32. Simulates a proc fs for Win32 Python.
"""
import os
from pycopia.aid import sortedlist
class ProcStat(object):
"""Status information about a process. """
_STATINDEX = {
"command": 0,
"pid": 1,
}
# "RSDZTW"
_STATSTR = {
"R": "running",
"S": "sleeping",
"D":... |
from oslo_config import cfg
from oslo_log import log as logging
from osprofiler import profiler
import threading
from mistral import context as auth_ctx
from mistral.engine import base as eng
from mistral.event_engine import base as evt_eng
from mistral.executors import base as exe
from mistral.notifiers import base as... |
from collections import Iterable, Iterator
def g():
yield 1
yield 2
yield 3
print('Iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable))
print('Iterable? \'abc\':', isinstance('abc', Iterable))
print('Iterable? 123:', isinstance(123, Iterable))
print('Iterable? g():', isinstance(g(), Iterable))
print()
pr... |
'''
Non-relativistic generalized Hartree-Fock with point group symmetry.
'''
from functools import reduce
import numpy
import scipy.linalg
from pyscf import lib
from pyscf import symm
from pyscf.lib import logger
from pyscf.scf import hf_symm
from pyscf.scf import ghf
from pyscf.scf import chkfile
from pyscf import __c... |
'''
Created on Aug 16, 2014
Simple encapsulation of the result of a "command" that may include errors
Typically used for command line functions that can be composed easily
@author: Stan
'''
import sys
ERROR_UNDEFINED = -1 # error code meaning "command did not set errorcode"
ERROR_SUCCESS = 0
ERROR_INVALID_INPUT = 1 #... |
import sys
import pytest
from tests.support.helpers import VirtualEnv
@pytest.mark.parametrize(
"pip_version",
(
"pip==9.0.3",
"pip<20.0",
"pip<21.0",
"pip>=21.0",
),
)
def test_list_available_packages(modules, pip_version, tmp_path):
if sys.version_info < (3, 6) and pip_... |
from __future__ import print_function
import sys
import unittest
import SimpleITK as sitk
import numpy as np
class TestImageIndexingInterface(unittest.TestCase):
"""This tests the indexing feature for the Image class. """
def setUp(self):
pass
def assertImageNDArrayEquals(self, img, nda, msg=""):
... |
import plistlib
from django import forms
from django.db.models import Q
from realms.utils import build_password_hash_dict
from .app_manifest import build_enterprise_app_manifest
from .crypto import load_push_certificate_and_key
from .declarations import update_blueprint_declaration_items
from .dep import decrypt_dep_to... |
"""Holzmarkt beauty contest.
"""
import re, os, hashlib
from django import forms
from django.conf import settings
from django.core import mail
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render, redirect
from django.template.loader import render_to_string... |
import sys, os, re, time
import logging
import marshal, zlib
logging.basicConfig(level=logging.INFO, format='%(levelname)s - - %(asctime)s %(message)s', datefmt='[%d/%b/%Y %H:%M:%S]')
class DataBase(object):
def __init__(self):
self.conn = MySQLdb.connect(host='localhost',user='root', passwd='mac8.6', db='a... |
from bs4 import BeautifulSoup
from re import findall
from requests import get
from time import time
from errors_handler import notify
import os
class Web_Worker:
def __init__(self, n_of_links, n_of_pages, query):
self.n_of_pages = n_of_pages
self.n_of_links = n_of_links
sel... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('smartshark', '0017_auto_20160613_0914'),
]
operations = [
migrations.AlterModelOptions(
name='project',
options={'permissions': (('start_... |
import platform
import re
import sys
from typing import Any
from typing import Dict
from packaging import version
VERSIONS_NONE: Dict[str, Any] = dict(torchvision=None, torchcsprng=None)
VERSIONS_LUT: Dict[str, Dict[str, Any]] = {
"1.4.0": dict(torchvision="0.5.0", torchcsprng=None),
"1.5.0": dict(torchvision="... |
"""Local directory-specific hook implementations.
Since this file is located at the root of all ensembl-compara tests, every test in every subfolder will have
access to the plugins, hooks and fixtures defined here.
"""
from contextlib import ExitStack
import os
from pathlib import Path
import shutil
import time
from ty... |
"""models.py
Udacity conference server-side Python App Engine data & ProtoRPC models
$Id: models.py,v 1.1 2014/05/24 22:01:10 wesc Exp $
created/forked from conferences.py by wesc on 2014 may 24
wesc+api@google.com (Wesley Chun)
"""
import httplib
import endpoints
from protorpc import messages
from protorpc import mess... |
import numpy as np
import requests
import tifffile as tf
import sys
import os
import ndreg
from ndreg import preprocessor, util
import SimpleITK as sitk
import numpy as np
from intern.remote.boss import BossRemote
from intern.resource.boss.resource import *
import skimage
import argparse
import time
import configparser... |
from __future__ import unicode_literals
import sure # noqa
from flask.testing import FlaskClient
import moto.server as server
'''
Test the different server responses
'''
class AuthenticatedClient(FlaskClient):
def open(self, *args, **kwargs):
kwargs['headers'] = kwargs.get('headers', {})
kwargs['he... |
from model.address import Address
def test_match_addresses(app, json_addresses, db, check_ui):
address = json_addresses
db_addresses_list = db.get_address_list()
assert sorted(db_addresses_list, key=Address.id_or_max) == sorted(app.address.get_addresses_list(), key=Address.id_or_max) |
from __future__ import print_function
import argparse
import glob
import gzip
import random
import sys
import urllib
from utility import utility
parser = argparse.ArgumentParser(description = "This script generates an example raw log file based on a folder with example queries")
parser.add_argument("--exampleQueryFolde... |
""" P1 tests for Account
"""
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import (random_gen,
cleanup_resources,
validateList)
from marvin.cloudstackAPI import *
from marvin.lib.base import (Domain,
... |
import datetime
import re
import unittest
import log_file_search
class TestParseTestResults(unittest.TestCase):
def setUp(self):
self.content1 = [
"2016-03-07 23:08:31.706 27883 DEBUG ironic.cmd.conductor [-]i\
Configuration: main /opt/stack/old/ironic/ironic/cmd/conductor.py:43",
"... |
import contextlib
import copy
import datetime
import functools
import json
import os
import sys
import tempfile
import time
import unittest
from unittest import mock
import urllib
import eventlet
import fixtures
from oslo_config import cfg
from oslo_config import fixture as config_fixture
from oslo_utils import timeuti... |
'''
REX UT.
'''
import unittest
import sys
sys.path.append("../")
import rex
import re
import pprint
class REXUT(unittest.TestCase):
'''
REX unit tests.
'''
def test_reformat_pattern(self):
'''
test reformat_pattern API.
'''
print("test_reformat_pattern")
test_pat... |
import netaddr
from tempest import config
from tempest.lib import exceptions as lib_exc
from tempest import test
import testtools
from neutron.tests.api import base
from neutron.tests.tempest.common import tempest_fixtures as fixtures
CONF = config.CONF
class BgpSpeakerTestJSONBase(base.BaseAdminNetworkTest):
defau... |
import os
import sys
import time
import subprocess
import ctypes
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # not required after 'pip install uiautomation'
import uiautomation as auto
text = """The uiautomation module
This module is for UIAutomation on Windows(Windows XP with SP3, Win... |
"""Handles all requests relating to compute resources (e.g. guest vms,
networking and storage of vms, and compute hosts on which they run)."""
import functools
import re
import time
import novaclient
import webob.exc
from nova import block_device
from nova.compute import aggregate_states
from nova.compute import instan... |
"""
Paasta API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
import nulltype # noqa: F4... |
from __future__ import absolute_import, division, print_function, with_statement
__author__ = 'Ma'
import select
import ioloop
assert hasattr(select, 'kqueue'), 'kqueue not supported'
class KQueueIOLoop(object):
"""
基于 KQueue 的 IOLoop 模型
用于 BSD/Mac 系统
"""
def __init__(self):
self._kqueue = s... |
import copy
import mock
from nova.api.openstack.compute import hypervisors \
as hypervisors_v21
from nova import exception
from nova import objects
from nova import test
from nova.tests.unit.api.openstack.compute import test_hypervisors
from nova.tests.unit.api.openstack import fakes
def fake_compute_node_get(c... |
import pytest
import sqlalchemy
import sqlalchemy_utils.functions
import os
import passlib.apps as passlib_apps
import dci
import dci.app
import dci.dci_config
from dciclient.v1.api import context as api_context
from dciclient.v1.api import team as api_team
from dciclient.v1.api import product as api_product
from dcicl... |
from paddle.trainer.config_parser import *
__all__ = [
'ParamAttr', 'ExtraAttr', 'ParameterAttribute', 'ExtraLayerAttribute'
]
def convert_and_compare(x, Type):
"""
Convert x to be the same type as Type and then convert back to
check whether there is a loss of information
:param x: object to be chec... |
from collections import Mapping, UserString
from io import IOBase
from .platform import RERAISED_EXCEPTIONS
def is_integer(item):
return isinstance(item, int)
def is_number(item):
return isinstance(item, (int, float))
def is_bytes(item):
# FIXME: Should we add also bytearray?
return isinstance(item, byt... |
from __future__ import print_function
import unittest
import numpy as np
import paddle
import paddle.fluid.core as core
import paddle.fluid as fluid
from paddle.fluid import compiler, Program, program_guard
from op_test import OpTest, convert_uint16_to_float, convert_float_to_uint16
class TestCastOpFp32ToFp64(OpTest):
... |
"""
SlipStream Client
=====
Copyright (C) 2014 SixSq Sarl (sixsq.com)
=====
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... |
from oslotest import base as test_base
import six
from oslo.i18n import fixture
from oslo_i18n import _message
class FixtureTest(test_base.BaseTestCase):
def setUp(self):
super(FixtureTest, self).setUp()
self.trans_fixture = self.useFixture(fixture.Translation())
def test_lazy(self):
msg... |
import datetime
import socket
import sys
from collections import defaultdict
from typing import Dict
from typing import List
import choice
from paasta_tools import remote_git
from paasta_tools import utils
from paasta_tools.api.client import get_paasta_oapi_client
from paasta_tools.cli.cmds.mark_for_deployment import c... |
import argparse
import json
import pathlib
import shutil
import subprocess
import sys
import tempfile
import urllib.parse
import urllib.request
import zipfile
def main():
parser = argparse.ArgumentParser(
description='This script is able to download the latest artifacts for '
'all of the packages in... |
import datetime
from collections import OrderedDict
class NabarGeneralProfileForm(Form):
def __init__(self, data = None, items = None, post = None, **args):
if data is None: data = {}
if post is None: post = {}
if 'id' not in data:
data['id'] = 'NabarGeneralProfileForm'
super().__init__(data, items, **args)... |
from common.dbconnect import db_connect
from common.entities import KippoHoneypot
from canari.maltego.entities import IPv4Address
from canari.maltego.message import Field, UIMessage
from canari.framework import configure
__author__ = 'catalyst256'
__copyright__ = 'Copyright 2014, Honeymalt Project'
__credits__ = []
__l... |
from __future__ import (
absolute_import,
division,
generators,
nested_scopes,
print_function,
unicode_literals,
with_statement,
)
from collections import OrderedDict
from contextlib import contextmanager
import itertools
import json
import os
import shutil
from textwrap import dedent
import time
import t... |
import subprocess
import os
def ngs_qc_trigger(event, context):
"""
Cloud function that uses dsub (https://github.com/DataBiosphere/dsub) to execute
pipeline jobs using lifesciences api in GCP.
GCS EVENT TRIGGER:
Triggered by a change to a Cloud Storage bucket.
Function is triggered when a (e.g ... |
import requests
from bs4 import BeautifulSoup
import os
import threading
from time import sleep
def downloadimage(atlasdirname,count,suffix,url):
res = requests.get(url)
print('down {0} {1}{2}'.format(url,count,suffix))
file = open('{0}{1}{2}'.format(atlasdirname,count,suffix),'wb')
file.write(res.content)
def down... |
import argparse
import gzip
import json
import pprint
from argparse import Namespace
from datetime import datetime
from typing import Dict, List
import boto3
import requests
import sys
from boto3.dynamodb.types import Binary
from botocore.exceptions import ClientError, ProfileNotFound
def parse_args() -> Namespace:
... |
import vtk
def get_program_parameters():
import argparse
description = 'Building a graph using Unstructured Grid & dumping it into a vtk file.'
epilogue = '''
Building a graph using Unstructured Grid & dumping it into a vtk file, to be visualized using ParaView.
The generated file can then b... |
import os
def integrate():
# From the newly-included 'daf_fruit_dist' module, import the
# standard CI run.
from daf_fruit_dist.ci_utils import standard_sdist_run
# Test this package, then create a source distribution of it.
standard_sdist_run()
if __name__ == '__main__':
# Change active directo... |
"""Basic training loop example for one-vs-all classifiers."""
import os.path
from typing import Any, Callable, Dict, Iterator, List, Optional
from absl import logging
import tensorflow.compat.v2 as tf
import uncertainty_baselines as ub
import eval as eval_lib # local file import from experimental.one_vs_all
_TensorDic... |
import logging
from flask import Blueprint, g, jsonify, request, url_for
import airflow.api
from airflow import models
from airflow.api.common.experimental import delete_dag as delete, pool as pool_api, trigger_dag as trigger
from airflow.api.common.experimental.get_code import get_code
from airflow.api.common.experime... |
import json
import urllib
import urlparse
import datetime as dt
from datetime import datetime
from time import time
from jsonfield import JSONField
from django_extensions.db.fields import UUIDField
from django.db import models
from django.db import transaction
from django.conf import settings
from django.contrib.auth.m... |
"""Test for RFLink light components.
Test setup of RFLink lights component/platform. State tracking and
control of RFLink switch devices.
"""
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.rflink import EVENT_BUTTON_PRESSED
from homeassistant.const import (
ATTR_ENTITY_ID,
... |
import re
from functools import partial
from .misc import py2to3
from .normalizing import normalize
from .robottypes import is_string
def eq(str1, str2, ignore=(), caseless=True, spaceless=True):
str1 = normalize(str1, ignore, caseless, spaceless)
str2 = normalize(str2, ignore, caseless, spaceless)
return s... |
don't use unless corrected with pruned100
import time, glob,os,pickle, igraph, itertools, collections
import matplotlib.pylab as plt
import pandas as pd
from matplotlib import interactive
import numpy as np
from scipy.spatial import distance
print('extract termanalysis pruned')
print(time.asctime( time.localtime(time.t... |
import pt_rand
def reproduce(a,b, mutate_func, numkids = 10, mutate_chance=0.001):
kids = []
agenes = a.get_genes()
bgenes = b.get_genes()
#half-and-half -> 2
a1 = agenes[:len(agenes)/2]
a2 = agenes[len(agenes)/2:]
b1 = bgenes[:len(bgenes)/2]
b2 = bgenes[len(bgenes)/2:]
kids.append(organism(a1+b2))
kids.appen... |
"""Binary sensor support for the Skybell HD Doorbell."""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OCCUPANCY,
PLATFORM_SCHEMA,
BinarySensorEntity,
)
from homeassistant.const import CONF_EN... |
import os
import re
from pants.backend.python.subsystems.python_tool_base import PythonToolBase
from pants.backend.python.tasks.python_tool_prep_base import PythonToolInstance, PythonToolPrepBase
from pants.task.task import Task
from pants.util.contextutil import temporary_dir
from pants_test.backend.python.tasks.pytho... |
"""Unit tests for cinder.db.api."""
import datetime
from oslo_config import cfg
from cinder import context
from cinder import db
from cinder import exception
from cinder.openstack.common import uuidutils
from cinder.quota import ReservableResource
from cinder import test
CONF = cfg.CONF
def _quota_reserve(context, proj... |
import argparse
from os import name, system
from sys import argv
from vang.bitbucket.api import call
def create_repo(project, repo):
uri = f'/rest/api/1.0/projects/{project}/repos'
# request_data = f'{{"name":"{repo}","scmId":"git","forkable":true}}'
request_data = {'name': repo, 'scmId': 'git', 'forkable':... |
from __future__ import print_function
import os
import sys
import fnmatch
import subprocess
import tarfile
import shutil
import stat
import re
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
from setuptools import setup
from distutils.core import Extension
from dis... |
import os, sys, shutil, glob, numpy, csv, cPickle
import scipy.io.wavfile as wavfile
import audioBasicIO
import audioTrainTest as aT
import audioSegmentation as aS
import matplotlib.pyplot as plt
import scipy.spatial.distance
minDuration = 7;
def classifyFolderWrapper(inputFolder, modelType, modelName, outputMode=False... |
"""
Packets with metadata to use in testing of nmeta suite
This flow is IPv4 + TCP + HTTP with a GET returning a "HTTP/1.1
400 Bad Request"
Note: no testing of max_interpacket_interval and
min_interpacket_interval as they become imprecise due
to floating point and when tried using decimal module
found t... |
import os
from neutron.common import config
from neutron import context
from oslo.config import cfg
import unittest2
class TestBase(unittest2.TestCase):
'''Class to decide which unit test class to inherit from uniformly.'''
def setUp(self):
super(TestBase, self).setUp()
tox_path = os.environ.get... |
import logging
from oslo_log import log
from oslo_utils import timeutils
from senlin.common import exception
from senlin.common import i18n
from senlin.db import api as db_api
_LC = i18n._LC
_LE = i18n._LE
_LW = i18n._LW
_LI = i18n._LI
_ = i18n._
LOG = log.getLogger(__name__)
class Event(object):
'''Class capturing... |
from .. import ir
from ..jvmops import *
def visitLinearCode(irdata, visitor):
# Visit linear sections of code, pessimistically treating all exception
# handler ranges as jumps.
except_level = 0
for instr in irdata.flat_instructions:
if instr in irdata.except_starts:
except_level += ... |
from __future__ import absolute_import
from __future__ import division
import logging
import os
import socket
import time
import warnings
from guild import util
log = logging.getLogger("guild")
def version():
import tensorboard.version as version
return version.VERSION
def version_supported():
major_version... |
"""oss_fuzz_apply_ccs tests."""
import datetime
import unittest
import flask
import six
import webtest
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.tests.test_libs import helpers as test_helpers
from clusterfuzz._internal.tests.test_libs import test_utils
from handlers.cron import o... |
"""Carry out voice commands by recognising keywords."""
import datetime
import logging
import subprocess
import phue
from rgbxy import Converter
import actionbase
from vision.OCR import OCR
from vision.logo_detection import LogoDetection
from vision.face_detection import FaceDetection
from vision.label_detection import... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'openstack_installer.views.home', name='home'),
url(r'^', include('config.urls')),
# Uncomment the admin/doc line below to enable admin documentati... |
from flask import g, request
from functools import wraps
from nayami.config import API_TOKEN
from nayami.common.error import NoPermission
def user_auth(func):
@wraps(func)
def wrapper(*args, **kw):
g.user_agent = request.user_agent
g.user_ip = request.remote_addr
return func(*args, **kw)... |
"""Settings that need to be set in order to run the tests."""
import os
import logging
DEBUG = True
logging.getLogger("factory").setLevel(logging.WARN)
SITE_ID = 1
APP_ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3'... |
"""Local implementation for preprocessing, training and prediction for inception model.
"""
import apache_beam as beam
import collections
import json
import os
from . import _util
def _load_tf_model(model_dir):
from tensorflow.python.saved_model import tag_constants
from tensorflow.contrib.session_bundle import bun... |
"""
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 ... |
"""Install tensorflow_model_optimization."""
import datetime
import os
import sys
from setuptools import find_packages
from setuptools import setup
from setuptools.command.install import install as InstallCommandBase
from setuptools.dist import Distribution
version_path = os.path.join(
os.path.dirname(__file__), 't... |
from asyncio import sleep
import discord
import subprocess
import time
from datetime import datetime, timedelta
import sys
from pathlib import Path
import holidays
us_holidays = holidays.UnitedStates()
client = discord.Client()
client.started = False
@client.event
async def on_ready():
if client.started: # @Hack: Pro... |
import base64
import hashlib
import re
import sys
import xml.etree.ElementTree as ET
seenhashes = set()
scriptlines = 0
changing = False
new_hashes = {}
def hashstr(s):
md5 = hashlib.md5(s.encode())
return re.sub(r'=+$', '', base64.b32encode(md5.digest()[0:6]).decode())
def processsentence(sentence):
global... |
import logging
from django.forms import ValidationError # noqa
from django import http
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables # noqa
from horizon_lib import exceptions
from horizon_lib import forms
from horizon_lib import messages
from hor... |
import socket
import os
import sys
import sh
import docker
import textwrap
import netaddr
import docker.errors
from pycalico.ipam import IPAMClient
from netaddr.core import AddrFormatError
DOCKER_VERSION = "1.16"
ORCHESTRATOR_ID = "docker"
hostname = socket.gethostname()
client = IPAMClient()
docker_client = docker.Cli... |
'''
@author: ipapu
@Email : ipapu@qq.com
'''
class Manager(object):
#url管理器
def __init__(self):
self.new_urls=list()
self.old_urls=set()
def add_new_url(self,url):
#添加url
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
... |
from rainicorn.openstack.common.gettextutils import _
from rainicorn.openstack.common import log as logging
from rainicorn.openstack.common.notifier import rpc_notifier
LOG = logging.getLogger(__name__)
def notify(context, message):
"""Deprecated in Grizzly. Please use rpc_notifier instead."""
LOG.deprecated(_(... |
"""Controllers for the library page."""
import json
import logging
import string
from core.controllers import base
from core.domain import collection_services
from core.domain import exp_services
from core.domain import summary_services
from core.domain import user_services
from core.platform import models
import fecon... |
import requests
import datetime
import config
import logging
import json
log = logging.getLogger(__name__)
search="EC x8"
station="karlsruhe"
def findTrain(search,trains):
now = datetime.datetime.now()
for train in trains:
if(train['name']==search):
train["abfahrt"]=(int(train['time'][:2])*6... |
"""Fake RPC implementation which calls proxy methods directly with no
queues. Casts will block, but this is very useful for tests.
"""
import inspect
import json
import time
import eventlet
from heat.openstack.common.rpc import common as rpc_common
CONSUMERS = {}
class RpcContext(rpc_common.CommonRpcContext):
def ... |
"""
Security (SSL) Settings
Usage:
import libcloud.security
libcloud.security.VERIFY_SSL_CERT = True
# Optional.
libcloud.security.CA_CERTS_PATH.append('/path/to/cacert.txt')
"""
import os
import ssl
__all__ = [
'VERIFY_SSL_CERT',
'SSL_VERSION',
'CA_CERTS_PATH'
]
VERIFY_SSL_CERT = True
SSL_V... |
import argparse
import json
import os.path
import urllib.parse
from os.path import expanduser
import sys
from urllib.request import (
urlopen,
Request
)
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def num_commits_since_prev_tag(token, base_url):
tags_url = f"{base_url}/tags"
... |
from skimage import color
from skimage import io
from skimage.transform import rescale
from config import MAX_SIZE
def downscale_an_image(image):
"""
Если одна из сторон больше MAX_SIZE то уменьшаем в
(MAX_SIZE / max_shape) раз
:param image:
:return:
"""
max_shape = max(image.shape)
if m... |
"""Tools for testing."""
from __future__ import absolute_import, print_function, division
import time
import gzip
import struct
import traceback
import numbers
import sys
import os
import errno
import logging
import bz2
import zipfile
import json
from contextlib import contextmanager
from collections import OrderedDict... |
"""
Entity classes for representing the various Strava datatypes.
"""
import abc
import logging
from collections import Sequence
from stravalib import exc
from stravalib import unithelper as uh
from stravalib.attributes import (META, SUMMARY, DETAILED, Attribute,
TimestampAttribute, Lo... |
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.or... |
from __future__ import unicode_literals, absolute_import
import os
import re
import sys
import codecs
from ardublocklyserver import configparser
import ardublocklyserver.serialport
class ServerCompilerSettings(object):
"""
Singleton class that retrieves and saves the settings for the server side
compilation... |
"""Setup and activate a python virtual environment through setup."""
__author__ = ('Lance Finn Helsten',)
__version__ = '0.7.4'
__copyright__ = """Copyright (C) 2014 Lance Helsten"""
__docformat__ = "reStructuredText en"
__license__ = """
Licensed under the Apache License, Version 2.0 (the "License");
you may n... |
from hanlp.components.lm.mlm import MaskedLanguageModel
mlm = MaskedLanguageModel()
mlm.load('Langboat/mengzi-bert-base')
print(mlm('生活的真谛是[MASK]。'))
print(mlm(['生活的真谛是[MASK]。', '巴黎是[MASK][MASK]的首都。'])) |
from synergine.synergy.event.Event import Event
from intelligine.cst import COL_TRANSPORTER
class CycleEvent(Event):
_concern = COL_TRANSPORTER
def _prepare(self, object_id, context, parameters):
return parameters |
from connector import channel
from google3.cloud.graphite.mmv2.services.google.sql import instance_pb2
from google3.cloud.graphite.mmv2.services.google.sql import instance_pb2_grpc
from typing import List
class Instance(object):
def __init__(
self,
backend_type: str = None,
connection_name: ... |
"""
This module provides a collection functions for estimating the *distance*
between *k*-mer spectra or *k*-mer sets.
All the distance functions take a Boolean parameter which is used to
distinguish between the *k*-mer spectrum form (a vector of 4**k frequency
values) and the set form (a list/array of *k*-mer values).... |
"""
stats.py module
(Requires pstat.py module.)
A collection of basic statistical functions for python. The function
names appear below.
IMPORTANT: There are really *3* sets of functions. The first set has an 'l'
prefix, which can be used with list or tuple arguments. The second set has
an 'a' prefix, which can acc... |
"""
Constants for django Organice.
"""
ORGANICE_DJANGO_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
]
ORGANICE_CMS_APPS = [
'cms',
'mp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.