code
stringlengths
1
199k
from peyotl.phylo.tree import parse_newick from peyotl.nexson_syntax import get_empty_nexson from peyotl import write_as_json import codecs import json import sys import os import re _ID_EXTRACTOR = re.compile(r'^.*[^0-9]([0-9]+)$') _ALL_DIGIT_ID_EXTRACTOR = re.compile(r'^([0-9]+)$') def ott_id_from_label(s): x = _...
from streamlink.plugins.rtpa import RTPA from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlRTPA(PluginCanHandleUrl): __plugin__ = RTPA should_match = [ "https://www.rtpa.es/tpa-television", "https://www.rtpa.es/video:Ciencia%20en%2060%20segundos_551644582052.html", ]
""" This tool will send a PNaCl Git change to the trybots for testing. This tool is intended for testing changes to the PNaCl Git repositories that are checked out under subdirectories of pnacl/git/. It should be run from one of these subdirectories. The tool sends changes to the PNaCl toolchain trybots. Example usage...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Women' db.delete_table(u'survey_women') def backwards(self, orm): # Adding model 'Women' db.creat...
from sympy import sin, cos, symbols, pi, ImmutableMatrix as Matrix from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols from sympy.physics.vector.dyadic import _check_dyadic from sympy.utilities.pytest import raises Vector.simp = True A = ReferenceFrame('A') def test_dyadic(): d1 = A.x | A.x ...
from django.core.management.base import BaseCommand, CommandError from program.models import ProgramSlot class Command(BaseCommand): help = 'removes the automation_id from the program slots' args = '<automation_id>' def handle(self, *args, **options): if len(args) == 1: automation_id = a...
import types import pytest import numpy as np from numpy.testing import assert_allclose from numpy.random import RandomState from astropy.modeling.core import Fittable1DModel from astropy.modeling.parameters import Parameter from astropy.modeling import models from astropy.modeling import fitting from astropy.utils.exc...
from django.contrib.gis.gdal import HAS_GDAL from django.core.serializers.base import SerializerDoesNotExist from django.core.serializers.json import Serializer as JSONSerializer if HAS_GDAL: from django.contrib.gis.gdal import CoordTransform, SpatialReference class Serializer(JSONSerializer): """ Convert a...
def raises(err, lamda): try: lamda() return False except err: return True def expand_tuples(L): """ >>> expand_tuples([1, (2, 3)]) [(1, 2), (1, 3)] >>> expand_tuples([1, 2]) [(1, 2)] """ if not L: return [()] elif not isinstance(L[0], tuple): ...
from django.contrib.auth.decorators import login_required from django.conf.urls import patterns, include, url js_info_dict = { 'packages': ('tilejetserver.cache',), } urlpatterns = patterns('tilejetserver.cache.views', url(r'^info$', 'info', name='info'), url(r'^flush$', 'flush', name='flush'), url(r'^s...
"""Accuracy tests for ICRS transformations, primarily to/from AltAz. """ import pytest import numpy as np from astropy import units as u from astropy.tests.helper import assert_quantity_allclose as assert_allclose from astropy.time import Time from astropy.coordinates import ( EarthLocation, ICRS, CIRS, AltAz, Sky...
""" SeedEditor for organ segmentation Example: $ seed_editor_qp.py -f head.mat """ from optparse import OptionParser from PyQt5.QtWidgets import * from scipy.io import loadmat import numpy as np import sys from scipy.spatial import Delaunay import PyQt5 from PyQt5.QtCore import Qt, QSize QString = type("") from PyQt5.Q...
from modeltranslation.translator import translator, TranslationOptions from .models import Language from signbank.settings.base import LANGUAGES class LanguageTranslationOptions(TranslationOptions): fields = ('name',) required_languages = (LANGUAGES[0][0],) translator.register(Language, LanguageTranslationOptio...
"""Migration for deleting old crontab usage.""" from pathlib import Path def up(config): """ Deletes the old crontab file we used to use if it exists. :param config: Object holding configuration details about Submitty :type config: migrator.config.Config """ cron_file = Path("/var", "spool", "cr...
from unittest2 import TestCase from aux.logger import LogController class LoggingTest(TestCase): def xtest_start_logging(self): pass #setting up log controller #logcontroller = LogController(config) #test write formats # log.info("This is a info message.") # log.debug...
from urlparse import urljoin import requests from checks import AgentCheck class Marathon(AgentCheck): DEFAULT_TIMEOUT = 5 SERVICE_CHECK_NAME = 'marathon.can_connect' APP_METRICS = [ 'backoffFactor', 'backoffSeconds', 'cpus', 'disk', 'instances', 'mem', ...
""" Bench the scikit's ward implement compared to scipy's """ import time import numpy as np from scipy.cluster import hierarchy import pylab as pl from sklearn.cluster import Ward ward = Ward(n_clusters=15) n_samples = np.logspace(.5, 3, 9) n_features = np.logspace(1, 3.5, 7) N_samples, N_features = np.meshgrid(n_samp...
import unittest from django.db import connections from wp_frontman.models import Site, Blog from wp_frontman.tests.utils import MultiBlogMixin class DynamicPostsTestCase(MultiBlogMixin, unittest.TestCase): def setUp(self): super(DynamicPostsTestCase, self).setUp() self.cursor = connections['test'].c...
import numpy as np import Starfish from . import constants as C from .grid_tools import Interpolator import json import h5py import logging import matplotlib.pyplot as plt from itertools import zip_longest def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABC...
""" Query suggestion hierarchical encoder-decoder code. The code is inspired from nmt encdec code in groundhog but we do not rely on groundhog infrastructure. """ __docformat__ = 'restructedtext en' __authors__ = ("Alessandro Sordoni") __contact__ = "Alessandro Sordoni <sordonia@iro.umontreal>" import theano import the...
"""Tests of misc utility functions.""" import os import os.path as op import subprocess import numpy as np from numpy.testing import assert_array_equal as ae from pytest import raises, mark from six import string_types from .._misc import (_git_version, _load_json, _save_json, ...
from __future__ import absolute_import import datetime import base64 import pytest import numpy as np import pandas as pd import pytz import bokeh.util.serialization as bus def test_id(): assert len(bus.make_id()) == 36 assert isinstance(bus.make_id(), str) def test_id_with_simple_ids(): import os os.en...
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.organization import OrganizationReleasesBaseEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize from sentry.models import CommitFileChange, Release, ReleaseCommit ...
report_high = """<?xml version="1.0"?> <report type="security"> <generatedBy id="Wapiti 2.2.1"/> <bugTypeList> <bugType name="SQL Injection"> <bugList/> <description> <![CDATA[SQL injection is a technique that exploits a vulnerability occurring in the database of an application.]...
import numpy as np from scipy.sparse import csr_matrix import pytest from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal, assert_raises from sklearn.metrics.pairwise import kernel_metrics from sklearn.kernel_approximation import RBFSampler from sklearn.kern...
from django import template from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django_counter.models import ViewCounter def counter(object): ctype = ContentType.objects.get_for_model(object) return { 'ctype': ctype, 'object': object, ...
""" Internationalization support. """ from __future__ import unicode_literals from django.utils.encoding import force_text from django.utils.functional import lazy from django.utils import six __all__ = [ 'activate', 'deactivate', 'override', 'deactivate_all', 'get_language', 'get_language_from_request', '...
from __future__ import absolute_import from geocoder.base import Base from geocoder.keys import opencage_key from geocoder.opencage import OpenCage from geocoder.location import Location class OpenCageReverse(OpenCage, Base): """ OpenCage Geocoding Services =========================== OpenCage Geocoder ...
""" homeassistant.components.groups ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides functionality to group devices that can be turned on or off. """ import homeassistant as ha from homeassistant.helpers import generate_entity_id import homeassistant.util as util from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FRIE...
from flask.ext.script import Manager from watermark.models import db, Image from watermark.app import create_app app = create_app() manager = Manager(app) @manager.command def create_all(): db.create_all() dummy_data() @manager.command def drop_all(): db.drop_all() @manager.command def dummy_data(): tes...
__all__ = ['zhanqi_download'] from ..common import * import re def zhanqi_download(url, output_dir = '.', merge = True, info_only = False): html = get_content(url) rtmp_base_patt = r'VideoUrl":"([^"]+)"' rtmp_id_patt = r'VideoID":"([^"]+)"' title_patt = r'<p class="title-name" title="[^"]+">([^<]+)</p>'...
import unittest from lib import keystore from lib import mnemonic from lib import old_mnemonic class Test_NewMnemonic(unittest.TestCase): def test_to_seed(self): seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic='foobar', passphrase='none') self.assertEquals(seed.encode('hex'), ...
from django.shortcuts import redirect, get_object_or_404 from django.http import Http404 from django.contrib.auth.models import User, SiteProfileNotAvailable from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from django.contrib import messages from dja...
from django.db import models
import os import theano import theano.tensor as T import numpy as np import re import copy from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams import logging as loggers logging = loggers.getLogger(__name__) FLOATX = theano.config.floatX EPSILON = T.constant(1.0e-15, dtype=FLOATX) BIG_EPSILON = T.const...
from whirlwind.core.request import BaseRequest from whirlwind.db.mongo import Mongo from tornado.web import authenticated from whirlwind.view.decorators import route @route('/') class IndexHandler(BaseRequest): def get(self): #template context variables go in here template_values = {} self.r...
import sys sys.path.append("..") import baseStrategy class CBaseMultiple(baseStrategy.CBaseStrategy): #------------------------------ #继承重载函数 #------------------------------ #自定义初始化函数 def customInit(self): self.name = "baseMultiple" #行情数据触发函数 def onRtnMarketData(self, data): print self.name, "onRtnMarketData...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import subprocess def build_id(): """ Returns pwndbg commit id if git is available. """ try: git_path = os.path.join(os.path.dirname(os.p...
from __future__ import division import re import string import sys import tempfile import warnings import inspect import os import subprocess import locale import traceback from datetime import datetime from functools import wraps, partial from contextlib import contextmanager from distutils.version import LooseVersion...
from nanpy.arduinoboard import ArduinoObject from nanpy.arduinoboard import (arduinoobjectmethod, returns) class DallasTemperature(ArduinoObject): def __init__(self, pin, connection=None): ArduinoObject.__init__(self, connection=connection) self.pin = pin self.id = self.call('new', pin) ...
def shiftgrid(lon0,datain,lonsin,start=True,cyclic=360.0): import numpy as np """ Shift global lat/lon grid east or west. .. tabularcolumns:: |l|L| ============== ==================================================== Arguments Description ============== =================================================...
import sys import gdb import os import os.path pythondir = '/home/build/work/GCC-4-8-build/install-native/share/gcc-arm-none-eabi' libdir = '/home/build/work/GCC-4-8-build/install-native/arm-none-eabi/lib/armv7-ar/thumb/softfp' if gdb.current_objfile () is not None: # Update module path. We want to find the relati...
from util import * from util import raiseNotDefined import time, os import traceback try: import boinc _BOINC_ENABLED = True except: _BOINC_ENABLED = False class Agent: """ An agent must define a getAction method, but may also define the following methods which will be called if they exist: def registerIn...
import datetime import logging import os from urllib.parse import urljoin from utils import utils, inspector, admin archive = 1998 REPORTS_URL = "https://www.fdicig.gov/Search-Engine.asp" GENERIC_MISSING_REPORT_URL = 'https://www.fdicig.gov/notice.pdf' RECORD_TYPE_BLACKLIST = set([ "FDIC OIG Hotline", "GPRA page", ...
""" Serialization utilities for Gramps. """ import json import gramps.gen.lib as lib def __default(obj): obj_dict = {'_class': obj.__class__.__name__} if isinstance(obj, lib.GrampsType): obj_dict['string'] = getattr(obj, 'string') if isinstance(obj, lib.Date): if obj.is_empty() and not obj.t...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('terminal', '0020_auto_20191218_1721'), ] operations = [ migrations.AlterField( model_name='session', name='is_finished', field=models.BooleanField(db_index=T...
"""Unit tests for the search engine.""" __revision__ = \ "$Id$" from itertools import chain from invenio.testutils import InvenioTestCase, make_test_suite, run_test_suite from invenio.bibauthorid_cluster_set import ClusterSet class TestDummy(InvenioTestCase): def setUp(self): pass def test_one(self)...
'''OpenGL extension IBM.rasterpos_clip Automatically generated by the get_gl_extensions script, do not edit! ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions from OpenGL.GL import glget import ctypes EXTENSION_NAME = 'GL_IBM_rasterpos_clip' _DEPRECATED = False GL_RASTER_POSITIO...
try: from collections import OrderedDict except ImportError: from UserDict import DictMixin class OrderedDict(dict, DictMixin): def __init__(self, *args, **kwds): if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: ...
""" Copyright (C) 2009-2012 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation...
""" Copyright 2008-2015 Free Software Foundation, Inc. This file is part of GNU Radio SPDX-License-Identifier: GPL-2.0-or-later """ from .base import Element from .utils.descriptors import lazy_property class Connection(Element): is_connection = True def __init__(self, parent, source, sink): """ ...
from __future__ import with_statement import cherrypy import webbrowser import sqlite3 import datetime import socket import os, sys, subprocess, re import urllib from threading import Lock from sickbeard import providers, metadata from providers import ezrss, tvtorrents, btn, newznab, womble, thepiratebay, torrentleech...
""" Linear algebra """ from __future__ import unicode_literals from __future__ import absolute_import import six from six.moves import range from six.moves import zip import sympy from mpmath import mp from mathics.builtin.base import Builtin from mathics.core.convert import from_sympy from mathics.core.expression impo...
from ephem import Observer from unittest import TestCase class ObserverTests(TestCase): def test_lon_can_also_be_called_long(self): o = Observer() o.lon = 3.0 self.assertEqual(o.long, 3.0) o.long = 6.0 self.assertEqual(o.lon, 6.0) def test_pressure_at_sea_level(self): ...
from jx_elasticsearch.es52.expressions._utils import ES52, split_expression_by_path, split_expression_by_depth from jx_elasticsearch.es52.expressions.and_op import AndOp, es_and from jx_elasticsearch.es52.expressions.basic_eq_op import BasicEqOp from jx_elasticsearch.es52.expressions.basic_starts_with_op import BasicSt...
from __future__ import print_function, unicode_literals import os import os.path as path import subprocess import sys from time import time from mach.decorators import ( CommandArgument, CommandProvider, Command, ) from servo.command_base import CommandBase, cd def is_headless_build(): return int(os.get...
""" CMS Video """ import time import os import requests from bok_choy.promise import EmptyPromise, Promise from bok_choy.javascript import wait_for_js, js_defined from ....tests.helpers import YouTubeStubConfig from ...lms.video.video import VideoPage from ...common.utils import wait_for_notification from selenium.webd...
from .quantization_aware import *
{ 'name': 'CAMT Format Bank Statements Import', 'version': '0.1', 'license': 'AGPL-3', 'author': 'Therp BV', 'website': 'https://launchpad.net/banking-addons', 'category': 'Banking addons', 'depends': ['account_banking'], 'description': ''' Module to import SEPA CAMT.053 Format bank stat...
from __future__ import with_statement import contextlib import base64 import locale import logging import os import platform import security import sys import thread import threading import time import traceback from cStringIO import StringIO from openerp.tools.translate import _ import openerp.netsvc as netsvc import ...
from spack import * class RFracdiff(RPackage): """Maximum likelihood estimation of the parameters of a fractionally differenced ARIMA(p,d,q) model (Haslett and Raftery, Appl.Statistics, 1989).""" homepage = "https://cloud.r-project.org/package=fracdiff" url = "https://cloud.r-project.org/src/co...
from . import models
import os import time import unittest from test import support class StructSeqTest(unittest.TestCase): def test_tuple(self): t = time.gmtime() self.assertIsInstance(t, tuple) astuple = tuple(t) self.assertEqual(len(t), len(astuple)) self.assertEqual(t, astuple) # Chec...
""" High level operations on repostories. """ import sys import subuserlib.resolve from subuserlib.classes.repository import Repository def add(user,name,url): repository = subuserlib.resolve.lookupRepositoryByURIOrPath(user,url) if repository: if repository.isTemporary(): sys.exit("A temporary repository...
""" HTTP request related code. """ import datetime import json import posixpath import re import shlex import subprocess try: import google.auth from google.auth.transport.requests import Request as GoogleAuthRequest google_auth_installed = True except ImportError: google_auth_installed = False import r...
"""Data iterators for common data formats.""" from __future__ import absolute_import from collections import OrderedDict, namedtuple import sys import ctypes import logging import threading try: import h5py except ImportError: h5py = None import numpy as np from .base import _LIB from .base import c_str_array, ...
""" Handles all requests relating to the volume backups service. """ from eventlet import greenthread from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import strutils from cinder.backup import rpcapi as backup_rpcapi from cinder import context from cinder.d...
input = """ fatto. pos(0,1,b):- fatto. pos(0,2,b):- fatto. pos(0,3,x):- fatto. pos(0,4,x):- fatto. pos(0,5,x):- fatto. pos(0,6,x):- fatto. pos(0,7,y):- fatto. pos(0,8,y):- fatto. pos(0,9,y):- fatto. pos(0,10,y):- fatto. prec(0,1). prec(1,2). prec(2,3). prec(3,4). prec(4,5). prec(5,6). prec(6,7). prec(7,8). prec(8,9). p...
"""Test the DSMR config flow.""" import asyncio from itertools import chain, repeat import os from unittest.mock import DEFAULT, AsyncMock, MagicMock, patch, sentinel import serial import serial.tools.list_ports from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.dsmr import D...
import unittest from google.api_core import grpc_helpers import google.auth.credentials from google.protobuf import empty_pb2 import mock import google.cloud.logging from google.cloud.logging import _gapic from google.cloud.logging_v2.gapic import config_service_v2_client from google.cloud.logging_v2.gapic import loggi...
import copy import random import time from oslo.config import cfg import six from cinder.openstack.common._i18n import _, _LE, _LI from cinder.openstack.common import log as logging periodic_opts = [ cfg.BoolOpt('run_external_periodic_tasks', default=True, help='Some periodic tasks c...
import json import re from typing import Callable, Iterator, List, Optional, Union import scrapy from scrapy.http import Request, Response from scrapy.linkextractors import IGNORED_EXTENSIONS from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor from scrapy.spidermiddlewares.httperror import HttpError from scrap...
import time logfile = "message_log" print "loading responders" # :-) def Always(*args, **argd): return True def Never(*args, **argd): return False def SendNotHere(self, who, message): sendmessage = False seen = self.stash.get("seen", {}) if seen.get(who): (first, last, count) = seen[who] ...
import io import os import posixpath import re from seafileapi.utils import querystr, utf8lize ZERO_OBJ_ID = '0000000000000000000000000000000000000000' class _SeafDirentBase(object): """Base class for :class:`SeafFile` and :class:`SeafDir`. It provides implementation of their common operations. """ isdi...
import tempfile import unittest import os import datafilereader from robotide.controller.filecontrollers import TestDataDirectoryController, ExcludedDirectoryController, \ DirtyRobotDataException class TestExcludesLogic(unittest.TestCase): def setUp(self): self.project = datafilereader.construct_project...
import sys import os import subprocess import glob import re def symcheck(objfile): symfile = objfile.replace('.obj', '.sym') cmd = ['dumpbin.exe', '/SYMBOLS', objfile, '/OUT:' + symfile] # /dev/null standin junk = open('junk', 'w') p = subprocess.Popen(cmd, stdout=junk) n = p.wait() if n !=...
import logging import time from helpers import unittest import luigi import luigi.hadoop import luigi.rpc import luigi.scheduler import luigi.worker class DummyTask(luigi.Task): n = luigi.Parameter() def __init__(self, *args, **kwargs): super(DummyTask, self).__init__(*args, **kwargs) self.has_r...
import math import sys from PIL import Image def distance(p1, p2): dx = p2[0] - p1[0] dy = p2[1] - p1[1] return math.sqrt(dx * dx + dy * dy) def scale_rotate__translate(image, angle, center=None, new_center=None, scale=None, resample=Image.BICUBIC): if (scale is None) and (center is None): retur...
from __future__ import print_function import sys import re from optparse import OptionParser from rdkit import Chem from rdkit import DataStructs parser = OptionParser( description="Program to Tversky search results as part of Fraggle", epilog="Format of input file: whole mol smiles,ID,fraggle split smiles\t\t" "...
import datetime import os import time import unittest import requests from nose.plugins.attrib import attr from nose.tools import assert_raises from nose.tools import assert_equal as eq from nose.tools import assert_true as ok from datadog import initialize from datadog import api as dog from datadog.api.exceptions imp...
import logging import time import traceback from app_yaml_helper import AppYamlHelper from appengine_wrappers import ( GetAppVersion, DeadlineExceededError, IsDevServer, logservice) from branch_utility import BranchUtility from caching_file_system import CachingFileSystem from compiled_file_system import CompiledFi...
""" Showutil Effects module: contains code for useful showcode effects. """ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * SX_BOUNCE = 0 SY_BOUNCE = 1 SZ_BOUNCE = 2 TX_BOUNCE = 3 TY_BOUNCE = 4 TZ_BOUNCE = 5 H_BOUNCE = 6 P_BOUNCE = 7 R_BOUNCE = 8 def createScaleXBounce(nodeObj, numBounces...
"""Utilities for meta-estimators""" from typing import List, Any from abc import ABCMeta, abstractmethod from operator import attrgetter from functools import update_wrapper import numpy as np from ..utils import _safe_indexing from ..base import BaseEstimator __all__ = ['if_delegate_has_method'] class _BaseComposition...
""" Testing decorators module """ import numpy as np from nose.tools import (assert_true, assert_raises, assert_equal) from skimage._shared.testing import doctest_skip_parser def test_skipper(): def f(): pass class c(): def __init__(self): self.me = "I think, therefore..." docstr...
from __future__ import absolute_import __all__ = ('ApiClient',) from django.core.urlresolvers import resolve from rest_framework.test import APIRequestFactory, force_authenticate from sentry.utils import json class ApiError(Exception): def __init__(self, status_code, body): self.status_code = status_code ...
try: import unittest2 as unittest except ImportError: import unittest import dns.set S = dns.set.Set class SimpleSetTestCase(unittest.TestCase): def testLen1(self): s1 = S() self.failUnless(len(s1) == 0) def testLen2(self): s1 = S([1, 2, 3]) self.failUnless(len(s1) == 3) ...
from crowdsourcing import models from crowdsourcing.serializers.user import UserProfileSerializer from rest_framework import serializers class WorkerRequesterRatingSerializer(serializers.ModelSerializer): origin = UserProfileSerializer(read_only=True) class Meta: model = models.WorkerRequesterRating ...
import json import unittest2 from datafeeds.parsers.fms_api.fms_api_team_details_parser import FMSAPITeamDetailsParser from google.appengine.ext import ndb from google.appengine.ext import testbed from models.district import District from models.sitevar import Sitevar class TestFMSAPITeamParser(unittest2.TestCase): ...
from __future__ import print_function import numpy as np class RBM: def __init__(self, num_visible, num_hidden, learning_rate = 0.1): self.num_hidden = num_hidden self.num_visible = num_visible self.learning_rate = learning_rate # Initialize a weight matrix, of dimensions (num_visible x num_hidden), u...
import datetime import dateutil.tz from twisted.internet import defer from twisted.internet import error from twisted.internet import reactor from twisted.python import failure from twisted.trial import unittest from buildbot.changes.p4poller import P4PollerError from buildbot.changes.p4poller import P4Source from buil...
from chimera.core.chimeraobject import ChimeraObject from chimera.controllers.imageserver.imageserverhttp import ImageServerHTTP from chimera.util.image import Image import Pyro.util import os class ImageServer(ChimeraObject): __config__ = { # root directory where images are stored 'images_dir': '~/images'...
import re from sos_tests import StageOneOutputTest class ReportHelpTest(StageOneOutputTest): """Ensure that --help gives the expected output in the expected format :avocado: tags=stageone """ sos_cmd = 'report --help' def test_all_help_sections_present(self): self.assertOutputContains('Globa...
error = "Registry Setup Error" import sys # at least we can count on this! def FileExists(fname): """Check if a file exists. Returns true or false. """ import os try: os.stat(fname) return 1 except os.error, details: return 0 def IsPackageDir(path, packageName, knownFileName): """Given a path, a ni package...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: onepassword_facts author: - Ryan Conway (@rylon) version_adde...
DOCUMENTATION = """ --- module: nxos_command version_added: "2.1" author: "Peter Sprygada (@privateip)" short_description: Run arbitrary command on Cisco NXOS devices description: - Sends an arbitrary command to an NXOS node and returns the results read from the device. This module includes an argument that ...
import pytest from pages.discopane import DiscoveryPane @pytest.fixture(scope='session') def base_url(base_url): ''' This is hardcoded for now, once we go through about:addons we'll be able to use the template expansion ''' base_url += '/en-US/firefox/discovery/pane/48.0/Darwin/normal' return ba...
"""mist.io.views Here we define the HTTP API of the app. The view functions here are responsible for taking parameters from the web requests, passing them on to functions defined in methods and properly formatting the output. This is the only source file where we import things from pyramid. View functions should only c...
"""Several classes and functions that help with integrating and using Babel in applications. .. note: the code in this module is not used by Babel itself """ from datetime import date, datetime, timedelta import gettext import locale from babel.compat import text_type, u from babel.core import Locale from babel.dates i...
from __future__ import unicode_literals from django.db import migrations from temba.sql import InstallSQL class Migration(migrations.Migration): dependencies = [ ('orgs', '0029_reset_1'), ] operations = [ InstallSQL('0030_orgs') ]
from spack import * class PyPathlib(PythonPackage): """Object-oriented filesystem paths. Attention: this backport module isn't maintained anymore. If you want to report issues or contribute patches, please consider the pathlib2 project instead.""" homepage = "https://pathlib.readthedocs.org/" py...