content
stringlengths
4
20k
import numpy from . import BokehHelp from ginga.canvas.mixins import * # force registration of all canvas types import ginga.canvas.types.all # Bokeh imports from bokeh.plotting import figure class RenderContext(object): def __init__(self, viewer): self.viewer = viewer self.shape = None ...
''' This is the GNU Radio LTE_fdd_dl_fs module. ''' # ---------------------------------------------------------------- # Temporary workaround for ticket:181 (swig+python problem) import sys _RTLD_GLOBAL = 0 try: from dl import RTLD_GLOBAL as _RTLD_GLOBAL except ImportError: try: from DLFCN import RTLD_GLOBAL ...
# This code is almost verbatim from: # http://blog.bjola.ca/2007/08/using-timeout-with-xmlrpclib.html try: import xmlrpclib from xmlrpclib import * except ImportError: # Python 3.0 portability fix... import xmlrpc.client as xmlrpclib from xmlrpc.client import * import httplib def Server(url, *args, **kwargs...
"""Internal implementation details of the peer review subsystem. Public classes, including domain objects, can be found in domain.py and models/student_work.py. Entities declared here should not be used by external clients. """ __author__ = [ '<EMAIL> (John Cox)', ] from models import counters from models import...
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL 3' __copyright__ = '2011, Anthon van der Neut <<EMAIL>>' __docformat__ = 'restructuredtext en' import os from subprocess import Popen, PIPE from cStringIO import Str...
from wsme import types as wtypes from solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types class Extension(api_types.Base): """The Extension resource represents changes that the Provider has added onto a Platform in addition to the ones supplied by Solum...
__author__ = 'calthorpe_analytics' def core_end_state_revert_to_base_condition(end_state, base): end_state.built_form_key = base.built_form_key end_state.built_form_base = None end_state.built_form_id = base.built_form_id end_state.land_development_category = None end_state.intersection_density_...
# Test the Unicode versions of normal file functions # open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir import os import sys import unittest import warnings from unicodedata import normalize from test import support filenames = [ '1_abc', '2_ascii', '3_Gr\xfc\xdf-Gott'...
# -*- coding: utf-8 -*- ## @package ivf.core.sfs.detail_layer # # ivf.core.sfs.detail_layer utility package. # @author tody # @date 2016/02/10 import cv2 from ivf.cv.image import to8U, to32F from ivf.core.guided_filter.guided_filter import GuidedFilter def baseDetailSeparationGaussian(I_32F, sigma=5.0...
#!/usr/bin/python # This script to be used to run liftOver on genotype data stored in # the plink format. # See: http://genome.sph.umich.edu/wiki/LiftOver # Downloaded from: http://genome.sph.umich.edu/wiki/LiftMap.py # # Modified by Scott Ritchie: # - to work with user specified chain files, rather than # the ori...
"""Unit tests for utilities for unit tests. See L{testutil}. """ from __future__ import with_statement import unittest import cPickle as pickle import sys import StringIO from testutil import BreakException, Opaque, Counter, MockRetry class TestOpaque(unittest.TestCase): """Unit tests for L{Opaque}.""" de...
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from django import VERSION as DJANGO_VERSION from django.conf import settings from django.core.exceptions import ImproperlyConfigured from haystack.utils import importlib __all__ = ['haystack_get_models', 'haystack_l...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 import ctypes import re def ValidHandle(value): if value == 0: raise ctypes.WinError() return value NULL = 0 HDEVINFO = ctypes.c_int BOOL = ctypes.c_int CHAR = ctypes.c_char PCTSTR = ctypes.c_char_p HWND = ctypes.c_uint DWORD = ctypes...
from __future__ import print_function import errno import gc import os import pprint import socket import sys import traceback import eventlet import eventlet.backdoor import greenlet from oslo.config import cfg from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging help_f...
import sys, os, re, urllib2, base64, subprocess, tempfile, shutil import json import datetime from optparse import OptionParser tmp_dir = None BASE_JIRA_URL = 'https://issues.apache.org/jira' BRANCHES = ["trunk", "0.7", "0.7.0", "0.7.1", "0.7.2", "0.8", "0.8.1", "0.8.2"] # Write output to file def write_file(filename...
import os from .util import Command class install_search_provider(Command): user_options = [] def initialize_options(self): self.install_dir = None self.search_provider = None self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ...
"""Functional tests for Concat Op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.platform impor...
#!/usr/bin/env python """Tests the SQLite data store.""" import shutil from grr.lib import access_control from grr.lib import config_lib from grr.lib import data_store from grr.lib import data_store_test from grr.lib import flags from grr.lib import test_lib from grr.lib import utils from grr.lib.data_stores import...
from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow from sympy.functions import exp, factorial, sin from sympy.logic import And from sympy.series import Limit from sympy.utilities.pytest import raises from sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, rational...
"""Some text manipulation utility functions. :group text formatting: normalize_text, normalize_paragraph, pretty_match,\ unquote, colorize_ansi :group text manipulation: searchall, splitstrip :sort: text formatting, text manipulation :type ANSI_STYLES: dict(str) :var ANSI_STYLES: dictionary mapping style identifier ...
# # iso2022_jp.py: Python Unicode Codec for ISO2022_JP # # Written by Hye-Shik Chang <<EMAIL>> # import _codecs_iso2022, codecs import _multibytecodec as mbc codec = _codecs_iso2022.getcodec('iso2022_jp') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.Mul...
from invenio.bibtask import write_message from invenio.weblinkback_config import CFG_WEBLINKBACK_TYPE from invenio.weblinkback import update_linkbacks, \ delete_linkbacks_on_blacklist, \ send_pending_linkbacks_notification def bst_weblinkback_updater(mod...
# coding=utf-8 from __future__ import division import numpy as _np from ..BaseEstimator import Estimator as _Estimator from ..Signal import UnevenlySignal as _UnevenlySignal, EvenlySignal as _EvenlySignal from ..filters.Filters import IIRFilter as _IIRFilter, DeConvolutionalFilter as _DeConvolutionalFilter, \ Convo...
"""Handles types registrations for tf.saved_model.load.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import versions_pb2 from tensorflow.core.protobuf import saved_object_graph_pb2 from tensorflow.python.util.tf_export i...
_GOODBYE_MESSAGE = u'Goodbye' def web_socket_do_extra_handshake(request): """Received Sec-WebSocket-Extensions header value is parsed into request.ws_requested_extensions. pywebsocket creates extension processors using it before do_extra_handshake call and never looks at it after the call. To rej...
from msgpack import packb, unpackb from collections import namedtuple from zlib import compress, decompress from struct import pack, unpack import asyncio from nectar.utils import logger from concurrent.futures import ThreadPoolExecutor Ack = namedtuple('Ack', ('value',)) PubKeyReply = namedtuple('PubKeyReply', ('key'...
import pyglet from dialog import Dialog from button import Button from vbox import VBox from hbox import HBox from slider import Slider from checkbox import Checkbox from label import Label from radiobutton import Radiobutton window = pyglet.window.Window(resizable=True) label1 = Label(text='<font face="Helvetica,Ari...
import sys def saveData(data): with open("list.txt", mode = "w", encoding="utf-8") as myFile: for str in data: if(not (str is data[0])): myFile.write('\n') myFile.write(str) def readData(): with open("list.txt", mode = 'r', encoding = 'utf-8') as myFile: ...
"""Define the kinds of data returned from the bugs tool.""" __author__ = '<EMAIL> (Jason Stredwick)' from common.util import class_attr class Kind(object): """Define kind keywords for the bugs tool.""" BUG = 'bugs#bug' ID = 'bugs#id' URL_BUG_MAP = 'bugs#url-bug-map' URLS = 'bugs#urls' # List of valid ki...
from __future__ import division import math from itertools import product import numpy as np from numpy.testing import (assert_raises, assert_allclose, assert_equal, assert_, run_module_suite) from scipy.sparse import csr_matrix, csc_matrix, lil_matrix from scipy.optimize._numdiff import (...
"""Provides data sources to use for benchmarking.""" import ConfigParser import glob import os import os.path import random import re import subprocess import sys import time # relative import addr_util import selectors import util # Pick the most accurate timer for a platform. Stolen from timeit.py: if sys.platform...
from ...pages.studio.auto_auth import AutoAuthPage from ...fixtures.course import CourseFixture from ..helpers import UniqueCourseTest from ...pages.studio.overview import CourseOutlinePage from ...pages.studio.utils import verify_ordering class StudioCourseTest(UniqueCourseTest): """ Base class for all Studi...
"""Wrappers for nearest neighbor operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.util import loader from tensorflow.python.framework import ops from tensorflow.python.platform import resource_loader _nearest_neighbor_...
from datetime import datetime import os import signal import sys import time from random import randint from gunicorn import util from gunicorn.workers.workertmp import WorkerTmp from gunicorn.reloader import Reloader from gunicorn.http.errors import ( InvalidHeader, InvalidHeaderName, InvalidRequestLine, Invalid...
import sys sys.path.append(sys.argv[0].rsplit('/', 1)[0] + "/ps_api") from gml import * from psx import * if len(sys.argv) < 2: sys.stderr.write("usage: ps_idc_gen <file 1> [file 2] [...] > import_changes.idc") sys.exit(1) # create the IDC script header. print "// Process Stalker - IDC Generator...
''' Copyright 2017 Akira Kashihara Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
# encoding: utf-8 import hmac import json import time import base64 import collections from website import settings # Written by @jmcarp originally def order_recursive(data): """Recursively sort keys of input data and all its nested dictionaries. Used to ensure consistent ordering of JSON payloads. """ ...
# -*- coding: utf-8 -*- """ pygments.lexers.elm ~~~~~~~~~~~~~~~~~~~ Lexer for the Elm programming language. :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, words, include from pygments.token impo...
""" =================================================== Label Propagation digits: Demonstrating performance =================================================== This example demonstrates the power of semisupervised learning by training a Label Spreading model to classify handwritten digits with sets of very few labels....
notifications = [ ] notificationAdded = [ ] # notifications which are currently on screen (and might be closed by similiar notifications) current_notifications = [ ] def __AddNotification(fnc, screen, id, *args, **kwargs): if ".MessageBox'>" in `screen`: kwargs["simple"] = True if ".Standby'>" in `screen`: rem...
from datetime import datetime, timedelta from uuid import uuid4 from cassandra.cqlengine.functions import get_total_seconds from tests.integration.cqlengine.base import BaseCassEngTestCase from cassandra.cqlengine.management import sync_table from cassandra.cqlengine.management import drop_table from cassandra.cqleng...
# test asynchat import asyncore, asynchat, socket, time import unittest import sys from test import test_support try: import threading except ImportError: threading = None HOST = test_support.HOST SERVER_QUIT = 'QUIT\n' if threading: class echo_server(threading.Thread): # parameter to determine t...
from optparse import make_option from twisted.internet import defer from deluge.ui.console.main import BaseCommand from deluge.ui.client import client import deluge.common import deluge.component as component class Command(BaseCommand): """Shows a various status information from the daemon.""" option_list = Ba...
try: import pyrax HAS_PYRAX = True except ImportError, e: HAS_PYRAX = False EXIT_DICT = dict(success=True) META_PREFIX = 'x-container-meta-' def _get_container(module, cf, container): try: return cf.get_container(container) except pyrax.exc.NoSuchContainer, e: module.fail_json(msg...
""" Module for GFXprim grabbers. """ # Import the SWIG wrapper from . import c_grabbers from ..utils import extend def extend_grabber(_Grabber): """ Extends _grabber class with convenience methods. Called once on module initialization. """ @extend(_Grabber) def start(self): "Starts frame capture." ...
from django.template.defaultfilters import ljust from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class LjustTests(SimpleTestCase): @setup({'ljust01': '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}'}) def test_lju...
'Power-control operations' from ncclient.xml_ import * from rpc import RPC PC_URN = "urn:liberouter:params:xml:ns:netconf:power-control:1.0" class PoweroffMachine(RPC): "*poweroff-machine* RPC (flowmon)" DEPENDS = ["urn:liberouter:param:netconf:capability:power-control:1.0"] def request(self): ...
""" The flight control tab shows telimitry data and flight settings. """ __author__ = 'Bitcraze AB' __all__ = ['FlightTab'] import sys import logging logger = logging.getLogger(__name__) from time import time from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import Qt, pyqtSlot, pyqtSignal, QThread, SIGNAL fr...
import logging from ryu.services.protocols.bgp.operator.command import Command from ryu.services.protocols.bgp.operator.command import CommandsResponse from ryu.services.protocols.bgp.operator.command import STATUS_ERROR from ryu.services.protocols.bgp.operator.command import STATUS_OK from ryu.services.protocols.bgp....
""" Kuwait-specific Form helpers """ from __future__ import unicode_literals import re from datetime import date from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field from django.utils.translation import gettext as _ id_re = re.compile(r'^(?P<i...
""" Unit test for endpoint websocket API. """ import unittest # Disable W0611: Unused import import tests.treadmill_test_deps # pylint: disable=W0611 from treadmill.websocket.api import endpoint class WSEndpointAPITest(unittest.TestCase): """Tests for endpoint websocket API.""" def test_subscribe(self): ...
import tensorflow as tf import numpy as np from vahun.autoencoder import Autoencoder class Autoencoder_FFNN(Autoencoder): def create_graph(self): network_weights = self._initialize_weights() self.weights = network_weights self._create_layers() # cost self.cost = ...
""" This config file follows the dev enviroment, but adds the requirement of a celery worker running in the background to process celery tasks. The worker can be executed using: django_admin.py celery worker """ # We intentionally define lots of variables that aren't used, and # want to import all variables from bas...
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## packet-loss-counter.h: ns3::PacketLossCounter [class] module.add_class('PacketLossCounter') ## udp-client.h: ns3::UdpClient [class] module.add_class(...
"""This file contains code used in "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2014 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import print_function import thinkstats2 import thinkplot import math import random import numpy as np d...
""" Map coloring problem in Google CP Solver. From Pascal Van Hentenryck 'The OPL Optimization Programming Language', page 7, 42. Compare with the following models: * Comet: http://www.hakank.org/comet/map.co * Tailor/Essence': http://hakank.org/tailor/map_coloring.eprime * SICStus: http://hakank.org/...
# numbers assert 2+2==4 assert (50-5*6)/4 == 5.0 assert 8/4*2 == 4.0 assert 8/5 == 1.6 assert 7//3 == 2 assert 7//-3 == -3 assert 4-2-2 == 0 width=20 height=5*9 assert width*height == 900 x = 6 x += 7+8 assert x == 21 x=y=z=0 assert x==0 assert y==0 assert z==0 # hex, octal, binary literals a=0xaf assert a==175 a=0...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from tests import support from tests.support import mock import dnf.comps import dnf.exceptions import dnf.persistor import dnf.util import libcomps import operator TRANSLATION=u"""Tato skupina zahrnuj...
""" Provides filtered attribute list classes. """ from suds import * from suds.umx import * from suds.sax import Namespace class AttrList: """ A filtered attribute list. Items are included during iteration if they are in either the (xs) or (xml) namespaces. @ivar raw: The I{raw} attribute list. ...
""" This module includes some utility functions for inspecting the layout of a GDAL data source -- the functionality is analogous to the output produced by the `ogrinfo` utility. """ from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal.geometries import GEO_CLASSES def ogrinfo(data_source, num_...
""" Data migration creation command """ from __future__ import print_function import sys import os import re from optparse import make_option try: set except NameError: from sets import Set as set from django.core.management.base import BaseCommand from django.core.management.color import no_style from djan...
import unittest import shutil import tempfile from zipfile import ZipFile from pydirl.app import create_app from . import populate_directory class PydirlZippedTestCase(unittest.TestCase): def setUp(self): self.root = tempfile.mkdtemp(prefix='pydirl_test_') populate_directory(self.root) def t...
""" Course navigation page object """ import re from bok_choy.page_object import PageObject from bok_choy.promise import EmptyPromise class CourseNavPage(PageObject): """ Navigate sections and sequences in the courseware. """ url = None def is_browser_on_page(self): return self.q(css='d...
#!/usr/bin/env python """ fleetctl base external inventory script. Automatically finds the IPs of the booted coreos instances and returns it under the host group 'coreos' """ # Copyright (C) 2014 Andrew Rothstein <andrew.rothstein at gmail.com> # # This program is free software: you can redistribute it and/or modify ...
# -*- coding: utf-8 -*- # # This file is part of sensim """Helpers for sentence semantic similarity model. .. Author:: Hussein AL-NATSHEH <<EMAIL>> """ """Helper functions.""" from .util import get_text from .util import group_by_sentence from .util import to_numeric from .util import sts_score from .util import d...
import atexit import os import random import re import subprocess import sys import threading import time from .hooks import addHook from .lang import _ from .utils import isMac, isWin, tmpdir # Shared utils ########################################################################## _soundReg = "\[sound:(.*?)\]" de...
import unittest from PySide2.QtCore import * from testbinding import TestObject class Foo(QObject): bar = Signal() class TestDisconnect(unittest.TestCase): def theSlot1(self): self.called1 = True def theSlot2(self): self.called2 = True def testIt(self): self.called1 = False ...
"""Provide animated GIF loops of Buienradar imagery.""" from __future__ import annotations import asyncio from datetime import datetime, timedelta import logging import aiohttp import voluptuous as vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.config_entries import Config...
SLOT_HELM = 1 SLOT_ARMOUR = 2 SLOT_SHIELD = 4 SLOT_GLOVE = 8 SLOT_RING = 16 SLOT_AMULET = 32 SLOT_BELT = 64 SLOT_BOOT = 128 SLOT_WEAPON = 256 SLOT_QUIVER = 512 SLOT_CLOAK = 1024 SLOT_ITEM = 2048 #quick item SLOT_SCROLL = 4096 SLOT_BAG = 8192 SLOT_POTION = 163...
from __future__ import with_statement import datetime import os import sys import unittest sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src')) import pyotp class HOTPExampleValuesFromTheRFC(unittest.TestCase): def testMatchTheRFC(self): # 12345678901234567890 in Bas32 ...
import os class Converter(object): @classmethod def convert_string(cls, param, value): # TODO: could do length validation, etc. here if not isinstance(value, basestring): raise ValueError return value @classmethod def convert_integer(cls, param, value): ...
import mimeparse def determine_format(request, serializer, default_format='application/json'): """ Tries to "smartly" determine which output format is desired. First attempts to find a ``format`` override from the request and supplies that if found. If no request format was demanded, it ...
"""Basic simplified data test functions - NOT FOR XML.""" from functools import wraps def task_a(a): """Function task_a docstring.""" @wraps(task_a) def _task_a(obj, eng): eng.log.info("executing task a " + str(a)) obj.data += a return _task_a def task_b(obj, eng): """Function t...
import wx from RunManager import RunManager import StringMap class RunDialog ( wx.Dialog ): def __init__( self, parent, tests ): wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 400, 300 ), style = wx.DEFAULT_DIALOG_STYLE ) self.initUI() s...
import site import os.path import sys def add(folder, index=1): """ Adds the given folder to the python path. Supports namespaced packages. By default, packages in the given folder take precedence over site-packages and any previous path manipulations. Args: folder: Path to the folder containing packag...
from subprocess import Popen,PIPE import shlex import logging class ExecProc: def __init__(self): self._command = None self._debug = False @property def debug(self): return self._debug @debug.setter def debug(self, debug): self._debug = debug @property ...
import wx import sys import os import time import threading import math import pynotify import pygame.mixer sys.path.append(os.getenv("PAPARAZZI_HOME") + "/sw/ext/pprzlink/lib/v1.0/python") from ivy_msg_interface import IvyMessagesInterface WIDTH = 150 HEIGHT = 40 UPDATE_INTERVAL = 250 class RadioWatchFrame(wx.Fr...
import _base class Filter(_base.Filter): def __init__(self, source, encoding): _base.Filter.__init__(self, source) self.encoding = encoding def __iter__(self): state = "pre_head" meta_found = (self.encoding is None) pending = [] for token in _base.Filter.__iter...
from appengine_wrappers import db from appengine_wrappers import BlobReferenceProperty BLOB_REFERENCE_BLOBSTORE = 'BlobReferenceBlobstore' class _Model(db.Model): key_ = db.StringProperty() value = BlobReferenceProperty() class BlobReferenceStore(object): """A wrapper around the datastore API that can store bl...
"""Logging """ import sys import logging from pip import backwardcompat class Logger(object): """ Logging object for use in command-line script. Allows ranges of levels, to avoid some redundancy of displayed information. """ VERBOSE_DEBUG = logging.DEBUG - 1 DEBUG = logging.DEBUG INFO =...
import Ice,sys,traceback Ice.loadSlice("RPCPybombs.ice") import RPCPybombs; from mod_pybombs import *; class ManagerI(RPCPybombs.Manager): def __init__(self,name): RPCPybombs.Manager.__init__(self) print "rpcpybombs manager init (%s)!"%(name) recipe_loader.load_all() print "recipes ...
"""Tests for record_input_op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.framework import test_util from tensorflow.python.framework.errors_impl import NotFoundError from tensorflow.python.lib.io import tf_record fr...
from django.db import models from django.conf import settings from datetime import datetime import time, random # Adapted from the custom XSLT Ftrain.com, written from 1998-2005. # This is not promoted as the right, or even a good, way to program a # CMS--it's a distillation of custom code in Perl, PHP, and XSLT/Java...
from __future__ import unicode_literals import os import shutil from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage from django.test import TestCase from pipeline import glob def local_path(path): return os.path.join(os.path.dirname(__file__), path) class Gl...
from PyQt4 import QtCore, QtGui from lib_openmolar.common.qt4.dialogs import BaseDialog from lib_openmolar.admin.qt4.classes.browser import Browser class KnownServerWidget(QtGui.QFrame): ''' loads the 230 servers @ startup. shows status of each. (most users will never use more than one 230 server) ...
import imp import os import sys def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" name = ".".join([package.__name__, module_name]) if name in sys.modules: return True for finder in sys.meta_path: if finder.find_module(name): return True ...
# -*- coding: utf-8 -*- import sys def getClassName(frame): try: # 取得目前工作在实例 self = f.f_locals[ 'self' ].__class__ try: # 只有内置的class类型才有这个属性 __mro__, 比如tuple, object等 mro = self.__mro__ except AttributeError: stack = [self] mro = [] while stack: curr = stack.pop(0) mro....
from gnuradio import gr, gr_unittest import ofdm_swig as ofdm class qa_channel_estimator_02 (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): # set up fg self.tb.run () # check data if ...
"""Self-test suite for Cryptodome.Hash.SHA""" from Cryptodome.Util.py3compat import * # Test vectors from various sources # This is a list of (expected_result, input[, description]) tuples. test_data = [ # FIPS PUB 180-2, A.1 - "One-Block Message" ('a9993e364706816aba3e25717850c26c9cd0d89d', 'abc'), # FI...
import argparse import serial import time def main(): # PARSE OPTIONS parser = argparse.ArgumentParser(description='A pyserial snippet.') parser.add_argument("--baudrate", "-b", help="The baudrate speed (e.g. 9600)", metavar="INTEGER", type=int, default=9600) parser.add_argument("--timeout", "-t", ...
#!/bin/env python import numpy as np import scipy.signal as ss import astropy.io.fits as fits import matplotlib.pyplot as plt inpt = str(raw_input("Nome do Arquivo: ")) lc = fits.open(inpt) bin = float(raw_input("bin size (or camera resolution): ")) # Convert to big-endian array is necessary to the lombscargle func...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( parse_duration, int_or_none, ) class AnySexIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?anysex\.com/(?P<id>\d+)' _TEST = { 'url': 'http://anysex.com/156592/', 'md5': '023...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from hashlib import sha1 import six from pants.base.exceptions import TargetDefinitionException from pants.build_graph.address import Address from pants.util.meta im...
import pytest from django.apps import apps from django.test import override_settings from shuup.core import MissingSettingException @pytest.mark.parametrize("setting_key, value, should_raise", [ ("PARLER_DEFAULT_LANGUAGE_CODE", None, True), ("PARLER_DEFAULT_LANGUAGE_CODE", False, True), ("PARLER_DEFAULT_...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param head, a ListNode # @return a boolean def isPalindrome(self, head): # Write your code here if head is None: return True s...
""" Utilities for django models. """ import unicodedata import re from eventtracking import tracker from django.conf import settings from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe from django_countries.fields import Country # The setting name used for events when "sett...
import certification import controllers
""" Additional asserts to supplement the :class:`TestCase` class. """ from taipan._compat import imap from taipan.collections import is_countable, is_iterable from taipan.lang import ABSENT from taipan.strings import BaseString, is_string __all__ = ['AssertsMixin'] class AssertsMixin(object): """Mixin providing...
from copy import deepcopy from .bertitos import tiny_bert_100k from .sparse_bertitos import tiny_bert_sparse_100k from .trifecta import ( KDLRRangeTestTrainer, small_bert_trifecta_100k, tiny_bert_trifecta_100k, ) """ These experiments to widen the BERT model and see the effect on eval/loss after pre-train...
from rhn.UserDictCase import UserDictCase from spacewalk.common import apache from spacewalk.common.rhnLog import log_debug from spacewalk.common.rhnException import rhnFault class BasePackageUpload: def __init__(self, req): self.header_prefix = "X-RHN-Upload" self.error_header_prefix = 'X-RHN-Up...