content
string
# -*- coding: utf-8 -*- # from django.conf import settings from .ansible.inventory import BaseInventory from common.utils import get_logger __all__ = [ 'JMSInventory', 'JMSCustomInventory', ] logger = get_logger(__file__) class JMSBaseInventory(BaseInventory): windows_ssh_default_shell = settings.WINDOWS...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests Task 04.""" # Import Python libs import unittest import task_04 class Task04TestCase(unittest.TestCase): """Test cases for Task 04.""" testmap = { 'not_enough_litterboxes': [2, 1, True, True], 'plenty_of_litterboxes': [1, 2, True, False...
""" Handle lease database updates from DHCP servers. """ from __future__ import print_function import os import sys import traceback from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import importutils from nova.conductor import rpcapi as conduc...
def test_nested_modules(): import pybind11_tests from pybind11_tests.submodule import submodule_func assert pybind11_tests.__name__ == "pybind11_tests" assert pybind11_tests.submodule.__name__ == "pybind11_tests.submodule" assert submodule_func() == "submodule_func()" def test_reference_internal...
# -*- coding: utf-8 -*- """ pygments.lexers.textedit ~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for languages related to text processing. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from bisect import bisect from pygments.lexer im...
from os.path import dirname, join from setuptools import setup, find_packages with open(join(dirname(__file__), 'scrapy/VERSION'), 'rb') as f: version = f.read().decode('ascii').strip() setup( name='Scrapy', version=version, url='http://scrapy.org', description='A high-level Web Crawling and Web...
""" sanlock lockspace initialization plugin. """ import gettext from otopi import plugin from otopi import util from ovirt_hosted_engine_setup import constants as ohostedcons def _(m): return gettext.dgettext(message=m, domain='ovirt-hosted-engine-setup') @util.export class Plugin(plugin.PluginBase): """...
'''Tools for interacting with VARYPED model equilibria''' import numpy as np from sys import argv import string import copy def create_db(file_path): '''Create a dictionary from a VARYPED results text file. Parameters: file_path -- string, path to the text file containing VARYPED results. The fi...
""" Provided code for Application portion of Module 2 Answers 4/6 Application Grade is 13 out of 15 Text Answers -Question 2: All three graphs are resilient in this case. Question5: -UPA and ER graphs are steel resilient (UPA is very close to overcoming 25% roughnes) in this type of attack. """ # general imports...
from functools import partial import numpy as np from skimage import img_as_float, img_as_uint from skimage import color, data, filters from skimage.color.adapt_rgb import adapt_rgb, each_channel, hsv_value from skimage._shared._warnings import expected_warnings # Down-sample image for quicker testing. COLOR_IMAGE =...
from __future__ import unicode_literals import json import re from .common import InfoExtractor from ..utils import int_or_none class CollegeHumorIE(InfoExtractor): _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/(video|embed|e)/(?P<videoid>[0-9]+)/?(?P<shorttitle>.*)$' _TESTS = [ { ...
import unittest from airflow.exceptions import AirflowException from airflow.providers.amazon.aws.sensors.sagemaker_base import SageMakerBaseSensor class TestSagemakerBaseSensor(unittest.TestCase): def test_execute(self): class SageMakerBaseSensorSubclass(SageMakerBaseSensor): def non_termina...
"""Tests for letsencrypt.auth_handler.""" import functools import logging import unittest import mock from acme import challenges from acme import client as acme_client from acme import messages from letsencrypt import errors from letsencrypt import le_util from letsencrypt.tests import acme_util TRANSLATE = { ...
"""Presubmit script for Chromium browser resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl/git cl, and see http://www.chromium.org/developers/web-development-style-guide for the rules we're checking against here. """ import ...
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda 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 3 of the License, or (at your option) any l...
from django.contrib.admin import ModelAdmin from django.contrib.gis.admin.widgets import OpenLayersWidget from django.contrib.gis.db import models from django.contrib.gis.gdal import HAS_GDAL, OGRGeomType from django.core.exceptions import ImproperlyConfigured spherical_mercator_srid = 3857 class GeoModelAdmin(Model...
import json import util from collections import defaultdict def get_fb_stats(freebase_data_file): with open(freebase_data_file) as fb: fact_counter = 0 relation_set = set() entity_set = set() for line in fb: line = line.strip() line = line[1:-1] ...
"""Tests for letsencrypt.proof_of_possession.""" import os import tempfile import unittest import mock from acme import challenges from acme import jose from acme import messages from letsencrypt import achallenges from letsencrypt import proof_of_possession from letsencrypt.display import util as display_util from...
""" Stub implementation of LTI Provider. What is supported: ------------------ 1.) This LTI Provider can service only one Tool Consumer at the same time. It is not possible to have this LTI multiple times on a single page in LMS. """ from uuid import uuid4 import textwrap import urllib from oauthlib.oauth1.rfc5849 ...
import contextlib import os import unittest import unittest.case from tap.i18n import _ from tap.runner import TAPTestResult from tap.tests import TestCase from tap.tracker import Tracker class FakeTestCase(unittest.TestCase): def runTest(self): pass @contextlib.contextmanager def subTest(self, ...
""" OpenERP - Server OpenERP is an ERP+CRM program for small and medium businesses. The whole source code is distributed under the terms of the GNU Public Licence. (c) 2003-TODAY, Fabien Pinckaers - OpenERP SA """ import atexit import csv import logging import os import signal import sys import threading import trac...
""" This module provide the function :py:func:`summary` that is used for printing an `execution summary <https://github.com/spotify/luigi/blob/master/examples/execution_summary_example.py>`_ at the end of luigi invocations. """ import textwrap import collections import functools import luigi class execution_summary...
"""Config flow to configure the Freebox integration.""" import logging from aiofreepybox.exceptions import AuthorizationError, HttpRequestError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_HOST, CONF_PORT from .const import DOMAIN # pylint: disable=unused-im...
from gcp_common import BaseTest from c7n_gcp.client import Session import mock import sys class NotifyTest(BaseTest): def test_pubsub_notify(self): factory = self.replay_flight_data("notify-action") orig_client = Session.client stub_client = mock.MagicMock() calls = [] ...
import sys import struct import random import optparse # This can be used as a module __all__ = ['QED_F_NEED_CHECK', 'QED'] QED_F_NEED_CHECK = 0x02 header_fmt = '<IIIIQQQQQII' header_size = struct.calcsize(header_fmt) field_names = ['magic', 'cluster_size', 'table_size', 'header_size', 'features', 'co...
from django.utils import six class FileProxyMixin(object): """ A mixin class used to forward file methods to an underlaying file object. The internal file object has to be called "file":: class FileProxy(FileProxyMixin): def __init__(self, file): self.file = file ...
import logging import os import re import time from collections import namedtuple from os import listdir from threading import Thread, Lock from odoo import http import odoo.addons.hw_proxy.controllers.main as hw_proxy _logger = logging.getLogger(__name__) DRIVER_NAME = 'scale' try: import serial except Impor...
""" A Django command that exports a course to a tar.gz file. If <filename> is '-', it pipes the file to stdout """ import os import shutil import tarfile from tempfile import mktemp, mkdtemp from textwrap import dedent from path import path from django.core.management.base import BaseCommand, CommandError from xm...
# coding: utf-8 from wtforms import TextField, TextAreaField, SelectField, BooleanField from wtforms.validators import DataRequired from flask.ext.babel import lazy_gettext as _ from ._base import BaseForm from ..models import Node class NodeForm(BaseForm): title = TextField( _('Title'), validators=[Dat...
import sys import os from PyQt4.QtSql import * #----------------------------------------------------------------------------- class FixCachedKeywords: #----------------------------------------------------------------------------- def __init__( self, parent ): self.parent = parent self.pgAssetName2...
"""Secret-key encryption algorithms. Secret-key encryption algorithms transform plaintext in some way that is dependent on a key, producing ciphertext. This transformation can easily be reversed, if (and, hopefully, only if) one knows the key. The encryption modules here all support the interface described in PEP 272...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} try: import boto3 from botocore.exceptions import ClientError HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False def list_mfa_devices(connection, module): user_nam...
''' UI namespace for the Flask application. ''' import flask from math import ceil import pkgdb2.forms import pkgdb2.lib as pkgdblib from pkgdb2 import SESSION, APP, is_admin from pkgdb2.ui import UI ## Some of the object we use here have inherited methods which apparently ## pylint does not detect. # pylint: disab...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests.mock import patch from ansible.modules.network.nxos import nxos_bgp_neighbor_af from .nxos_module import TestNxosModule, load_fixture, set_module_args class TestNxosBgpNeighborAfModule(TestNxosModule): ...
"""Tests for nova websocketproxy.""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.NoDBTestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.flags(console_...
from typing import Dict, Any, List, Optional, Union import uuid from .templates import TPL_DEP_SVG, TPL_DEP_WORDS, TPL_DEP_WORDS_LEMMA, TPL_DEP_ARCS from .templates import TPL_ENT, TPL_ENT_RTL, TPL_FIGURE, TPL_TITLE, TPL_PAGE from .templates import TPL_ENTS from ..util import minify_html, escape_html, registry from .....
import sys import csv import re from obudget.budget_lines.models import BudgetLine from django.core.management.base import BaseCommand class Command(BaseCommand): args = '<csv-file>' help = 'Parses csv''d budget data into the DB' def handle(self, *args, **options): reader = csv.DictReader(file(...
"""The bare-metal admin extension with Ironic Proxy.""" from oslo_config import cfg from oslo_log import log as logging from oslo_utils import importutils import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.i18n import _ ironic_client = importutils.try_import('ironicc...
class ModuleDocFragment(object): # OneView doc fragment DOCUMENTATION = ''' options: config: description: - Path to a .json configuration file containing the OneView client configuration. The configuration file is optional. If the file path is not provided, the configuration will be ...
"""Unittest main program""" import sys import argparse import os from . import loader, runner from .signals import installHandler __unittest = True MAIN_EXAMPLES = """\ Examples: %(prog)s test_module - run tests from test_module %(prog)s module.TestClass - run tests from module.TestClass ...
def should_throw(parser, harness, message, code): parser = parser.reset(); threw = False try: parser.parse(code) parser.finish() except: threw = True harness.ok(threw, "Should have thrown: %s" % message) def WebIDLTest(parser, harness): # The [Replaceable] extended att...
CODEBASE_API_USERNAME = "<EMAIL>" CODEBASE_API_KEY = "1234561234567abcdef" # The URL of your codebase setup CODEBASE_ROOT_URL = "https://YOUR_COMPANY.codebasehq.com" # When initially started, how many hours of messages to include. # Note that the Codebase API only returns the 20 latest events, # if you have more than...
import ctypes as ct class POINT(ct.Structure): _fields_ = [("x", ct.c_ulong), ("y", ct.c_ulong)] PUL = ct.POINTER(ct.c_ulong) GMEM_DDESHARE = 0x2000 class KEYBOARD_INPUT(ct.Structure): _fields_ = [("wVk", ct.c_ushort), ("wScan", ct.c_ushort), ("dwFlags", ct.c_ulong), ...
""" Blizzard BLP Image File Parser Author: Robert Xiao Creation date: July 10 2007 - BLP1 File Format http://magos.thejefffiles.com/War3ModelEditor/MagosBlpFormat.txt - BLP2 File Format (Wikipedia) http://en.wikipedia.org/wiki/.BLP - S3TC (DXT1, 3, 5) Formats http://en.wikipedia.org/wiki/S3_Texture_Compression ...
from functools import wraps from django.middleware.csrf import CsrfViewMiddleware, get_token from django.utils.decorators import available_attrs, decorator_from_middleware csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds...
""" The following objects are designed to work with the Database class, see Database.py for usage. """ import os import re import subprocess import MooseDocs from markdown.util import etree import logging log = logging.getLogger(__name__) class DatabaseItem(object): """ Base class for database items. Args: ...
# -*- coding: utf-8 -*- # Run with one of these commands: # > OPENERP_ADDONS_PATH='../../addons/trunk' OPENERP_PORT=8069 \ # OPENERP_DATABASE=yy PYTHONPATH=. python tests/test_ir_sequence.py # > OPENERP_ADDONS_PATH='../../addons/trunk' OPENERP_PORT=8069 \ # OPENERP_DATABASE=yy nosetests tests/test_ir_se...
""" =========================================================== Plot Ridge coefficients as a function of the regularization =========================================================== Shows the effect of collinearity in the coefficients of an estimator. .. currentmodule:: sklearn.linear_model :class:`Ridge` Regressi...
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.osv import osv, orm, fields from openerp.tools.translate import _ class sale_order_line(osv.Model): _inherit = "sale.order.line" _columns = { 'linked_line_id': fields.many2one('sale.order.line', 'Linked Order Line', domain="[('orde...
import os import re from setuptools import setup, find_packages def docs_read(fname): return open(os.path.join(os.path.dirname(__file__), 'docs', fname)).read() def version_read(): settings_file = open(os.path.join(os.path.dirname(__file__), 'lib', 'hsh', 'settings.py')).read() major_regex = """major_ve...
from __future__ import unicode_literals from collections import namedtuple from django.db.backends.base.introspection import ( BaseDatabaseIntrospection, FieldInfo, TableInfo, ) from django.utils.encoding import force_text FieldInfo = namedtuple('FieldInfo', FieldInfo._fields + ('default',)) class DatabaseIntr...
import sys import shapely.geometry import shapely.wkb import shapely.affinity from osgeo import ogr from osgeo import osr import json import codecs import copy class Map: def __init__(self, name, language): self.paths = {} self.name = name self.language = language self.width = 0 self.height = 0 ...
import operator from oslo_serialization import jsonutils import six from cinder.openstack.common.scheduler import filters class JsonFilter(filters.BaseHostFilter): """Host Filter to allow simple JSON-based grammar for selecting hosts. """ def _op_compare(self, args, op): """Returns True if t...
""" Server-side (i.e. worker side) Keystone notification related classes and logic. """ import oslo_messaging from oslo_service import service from barbican.common import utils from barbican import queue from barbican.tasks import keystone_consumer LOG = utils.getLogger(__name__) class NotificationTask(object): ...
import perf def main(context_switch = 0, thread = -1): cpus = perf.cpu_map() threads = perf.thread_map(thread) evsel = perf.evsel(type = perf.TYPE_SOFTWARE, config = perf.COUNT_SW_DUMMY, task = 1, comm = 1, mmap = 0, freq = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, context_sw...
""" API for managing user preferences. """ import logging import analytics from eventtracking import tracker from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError from django.utils.translation import ugettext as _ from django.utils.translation impor...
#!/usr/bin import probabilisticgraph as pg import graphgenerator as gg import dmarkov as dm import sequenceanalyzer as sa import yaml import matplotlib.pyplot as plt import synchwordfinder as swf def main(config_file, fsw=False, terminate=False, dmark=False, generate=False, gen_seq=False, an_seq=False, plot=False, ...
# System built-in modules import time from datetime import datetime import sys import os from multiprocessing import Pool # Project dependency modules import pandas as pd pd.set_option('mode.chained_assignment', None) # block warnings due to DataFrame value assignment import lasagne # Project modules sys.path.append('...
SwCDR DEFINITIONS IMPLICIT TAGS ::= BEGIN EXPORTS SwCDR; SwCDR ::= CHOICE { origSvcCallRecord [0] OrigSvcCallRecord, termSvcCallRecord [1] TermSvcCallRecord } --OrigSvcCallRecord ::= SET OrigSvcCallRecord ::= SEQUENCE { callCorrelationId [0] INTEGER , chargingIndicator [1] ChargingIndicator, ...
import sys if sys.version_info[0] >= 3: # Python 3 import tkinter as tk from tkinter import ttk from tkinter import messagebox as msgbox else: import Tkinter as tk import tkMessageBox as msgbox import ttk import random import pjsua2 as pj import application import endpoint as ep # Call class class Call(pj.Call)...
import alembic from nailgun.db import dropdb from nailgun.db.migration import ALEMBIC_CONFIG from nailgun.test import base class TestDbMigrations(base.BaseTestCase): def test_clean_downgrade(self): # We don't have data migration for clusters with vip_type 'ovs' # so checking migration only for c...
""" Utilities that manipulate strides to achieve desirable effects. An explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. """ from __future__ import division, absolute_import, print_function import numpy as np __all__ = ['broadcast_arrays'] class DummyArray(object): """...
class PossibleBrowser(object): """A browser that can be controlled. Call Create() to launch the browser and begin manipulating it.. """ def __init__(self, browser_type, target_os, finder_options, supports_tab_control): self._browser_type = browser_type self._target_os = target_os se...
"""BookmarkModel: python representation of the bookmark model. Obtain one of these from PyUITestSuite::GetBookmarkModel() call. """ import os import simplejson as json import sys class BookmarkModel(object): def __init__(self, json_string): """Initialize a BookmarkModel from a string of json. The JSON re...
# VERSION 1.1.5 # Updated by Alexandre da Silva for GMate Project (http://blog.siverti.com.br/gmate) import gedit, gtk, gtk.glade import gconf import gnomevfs import pygtk pygtk.require('2.0') import os, os.path, gobject # set this to true for gedit versions before 2.16 pre216_version = False max_result = 50 ui_str...
""" Support for D-link W215 smart switch. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.dlink/ """ import logging import voluptuous as vol from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA) from homeassistant.const impo...
import unittest import settestpath import mainmenu class MainMenuModelTests(unittest.TestCase): def setUp(self): self.model = mainmenu.MainMenuModel("program name") def testSelectBorderValues(self): try: self.model.select(-1) self.fail() except: ...
{ 'name' : 'eInvoicing', 'version' : '1.1', 'author' : 'OpenERP SA', 'category' : 'Accounting & Finance', 'description' : """ Accounting and Financial Management. ==================================== Financial and accounting module that covers: -------------------------------------------- * Gen...
# # test cases for new-style fields # from datetime import date, datetime from collections import defaultdict from openerp.tests import common from openerp.exceptions import except_orm class TestNewFields(common.TransactionCase): def test_00_basics(self): """ test accessing new fields """ # find...
import openerp from openerp import SUPERUSER_ID from openerp import tools from openerp.osv import orm, fields from openerp.modules.registry import RegistryManager class decimal_precision(orm.Model): _name = 'decimal.precision' _columns = { 'name': fields.char('Usage', select=True, required=True), ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Supporting math for the consensus mechanism. """ from __future__ import division from numpy import * from numpy.linalg import * def WeightedMedian(data, weights): """Calculate a weighted median. Args: data (list or numpy.array): data weights (list...
''' Ultimate Whitecream Copyright (C) 2015 mortael 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 3 of the License, or (at your option) any later version. ...
""" Provides a set of pluggable permission policies. """ from __future__ import unicode_literals from django.http import Http404 from rest_framework.compat import get_model_name SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class BasePermission(object): """ A base class from which all permission classes should...
from __future__ import division, absolute_import, print_function import os import re import sys from test._common import unittest pkgpath = os.path.dirname(__file__) or '.' sys.path.append(pkgpath) os.chdir(pkgpath) def suite(): s = unittest.TestSuite() # Get the suite() of every module in this directory b...
# coding: utf-8 from __future__ import unicode_literals import uuid from .common import InfoExtractor from .ooyala import OoyalaIE from ..compat import ( compat_str, compat_urllib_parse_urlencode, compat_urlparse, ) from ..utils import ( int_or_none, extract_attributes, determine_ext, smug...
import numpy as np import cv2 import time import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import rcParams import SimpleITK as sitk from multiprocessing import Process, Pipe, Value from matplotlib.widgets import Slider, Button rcParams['font.family'] = 'serif' #ps aux | grep pyth...
{ 'name': 'Purchase Requisitions', 'version': '0.1', 'author': 'OpenERP SA', 'category': 'Purchase Management', 'website': 'https://www.odoo.com/page/purchase', 'description': """ This module allows you to manage your Purchase Requisition. ========================================================...
""" Represents a Network ACL """ from boto.ec2.ec2object import TaggedEC2Object from boto.resultset import ResultSet class Icmp(object): """ Defines the ICMP code and type. """ def __init__(self, connection=None): self.code = None self.type = None def __repr__(self): re...
"""This module is a ad-hoc command processor for xmpppy. It uses the plug-in mechanism like most of the core library. It depends on a DISCO browser manager. There are 3 classes here, a command processor Commands like the Browser, and a command template plugin Command, and an example command. To use this module: Ins...
import sys import os try: import py2exe.mf as modulefinder import win32com for p in win32com.__path__[1:]: modulefinder.AddPackagePath("win32com", p) for extra in ["win32com.shell"]: __import__(extra) m = sys.modules[extra] for p in m.__path__[1:]: ...
import logging import urllib from django import template from django.template.defaulttags import url, URLNode from django.urls import get_script_prefix register = template.Library() logger = logging.getLogger(__name__) class NoPrefixURLNode(URLNode): def __init__(self, url_node): super(NoPrefixURLNode, ...
""" FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol. Uses the flup python package: http://www.saddi.com/software/flup/ This is a adaptation of the flup package to add FastCGI server support to run Django apps from Web servers that support the FastCGI protocol. This module can be run standalo...
from __future__ import print_function import os import time import json import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Lambda from keras.optimizers import Nadam as Trainer #from keras.optimizers import Adam as Trainer from keras.regularizers import WeightRe...
from test import support import unittest import sys, os, io, subprocess import quopri ENCSAMPLE = b"""\ Here's a bunch of special=20 =A1=A2=A3=A4=A5=A6=A7=A8=A9 =AA=AB=AC=AD=AE=AF=B0=B1=B2=B3 =B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE =BF=C0=C1=C2=C3=C4=C5=C6 =C7=C8=C9=CA=CB=CC=CD=CE=CF =D0=D1=D2=D3=D4=D5=D6=D7 =D8=D9=DA=D...
from utils import propagate_expose import math import cairo import gtk class MenuWindow(gtk.Window): def __init__(self): gtk.Window.__init__(self, gtk.WINDOW_POPUP) self.__init_values() self.__init_settings() self.__init_events() def __init_values(self): self.on_paint_...
import sys import re from subprocess import Popen, PIPE from xml.etree import ElementTree HEAD = '/passwords/' def insert_data(path,text): """ Insert data into the password store. (1) removes HEAD from path (2) ensures text ends with a new line and encodes in UTF-8 (3) inserts """ global HEAD...
""" GIF picture parser. Author: Victor Stinner """ from lib.hachoir_parser import Parser from lib.hachoir_core.field import (FieldSet, ParserError, Enum, UInt8, UInt16, Bit, Bits, NullBytes, String, PascalString8, Character, NullBits, RawBytes) from lib.hachoir_parser.image.common import PaletteRGB fr...
"""A deep MNIST classifier using convolutional layers. Sample usage: python mnist.py --help """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import functools import os import sys import time import tensorflow as tf import tensorflow....
import nest nest.sli_run("statusdict/have_music ::") if not nest.spp(): import sys print("NEST was not compiled with support for MUSIC, not running.") sys.exit() mmip = nest.Create('music_message_in_proxy') nest.SetStatus(mmip, {'port_name' : 'msgdata'}) # Simulate and get message data with a granularity...
"""SignatureDef utility functions. Utility functions for constructing SignatureDef protos. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from tensorflow.python.saved_model.signature_def_utils_impl import build_signature...
import account_analytic_journal_report import account_analytic_balance_report import account_analytic_inverted_balance_report import account_analytic_cost_ledger_report import account_analytic_cost_ledger_for_journal_report import project_account_analytic_line import account_analytic_chart # vim:expandtab:smartindent:...
import os from dotgit.plugins.plain import PlainPlugin class TestPlainPlugin: def test_apply(self, tmp_path): plugin = PlainPlugin(str(tmp_path / 'data')) data = 'test data' with open(tmp_path / 'file', 'w') as f: f.write(data) plugin.apply(tmp_path / 'file', tmp_pa...
import base58 from neo.Settings import settings from neo.Core.Fixed8 import Fixed8 from typing import Tuple def isValidPublicAddress(address: str) -> bool: """Check if address is a valid NEO address""" valid = False if len(address) == 34 and address[0] == 'A': try: base58.b58decode_ch...
""" Python 'utf-16-le' Codec Written by Marc-Andre Lemburg (<EMAIL>). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_16_le_encode def decode(input, errors='strict'): return codecs.utf_16_le_decode(input, errors, True) class IncrementalEncoder(codec...
r""" Bending of a long thin cantilever beam computed using the :class:`dw_shell10x <sfepy.terms.terms_shells.Shell10XTerm>` term. Find displacements of the central plane :math:`\ul{u}`, and rotations :math:`\ul{\alpha}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}, \ul{\beta}) e_{kl}(\ul{u}, \ul...
"""A collection of modules for building different kinds of tree from HTML documents. To create a treebuilder for a new type of tree, you need to do implement several things: 1) A set of classes for various types of elements: Document, Doctype, Comment, Element. These must implement the interface of _base.treebuilders...
from __future__ import unicode_literals import json from .common import InfoExtractor from ..utils import ( remove_start, int_or_none, ) class BlinkxIE(InfoExtractor): _VALID_URL = r'(?:https?://(?:www\.)blinkx\.com/#?ce/|blinkx:)(?P<id>[^?]+)' IE_NAME = 'blinkx' _TEST = { 'url': 'http:...
# -*- coding:utf8 -*- from __future__ import print_function import codecs def caluPAndRAndF1(file1, file2): ''' 计算准确率p和召回率r,f1值 file1: 参考文件 file2: 处理后文件 ''' with codecs.open(file1, 'r', 'utf8') as fin1: with codecs.open(file2, 'r', 'utf8') as fin2: line1 = fin1.readline() ...
from telemetry.page import cache_temperature as cache_temperature_module from telemetry.page import page as page_module from telemetry.page import shared_page_state from telemetry import story class ToughLayoutCasesPage(page_module.Page): def __init__(self, url, page_set, cache_temperature=None): super(ToughLa...
import unittest from pool import Pool def Run(x): if x == 10: raise Exception("Expected exception triggered by test.") return x class PoolTest(unittest.TestCase): def testNormal(self): results = set() pool = Pool(3) for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]): resu...