content
stringlengths
4
20k
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os sys.path.append(sys.path[0]+os.sep+'pygccxml-1.0.0') import pygccxml, sys, cStringIO # the output file outputFile = cStringIO.StringIO() # init the pygccxml stuff pygccxml.declarations.scopedef_t.RECURSIVE_DEFAULT = False pygccxml.declarations.scopedef_t.A...
class Album(): def __init__(self, titulo, cancion, genero, artista, año): self.titulo = titulo self.cancion= cancion self.genero = genero self.artista = artista self.año = año def get_titulo(self): return "Informacion: \nTitulo: {} \ncancion: {} \ngenero: {} \n...
""" This module implements the upload and remove endpoints of the profile image api. """ from contextlib import closing import datetime import itertools import logging from django.utils.translation import ugettext as _ from django.utils.timezone import utc from rest_framework import permissions, status from rest_frame...
__version__=''' $Id$ ''' __doc__='''Data structure to hold a collection of attributes, used by styles.''' class ABag: """ 'Attribute Bag' - a trivial BAG class for holding attributes. This predates modern Python. Doing this again, we'd use a subclass of dict. You may initialize with keyword argum...
""" parser package (imdb package). This package provides various parsers to access IMDb data (e.g.: a parser for the web/http interface, a parser for the SQL database interface, etc.). So far, the http/httpThin, mobile and sql parsers are implemented. Copyright 2004-2009 Davide Alberani <<EMAIL>> This program is fre...
"""Support for DLNA DMR (Device Media Renderer).""" import asyncio from datetime import timedelta import functools import logging from typing import Optional import aiohttp from async_upnp_client import UpnpFactory from async_upnp_client.aiohttp import AiohttpNotifyServer, AiohttpSessionRequester from async_upnp_clien...
import gdb from linux import utils task_type = utils.CachedType("struct task_struct") def task_lists(): task_ptr_type = task_type.get_type().pointer() init_task = gdb.parse_and_eval("init_task").address t = g = init_task while True: while True: yield t t = utils.co...
"""check assignment to function call where the function doesn't return 'E1111': ('Assigning to function call which doesn\'t return', 'Used when an assignment is done on a function call but the \ infered function doesn\'t return anything.'), 'W1111': ('Assigning to function call whic...
""" Make sure safeseh setting is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['ninja']) CHDIR = 'linker-flags' test.run_gyp('safeseh.gyp', chdir=CHDIR) test.build('safeseh.gyp', test.ALL, chdir=CHDIR) def HasSafeExceptionHandlers(exe): ...
import sys from optparse import OptionParser import time try: import tir4 except: print("tir4.py missing") sys.exit(1) class GeneralException(Exception): def __init__(self, msg): self.msg = msg def handle_exception(errorinfo): if errorinfo.args[0] == tir4.TIR4EXCEPTION_ENUM.USB_LIST_FAIL...
import gettext t = gettext.translation('rhn-client-tools', fallback=True) _ = t.ugettext COPYRIGHT_TEXT = _(u"Copyright © 2006--2014 Red Hat, Inc. All rights reserved.") # Satellite URL Window SATELLITE_URL_WINDOW = _("Enter your Red Hat Satellite URL.") SATELLITE_URL_TEXT = _("Please enter the location of...
#coding=utf-8 ''' Created on 2014年6月18日 K-means 算法,将数据聚类到K个中心点 距离计算:欧式距离 中心店计算:均值法 @author: sjm ''' import numpy as np import random def Euclid_dist(x,y): if len(y.shape)==1: return np.sqrt(np.sum(np.sum((x-y)**2))) elif len(y.shape)==2: return np.sqrt(np.sum((x-y)**2,axis=1)) else: ...
import functools, hashlib import numpy as np from scipy.stats import norm as normal_dbn import regreg.api as rr from selection.algorithms.debiased_lasso import pseudoinverse_debiasing_matrix # load in the X matrix import rpy2.robjects as rpy from rpy2.robjects import numpy2ri rpy.r('library(hdi); data(riboflavin);...
#!/usr/bin/python import curses import math import os import sys import fcntl import struct import termios import array import logging import time logging.basicConfig(filename='example.log',level=logging.DEBUG) __doc__="""\ The program presents a series of menus that we're going to use for testing. 1. Enter new pers...
from spack import * class PyMaestrowf(PythonPackage): """A general purpose workflow conductor for running multi-step simulation studies.""" homepage = "https://github.com/LLNL/maestrowf/" url = "https://github.com/LLNL/maestrowf/archive/v1.0.1.tar.gz" version('1.0.1', '6838fc8bdc7ca0c1ad...
""" Lexer interface and implementation. Used for syntax highlighting. """ from __future__ import unicode_literals from abc import ABCMeta, abstractmethod from six import with_metaclass from six.moves import range from prompt_toolkit.token import Token from prompt_toolkit.filters import to_cli_filter from .utils import...
"""Fixer that changes xrange(...) into range(...).""" # Local imports from .. import fixer_base from ..fixer_util import Name, Call, consuming_calls from .. import patcomp class FixXrange(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< (name='range'|name='xrange'...
from struct import pack, unpack from TProtocol import * __all__ = ['TCompactProtocol', 'TCompactProtocolFactory'] CLEAR = 0 FIELD_WRITE = 1 VALUE_WRITE = 2 CONTAINER_WRITE = 3 BOOL_WRITE = 4 FIELD_READ = 5 CONTAINER_READ = 6 VALUE_READ = 7 BOOL_READ = 8 def make_helper(v_from, container): def helper(func): ...
from waldur_mastermind.marketplace.tests import factories as marketplace_factories from waldur_mastermind.marketplace_openstack.tests.utils import BaseOpenStackTest from waldur_openstack.openstack_tenant.tests import ( fixtures as openstack_tenant_fixtures, ) class VolumeMetadataTest(BaseOpenStackTest): def s...
import xml.sax.saxutils from acl import Grant class BucketLogging(object): def __init__(self, target=None, prefix=None, grants=None): self.target = target self.prefix = prefix if grants is None: self.grants = [] else: self.grants = grants def __repr__(s...
import ray import os class HorovodWorker: def ip_addr(self): import ray return ray._private.services.get_node_ip_address() def set_gloo_iface(self): ip_addr = self.ip_addr() import psutil import socket iface_name = None for intf, intf_addresses in psut...
from socket import * import subprocess localAddr = ('localhost', 8889) sock = socket(AF_INET, SOCK_STREAM) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.bind(localAddr) sock.listen(5) data = "" while 1: (client, address) = sock.accept() print 'CONNECTED TO : ', address while 1: data = client.r...
import logging from django.utils.translation import ugettext_lazy as _ # noqa from horizon import tables from openstack_dashboard.dashboards.project.networks.ports \ import tables as networks_tables from openstack_dashboard.dashboards.project.routers.ports \ import tables as routers_tables LOG = logging.ge...
#!/usr/bin/env python3 # coding: utf-8 from sys import argv import dbus def kb_light_set(delta): bus = dbus.SystemBus() kbd_backlight_proxy = bus.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower/KbdBacklight') kbd_backlight = dbus.Interface(kbd_backlight_proxy, 'org.freedesktop.UPower.KbdBac...
import unittest import struct import sys import os import pywintypes import win32event, win32api import os from pywin32_testutil import str2bytes, TestSkipped import win32com.directsound.directsound as ds # next two lines are for for debugging: # import win32com # import directsound as ds WAV_FORMAT_PCM = 1 WAV_HEADER...
""" Check that all of the certs on all service endpoints validate. """ import unittest from tests.integration import ServiceCertVerificationTest import boto.swf class SWFCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest): swf = True regions = boto.swf.regions() def sample_service_call...
import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import plotly.offline as py import plotly.graph_objs as go from plotly.graph_objs import * import plotly.tools as tls import seaborn as sns import plotly plotly.offline.init_notebook_mode() def plot_pollutants(df, year, state)...
import abc import os.path import time import sys import logging sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) from github_analysis_tool import OUTPUT_DIR, secret_config from github_analysis_tool.services.database_service import DatabaseService from github_analysis_tool.s...
"""Tests for modules/search/.""" __author__ = 'Ellis Michael (<EMAIL>)' import datetime import logging import re import actions from controllers import sites from models import courses from models import custom_modules from modules.announcements import announcements from modules.search import search from tests.unit ...
import logging, sys from logging.handlers import RotatingFileHandler def filter_status(record): """" Only displays log messages about status info or ERROR level """ if ("Status:" in str(record.msg)) or (record.levelname == 'ERROR'): return 1 else: return 0 def log(logFile, l...
#!/usr/bin/env python import os import shutil import glob import time import sys import subprocess import string from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PKG_NAME = os.path.basename(SCRIPT_DIR) PARAMETERS = None #XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=...
# Used by genpytokenize.py to generate the parser in pytokenize.py from ayrton.parser.pyparser.automata import DFA, DEFAULT class EMPTY: pass def newArcPair (states, transitionLabel): s1Index = len(states) s2Index = s1Index + 1 states.append([(transitionLabel, s2Index)]) states.append([]) return s...
from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. E Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = ...
from codecs import open from os import path from setuptools import find_packages, setup from tiko import __version__ base = path.abspath(path.dirname(__file__)) def install_requires(): with open(path.join(base, 'requirements.txt'), encoding='utf-8') as file: return file.read().splitlines() def dev_re...
import os import shutil import tempfile import unittest import mock from pulp.plugins.config import PluginCallConfiguration from pulp_ostree.common import constants from pulp_ostree.plugins.distributors import configuration class TestConfigurationGetters(unittest.TestCase): def setUp(self): self.workin...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json from ansible.compat.tests.mock import patch from ansible.modules.network.nxos import nxos_vrf_af from .nxos_module import TestNxosModule, load_fixture, set_module_args class TestNxosVrfafModule(TestNxosModule): ...
""" Convenience routines for creating non-trivial Field subclasses, as well as backwards compatibility utilities. Add SubfieldBase as the metaclass for your Field subclass, implement to_python() and the other necessary methods and everything will work seamlessly. """ import warnings from django.utils.deprecation imp...
from __future__ import unicode_literals import os import re from .common import InfoExtractor from ..compat import ( compat_urllib_parse_urlparse, compat_urllib_request, compat_urllib_parse, ) class MofosexIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?(?P<url>mofosex\.com/videos/(?P<id>[0-9]+...
# Written to test interrupted system calls interfering with our many buffered # IO implementations. http://bugs.python.org/issue12268 # # This tests the '_io' module. Similar tests for Python 2.x's older # default file I/O implementation exist within test_file2k.py. # # It was suggested that this code could be merged...
from django.contrib import admin class AdminBuilder: def __init__(self, admin_model_class): self.admin_model = admin_model_class() self.model = admin_model_class.Meta.model def construct_list_display(self, admin_class): admin_class.list_display = [] for field in self...
import TestServer import server.app.packages import SimpleXMLRPCServer class TestRhnpush(TestServer.TestServer): def __init__(self): TestServer.TestServer.__init__(self) self._init_app() def _init_app(self): self.app = server.app.packages.Packages() def getApp(self): ret...
"""Detect changes in Ansible code.""" from __future__ import absolute_import, print_function import re import os from lib.util import ( ApplicationError, SubprocessError, MissingEnvironmentVariable, CommonConfig, display, ) from lib.http import ( HttpClient, urlencode, ) from lib.git im...
''' NEST Topology Module Example Create two 30x30 layers of iaf_psc_alpha neurons with edge_wrap, connect with circular mask, flat probability, visualize. BCCN Tutorial @ CNS*09 Hans Ekkehard Plesser, UMB ''' import pylab import nest import nest.topology as topo pylab.ion() nest.ResetKernel() # create two test la...
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin class Snmp(Plugin): """Simple network management protocol """ plugin_name = "snmp" profiles = ('system', 'sysmgmt') files = ('/etc/snmp/snmpd.conf',) def setup(self): self.add_copy_spec("/etc/snmp") class RedH...
import sys from pyasn1 import error from pyasn1.type import tag from pyasn1.type import univ __all__ = ['NumericString', 'PrintableString', 'TeletexString', 'T61String', 'VideotexString', 'IA5String', 'GraphicString', 'VisibleString', 'ISO646String', 'GeneralString', 'UniversalString', 'BMPStrin...
from selenium.webdriver.remote.remote_connection import RemoteConnection class FirefoxRemoteConnection(RemoteConnection): def __init__(self, remote_server_addr, keep_alive=True): RemoteConnection.__init__(self, remote_server_addr, keep_alive) self._commands["SET_CONTEXT"] = ('POST', ...
__author__ = 'api.jscudder (Jeff Scudder)' import unittest import atom.http_interface import StringIO class HttpResponseTest(unittest.TestCase): def testConstructorWithStrings(self): resp = atom.http_interface.HttpResponse(body='Hi there!', status=200, reason='OK', headers={'Content-Length':'9'}) ...
""" Sardana extension for taurus Qt """ __docformat__ = 'restructuredtext' def registerExtensions(): from . import pool from . import macroserver pool.registerExtensions() macroserver.registerExtensions()
#!/usr/bin/python """ Simulates svnrdump by replaying an existing dump from a file, taking care of the specified revision range. To simulate incremental imports the environment variable SVNRMAX can be set to the highest revision that should be available. """ import sys import os if sys.hexversion < 0x02040000: # T...
# -*- coding: utf-8 -*- """ This module """ import os import urllib2 import json import requests from psiturk.version import version_number import git import subprocess import signal import struct from sys import platform as _platform from psiturk.psiturk_config import PsiturkConfig import psutil class PsiturkOrgSer...
import Test import Pmw Test.initialise() c = Pmw.ScrolledCanvas def _createOvals(): w = Test.currentWidget() w.create_oval(50, 50, 150, 100, fill = 'red') w.create_oval(100, 50, 150, 150, fill = 'blue') w.create_oval(50, 100, 200, 350, fill = 'yellow') def _createWindow(): w = Test...
""" Outline Tab Serializers. """ from django.utils.translation import ngettext from rest_framework import serializers from lms.djangoapps.course_home_api.dates.v1.serializers import DateSummarySerializer from lms.djangoapps.course_home_api.progress.v1.serializers import CertificateDataSerializer from lms.djangoapps.c...
# coding=utf-8 # --------------------------------------------------------------- # Desenvolvedor: Arannã Sousa Santos # Mês: 12 # Ano: 2015 # Projeto: pagseguro_xml # e-mail: <EMAIL> # --------------------------------------------------------------- import unittest import...
"""Profiler tools for CherryPy. CherryPy users ============== You can profile any of your pages as follows: from cherrypy.lib import profiler class Root: p = profile.Profiler("/path/to/profile/dir") def index(self): self.p.run(self._index) index.exposed = Tru...
from neutron.api import extensions from neutron.api.v2 import attributes as attr from neutron.common import exceptions # ExtraDHcpOpts Exceptions class ExtraDhcpOptNotFound(exceptions.NotFound): message = _("ExtraDhcpOpt %(id)s could not be found") class ExtraDhcpOptBadData(exceptions.InvalidInput): message...
import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." Package...
from unittest import TestCase from os import remove, path import create_files from nose.tools import assert_equal from lisa_parser.test_run import TestRun class TestTestRun(TestCase): def setUp(self): self.test_run = TestRun(skip_vm_check=True, checkpoint_name=False) self.xml_file = path.join(path...
"""SCons.Tool.Packaging SCons Packaging Tool. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} import re from ansible.module_utils.network.nxos.nxos import get_config, load_config, run_commands from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args...
# Standard imports import re # Qt imports from PySide2.QtGui import QColor, QFont, QBrush, QPainter, QPen, QFontMetrics, QPalette from PySide2.QtCore import Qt, QModelIndex, QRect, QUrl from PySide2.QtWidgets import QStyleOptionViewItem, QStyle # Custom imports from cutevariant.gui.formatter import Formatter from cut...
try: from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False class VMwareDvsPortgroup(object): def __init__(self, module): self.module = module self.dvs_portgroup = None self.switch_name = self.module.params['switch_name'] self.portgrou...
"""resource_attr_id Revision ID: 08f0ebe40290 Revises: a7896842f484 Create Date: 2018-04-16 14:49:24.202974 """ from alembic import op import sqlalchemy as sa import logging log = logging.getLogger(__name__) # revision identifiers, used by Alembic. revision = '08f0ebe40290' down_revision = 'a7896842f484' branch_lab...
""" ========================================= SVM: Maximum margin separating hyperplane ========================================= Plot the maximum margin separating hyperplane within a two-class separable dataset using a Support Vector Machines classifier with linear kernel. """ print(__doc__) import numpy as np impo...
from __future__ import unicode_literals import frappe from frappe import _ def install(country=None): records = [ # address template {'doctype':"Address Template", "country": country}, # item group {'doctype': 'Item Group', 'item_group_name': _('All Item Groups'), 'is_group': 'Yes', 'parent_item_group'...
from datetime import datetime from corehq.apps.sms.api import send_sms_to_verified_number from custom.ilsgateway.tanzania.handlers import get_location from custom.ilsgateway.tanzania.handlers.keyword import KeywordHandler from custom.ilsgateway.models import SupplyPointStatus, SupplyPointStatusTypes, SupplyPointStatusV...
""" Tests for the CyberSource processor handler """ from collections import OrderedDict from django.test import TestCase from django.test.utils import override_settings from django.conf import settings from student.tests.factories import UserFactory from shoppingcart.models import Order, OrderItem from shoppingcart.pro...
""" Helper module for Python version 2.7 - Ordered dictionaries - Encoding/decoding urls - Unicode - Exception handling (except Exception as e) """ import base64 from urllib import unquote, quote from collections import OrderedDict def modulename(): return "Helper module for Python version 2.7" def url_decode(uri):...
import os import copy import errno import sys import traceback # Django Split Settings from split_settings.tools import optional, include # Load default settings. from defaults import * # NOQA DEBUG = False TEMPLATE_DEBUG = DEBUG SQL_DEBUG = DEBUG # Clear database settings to force production environment to define...
import tweepy import time import picamera from datetime import datetime # Consumer keys and access tokens, used for OAuth consumer_key = '<your value>' consumer_secret = '<your value>' access_token = '<your value>' access_token_secret = '<your value>' # OAuth process, using the keys and tokens auth = tweepy.OAuthHand...
""" Test xblock/validation.py """ import unittest from xblock.test.tools import assert_raises from xmodule.validation import StudioValidationMessage, StudioValidation from xblock.validation import Validation, ValidationMessage class StudioValidationMessageTest(unittest.TestCase): """ Tests for `ValidationMe...
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import os import sys import email import logging from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.uploadedfile import TemporaryUploadedFile, InMemoryUp...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import re from ansible.module_utils.network.ironware.ironware import run_commands from ans...
appstyle = """ * { font: 16px "Segoe UI" ; } QToolButton { padding: 4px; color: #4f4f4f; } QToolButton:hover { padding: 4px; background-color: rgb(211, 228, 255); } QStatusBar { background: white; border: none; } QStatusBar::item { border: none; } QCheckBox { color: #4...
from ansible import utils, errors import socket HAVE_DNS=False try: import dns.resolver import dns.reversename from dns.rdatatype import * from dns.exception import DNSException HAVE_DNS=True except ImportError: pass def make_rdata_dict(rdata): ''' While the 'dig' lookup plugin supports any...
import xml.etree.ElementTree as ET import six xsi = 'http://www.w3.org/2001/XMLSchema-instance' xs = 'http://www.w3.org/2001/XMLSchema' def camel_case(word): return ''.join(x.capitalize() or '_' for x in word.split('_')) def generate_entity(data, parent): if isinstance(data, dict): for key, data in...
"""Classes used in pickling tests, need to be at the module level for unpickling. """ from . import fixtures class User(fixtures.ComparableEntity): pass class Order(fixtures.ComparableEntity): pass class Dingaling(fixtures.ComparableEntity): pass class EmailUser(User): pass class Address(fixt...
"""Unit tests for trychange.py.""" import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from testing_support.super_mox import SuperMoxTestBase import subprocess2 import trychange class TryChangeTestsBase(SuperMoxTestBase): """Setups and tear downs ...
#!/usr/bin/env python notes = "CDEFGAB" alterations = [-1, 0, 1] def print_note (octave, note, alteration): print " <note>\n <pitch>\n <step>%s</step>" % notes[note] if alteration <> 0: print " <alter>%s</alter>" % alteration print " <octave>%s</octave>\n ...
""" PHP date() style date formatting See http://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print(df.format('jS F Y H:i')) 7th October 2003 11:39 >>> """ from __future__ import unicode_literals import calendar import datetime import re impo...
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import os import warnings from pip.basecommand import RequirementCommand from pip.exceptions import CommandError, PreviousBuildDirError from pip.req import RequirementSet from pip.utils import import_or_raise from pip.utils.build import Bui...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ExtractorError class TestURLIE(InfoExtractor): """ Allows addressing of the test cases as test:yout.*be_1 """ IE_DESC = False # Do not list _VALID_URL = r'test(?:url)?:(?P<id>(?P<extractor>.+?)(?:_(...
#!/usr/bin/env python3 from sys import exit from test.http_test import HTTPTest from misc.wget_file import WgetFile """ This test ensures that Wget correctly handles responses to HEAD requests and does not actually download any data """ TEST_NAME = "HEAD Requests" ############# File Definitions ###############...
""" Views for managing Nova floating ips. """ import logging from django import template from django.contrib import messages from django.contrib.auth.decorators import login_required from django import shortcuts from django_openstack import api from django_openstack import forms from novaclient import exceptions as n...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging import os from pants.base.build_environment import get_buildroot from pants.build_graph.address import Address from pants.build_graph.address_lookup_er...
__author__ = '<EMAIL> (Jeff Scudder)' import unittest import atom.auth import atom.http_core class BasicAuthTest(unittest.TestCase): def test_modify_request(self): http_request = atom.http_core.HttpRequest() credentials = atom.auth.BasicAuth('Aladdin', 'open sesame') self.assert_(credentials.basic_c...
import os, sys curr_path = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(curr_path, "../../python")) sys.path.insert(0, os.path.join(curr_path, "../../example/image-classification/symbols")) import mxnet as mx import logging import argparse import time import numpy as np from importlib impo...
import logging import sys from django.db import connections from ...boot import PROJECT_DIR from ...db.base import DatabaseWrapper from django.core.management.base import BaseCommand from django.core.exceptions import ImproperlyConfigured def start_dev_appserver(argv): """Starts the App Engine dev_appserver prog...
import copy from django import forms from django.contrib.postgres.validators import ( ArrayMaxLengthValidator, ArrayMinLengthValidator, ) from django.core.exceptions import ValidationError from django.utils import six from django.utils.safestring import mark_safe from django.utils.translation import string_concat,...
""" This module defines the parameter reading function. Used to parse a text file into a dictionary to be passed to datatool.prepare_data() It also defines the default parameters for prepare_data() Credit: Mark Krumholz Notes ----- Probably should transition to YAML format, and utilise pre-existing libraries for par...
"""Exports a toy linear regression inference graph. Exports a TensorFlow graph to /tmp/half_plus_two/ based on the Exporter format. This graph calculates, y = a*x + b where a and b are variables with a=0.5 and b=2. Output from this program is typically used to exercise Session loading and execution code. """ from...
# -*- coding: utf-8 -*- from openerp.tests import common class TestFloatExport(common.TransactionCase): def setUp(self): super(TestFloatExport, self).setUp() self.Model = self.registry('decimal.precision.test') def get_converter(self, name): converter = self.registry('ir.qweb.field.flo...
"""LU decomposition functions.""" from warnings import warn from numpy import asarray, asarray_chkfinite # Local imports from .misc import _datacopied, LinAlgWarning from .lapack import get_lapack_funcs from .flinalg import get_flinalg_funcs __all__ = ['lu', 'lu_solve', 'lu_factor'] def lu_factor(a, overwrite_a=F...
from random import random from bokeh.models import CustomJS, ColumnDataSource from bokeh.plotting import hplot, figure, output_file, show output_file("callback.html") x = [random() for x in range(500)] y = [random() for y in range(500)] s1 = ColumnDataSource(data=dict(x=x, y=y)) p1 = figure(plot_width=400, plot_heig...
""" Threaded select reactor The threadedselectreactor is a specialized reactor for integrating with arbitrary foreign event loop, such as those you find in GUI toolkits. There are three things you'll need to do to use this reactor. Install the reactor at the beginning of your program, before importing the rest of Tw...
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, parse_iso8601, xpath_text, ) class SrfIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.srf\.ch/play(?:er)?/tv/[^/]+/video/(?P<display_id>[^?]+)\?id=|tp\.srgssr\.c...
"""An estimator is a rule for calculating an estimate of a given quantity. # Estimators * **Estimators** are used to train and evaluate TensorFlow models. They support regression and classification problems. * **Classifiers** are functions that have discrete outcomes. * **Regressors** are functions that predict conti...
"""WebSearch Admin Regression Test Suite.""" __revision__ = "$Id$" from invenio.base.globals import cfg from invenio.testsuite import make_test_suite, run_test_suite, \ test_web_page_content, merge_error_messages, \ InvenioTestCase class WebSearchAdminWebP...
import webob from cinder.api import common from cinder.api.openstack import wsgi from cinder import exception from cinder import volume from webob import exc class Controller(wsgi.Controller): """The snapshot metadata API controller for the OpenStack API.""" def __init__(self): self.volume_api = vol...
from __future__ import unicode_literals from django.db import utils from django.db.backends.base.features import BaseDatabaseFeatures from django.utils import six from django.utils.functional import cached_property from .base import Database try: import pytz except ImportError: pytz = None class DatabaseFe...
"""Weak reference support for Python. This module is an implementation of PEP 205: http://python.sourceforge.net/peps/pep-0205.html """ # Naming convention: Variables named "wr" are weak reference objects; # they are called this instead of "ref" to avoid name collisions with # the module-global ref() function import...