content string |
|---|
"""Basic password hashing."""
def hash_password(plaintext_password=''):
"""Create a password hash from a given string.
This method is based on the algorithm provided by
Daniel Rentz of OpenOffice and the PEAR package
Spreadsheet_Excel_Writer by Xavier Noguer <<EMAIL>>.
"""
password = 0x0000
... |
"""
A release-automation toolkit.
Don't use this outside of Twisted.
Maintainer: Christopher Armstrong
"""
import os
# errors
class DirectoryExists(OSError):
"""
Some directory exists when it shouldn't.
"""
pass
class DirectoryDoesntExist(OSError):
"""
Some directory doesn't exist when ... |
"Misc. utility functions/classes for admin documentation generator."
import re
from email.parser import HeaderParser
from email.errors import HeaderParseError
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.utils.encoding import force_bytes
try:
import docuti... |
"""
lockfile.py - Platform-independent advisory file locks.
Requires Python 2.5 unless you apply 2.4.diff
Locking is done on a per-thread basis instead of a per-process basis.
Usage:
>>> lock = FileLock('somefile')
>>> try:
... lock.acquire()
... except AlreadyLocked:
... print 'somefile', 'is locked already... |
import time
from beebotte import *
import ephem
import datetime
import urllib2
from math import degrees
### URL where we will fetch TLE data
url = "http://www.celestrak.com/NORAD/elements/stations.txt"
### Replace CHENNL_TOKEN with that of your channel's (this code assumes the channel name is "ISS")
CHANNEL_TOKEN = N... |
#!/usr/bin/python
""" PN CLI vlan-create/vlan-delete """
#
# This file is part of Ansible
#
# Ansible 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... |
"""`SequentialModule` is a container module that chains a number of modules together."""
import logging
import copy
from ..initializer import Uniform
from .base_module import BaseModule
class SequentialModule(BaseModule):
"""A SequentialModule is a container module that can chain multiple modules together.
... |
import mock
from rally.plugins.openstack.scenarios.ceilometer import stats
from tests.unit import test
class CeilometerStatsTestCase(test.ScenarioTestCase):
def test_get_stats(self):
scenario = stats.GetStats(self.context)
scenario._get_stats = mock.MagicMock()
context = {"user": {"tenan... |
class RevealAccess(object):
"""
A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print('Retrieving', s... |
import sys
import os
import re
import time
import base64
import tempfile
import subprocess
import threading
if __name__ == '__main__':
print 'Please do not launch this file directly.'
sys.exit(0)
def module_path():
if hasattr(sys, "frozen"):
return os.path.dirname(sys.executable)
return os.path.dirname(__file__... |
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
from cloudbaseinit import conf as cloudbaseinit_conf
from cloudbaseinit import exception
from cloudbaseinit.metadata.services import maasservice
from cloudbaseinit.models import network as network_model
from cloudbaseinit.tests ... |
"""Extract, format and print information about Python stack traces."""
import linecache
import sys
import operator
__all__ = ['extract_stack', 'extract_tb', 'format_exception',
'format_exception_only', 'format_list', 'format_stack',
'format_tb', 'print_exc', 'format_exc', 'print_exception',
... |
#
# tiutils.py is a Titanium function library for use with the SpiralArm Titanium plug-in for Sublime Text 3
#
# developed by Steve Rogers, SpiralArm Consulting Ltd (www.spiralarm.uk)
# @sarmcon
#
#
import sublime, subprocess,os
from os.path import expanduser
# read in our default Titanium settings
settings = subl... |
from tendrl.commons.flows.exceptions import FlowExecutionFailedError
from tendrl.commons.utils import log_utils as logger
def get_node_ips(parameters):
node_ips = []
for node, config in parameters["Cluster.node_configuration"].iteritems():
node_ips.append(config["provisioning_ip"])
return node_ips... |
# coding: utf-8
import os
try:
from PIL import Image
except:
pass
from deworld.map_colors import HeightColorMap, RGBColorMap
from deworld.layers import VEGETATION_TYPE
def draw_image(turn, catalog, layer, power_points, colorizer):
if not os.path.exists(catalog):
os.makedirs(catalog)
img = ... |
''' This module supports commandline functionality '''
import argparse
import sys, os
from psiturk.version import version_number
from psiturk.psiturk_org_services import ExperimentExchangeServices
def process():
''' Figure out how we were invoked '''
invoked_as = os.path.basename(sys.argv[0])
if invoked... |
# This code lifted from the mod_wsgi docs.
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
import os
from pathlib import Path
from typing import Sequence
import sys
import signal
import threading
import atexit
import queue
_interval = 1.0
_times = {}
_files ... |
"""
Abstraction of a one-way pipe where the read end can be used in
`select.select`. Normally this is trivial, but Windows makes it nearly
impossible.
The pipe acts like an Event, which can be set or cleared. When set, the pipe
will trigger as readable in `select <select.select>`.
"""
import sys
import os
import sock... |
import win32api, mmapfile
import winerror
import tempfile, os
from pywin32_testutil import str2bytes
system_info=win32api.GetSystemInfo()
page_size=system_info[1]
alloc_size=system_info[7]
fname=tempfile.mktemp()
mapping_name=os.path.split(fname)[1]
fsize=8*page_size
print fname, fsize, mapping_name
m1... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from azure.mgmt... |
import os
import sys
import warnings
# opcode is not a virtualenv module, so we can use it to find the stdlib
# Important! To work on pypy, this must be a module that resides in the
# lib-python/modified-x.y.z directory
import opcode
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(opcode.__fi... |
"""
This code was Ported from CPython's sha512module.c
"""
import struct
SHA_BLOCKSIZE = 128
SHA_DIGESTSIZE = 64
def new_shaobject():
return {
'digest': [0]*8,
'count_lo': 0,
'count_hi': 0,
'data': [0]* SHA_BLOCKSIZE,
'local': 0,
'digestsize': 0
}
ROR64 = lam... |
#!/usr/bin/env python
import io
import os
from setuptools import setup, Extension
def read(fname, encoding='utf-8'):
here = os.path.dirname(__file__)
with io.open(os.path.join(here, fname), encoding=encoding) as f:
return f.read()
setup (
name='PPeg',
version='0.9.4',
description="A Py... |
#!/usr/bin/env python
#
# A module to analyze and identify any common problems which can be determined from log files
#
# Initial code by Andrew Chapman (<EMAIL>), 16th Jan 2014
#
# some logging oddities noticed while doing this, to be followed up on:
# - tradheli MOT labels Mot1,Mot2,Mot3,Mot4,GGain
# - Pixhawk ... |
{
'name': 'Partner Assignation & Geolocation',
'version': '1.0',
'category': 'Customer Relationship Management',
'description': """
This is the module used by OpenERP SA to redirect customers to its partners, based on geolocation.
=========================================================================... |
"""
Author: Chase Coleman
Filename: test_lqcontrol
Tests for lqcontrol.py file
"""
import sys
import os
import unittest
import numpy as np
from scipy.linalg import LinAlgError
from numpy.testing import assert_allclose
from quantecon.lqcontrol import LQ
class TestLQControl(unittest.TestCase):
def setUp(self):
... |
from snovault import (
upgrade_step,
)
@upgrade_step('file_fastq', '1', '2')
@upgrade_step('file_calibration', '1', '2')
@upgrade_step('file_microscopy', '1', '2')
@upgrade_step('file_processed', '1', '2')
@upgrade_step('file_reference', '1', '2')
def file_1_2(value, system):
file_format = value.get('file_for... |
"""
These are the unit tests for the BigQuery-luigi binding.
"""
import luigi
from luigi.contrib import bigquery
from helpers import unittest
from mock import MagicMock
PROJECT_ID = 'projectid'
DATASET_ID = 'dataset'
class TestRunQueryTask(bigquery.BigQueryRunQueryTask):
client = MagicMock()
query = ''' S... |
from . import test_access_rights
checks = [
test_access_rights,
]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import division, absolute_import, print_function
from numpy import (logspace, linspace, geomspace, dtype, array, sctypes,
arange, isnan, ndarray, sqrt, nextafter)
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal, assert_raises,
assert_array_equal,... |
import pygame
from pygame.locals import *
from player import Player
from stagegenerator import StageGenerator
from gamestatus import GameStatus
from gameconfig import GameConfig
class GameEngine():
def __init__(self, modes=None):
pygame.init()
self.screen = pygame.display.set_mode((800, 600))
... |
from msrest.serialization import Model
class LocationCapabilities(Model):
"""The capabilities for a location.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar name: The location name.
:vartype name: str
:ivar status: Azure SQL Database's status fo... |
"""A dumb and slow but simple dbm clone.
For database spam, spam.dir contains the index (a text file),
spam.bak *may* contain a backup of the index (also a text file),
while spam.dat contains the data (a binary file).
XXX TO DO:
- seems to contain a bug when updating...
- reclaim free space (currently, sp... |
class Wind(object):
"""
Current forecast information about the wind.
Attributes:
chill: Wind chill in degrees (integer). If a value for wind chill is not
found, chill will be None.
direction: Wind direction in degrees (integer). If a value for wind
direction is not f... |
from setuptools import setup
import os.path
__license__ = """
Copyright (c) 2015 ScientiaMobile Inc.
The WURFL Cloud Client is intended to be used in both open-source and
commercial environments. To allow its use in as many situations as possible,
the WURFL Cloud Client is dual-licensed. You may choose to use th... |
from datetime import datetime
from django.conf.urls import patterns, url
from django.contrib.sitemaps import Sitemap, GenericSitemap, FlatPageSitemap, views
from django.contrib.auth.models import User
from django.views.decorators.cache import cache_page
from django.contrib.sitemaps.tests.base import TestModel
class ... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
js_to_json,
mimetype2ext,
ExtractorError,
)
class ImgurIE(InfoExtractor):
_VALID_URL = r'https?://(?:i\.)?imgur\.com/(?!(?:a|gallery|(?:t(?:opic)?|r)/[^/]+)/)(?P<id>[a-zA-Z0-9]+... |
#!/usr/bin/env python
import os.path
import re
import sys
import tempfile
import zipfile
import wheel.bdist_wheel
import shutil
import distutils.dist
from distutils.archive_util import make_archive
from argparse import ArgumentParser
from glob import iglob
egg_info_re = re.compile(r'''(?P<name>.+?)-(?P<ver>.+?)
(-... |
import unittest, re, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i
def writeRows(csvPathname,row,eol,repeat):
f = open(csvPathname, 'w')
for r in range(repeat):
f.write(row + eol)
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sa... |
"""Simple HTTP server requiring only Python and no other preconditions.
Server is started by running this script with argument 'start' and
optional port number (default port 7272). Server root is the same
directory where this script is situated. Server can be stopped either
using Ctrl-C or running this script with arg... |
from couchpotato.core.helpers.variable import splitString
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
from pynmwp import PyNMWP
import six
log = CPLog(__name__)
autoload = 'NotifyMyWP'
class NotifyMyWP(Notification):
def notify(self, message = '', data... |
from bok_choy.page_object import PageObject, PageLoadError, unguarded
from bok_choy.promise import BrokenPromise
from .course_page import CoursePage
from ...tests.helpers import disable_animations
from selenium.webdriver.common.action_chains import ActionChains
class NoteChild(PageObject):
url = None
BODY_SEL... |
add_tenant_access = {
'type': 'object',
'properties': {
'addTenantAccess': {
'type': 'object',
'properties': {
'tenant': {
# defined from project_id in instance_type_projects table
'type': 'string', 'minLength': 1, 'maxLengt... |
'''Zulip notification change-commit hook.
In Perforce, The "change-commit" trigger is fired after a metadata has been
created, files have been transferred, and the changelist comitted to the depot
database.
This specific trigger expects command-line arguments in the form:
%change% %changeroot%
For example:
1234 ... |
import socket
import sys
import time
import eventlet
eventlet.monkey_patch()
from oslo.config import cfg
from neutron.agent import rpc as agent_rpc
from neutron.agent import securitygroups_rpc as sg_rpc
from neutron.common import config as common_config
from neutron.common import constants as q_constants
from neutro... |
from __future__ import (absolute_import, division, print_function, unicode_literals)
import logging
import datetime
import time
import socket
import json
import multiprocessing
from contextlib import contextmanager
import sys
import os
HOSTNAME = socket.gethostname()
metric_log_file = None
plugin_params = None
keepal... |
"""Run a target function on a background thread."""
import atexit
import threading
import time
import weakref
from pymongo import thread_util
from pymongo.monotonic import time as _time
class PeriodicExecutor(object):
def __init__(self, condition_class, interval, min_interval, target):
""""Run a target ... |
import netaddr
from tempest_lib.common.utils import data_utils
from tempest_lib import exceptions as lib_exc
from tempest.api.network import base_routers as base
from tempest import config
from tempest import test
CONF = config.CONF
class RoutersNegativeTest(base.BaseRouterTest):
@classmethod
def skip_chec... |
from ginger.dataset import GingerDataSet
from django.forms.widgets import CheckboxInput
import re
from collections import namedtuple
from django.middleware import csrf
from django.utils import six
from django.utils.encoding import force_text
from ginger import utils
from . import common
__all__ = ["Choice", "Link", ... |
""" Beckman Coulter Access 2
"""
from bika.lims import bikaMessageFactory as _
from bika.lims.utils import t
from . import BeckmancoulterAccessCSVParser, BeckmancoulterAccessImporter
import json
import traceback
title = "Beckman Coulter Access 2"
def Import(context, request):
""" Beckman Coulter Access 2 analysi... |
#!/usr/bin/env python
# coding: utf8
"""
Oneall Authentication for web2py
Developed by Nathan Freeze (Copyright © 2013)
Email <<EMAIL>>
This file contains code to allow using onall.com
authentication services with web2py
"""
import os
import base64
from gluon import *
from gluon.storage import Storage... |
from contextlib import contextmanager
from typing import Any, Dict, Generator, List, NamedTuple
import flask
import jinja2
import pytest
from airflow import settings
from airflow.models import DagBag
from airflow.www.app import create_app
from tests.test_utils.api_connexion_utils import create_user, delete_roles
from... |
"""
Filter support
"""
from nova import loadables
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class BaseFilter(object):
"""Base class for all filter classes."""
def _filter_one(self, obj, filter_properties):
"""R... |
import errno
import os
import tempfile
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
class SessionStore(SessionBase):
"""
Implements a file based session store.
"""
... |
# -*- coding: utf-8 -*-
import time
import openerp
class m(openerp.osv.osv.Model):
""" This model exposes a few methods that will consume between 'almost no
resource' and 'a lot of resource'.
"""
_name = 'test.limits.model'
def consume_nothing(self, cr, uid, context=None):
return True... |
from .constants import eStart
from .compat import wrap_ord
class CodingStateMachine:
def __init__(self, sm):
self._mModel = sm
self._mCurrentBytePos = 0
self._mCurrentCharLen = 0
self.reset()
def reset(self):
self._mCurrentState = eStart
def next_state(self, c):
... |
import time
import queue
from typing import List, Optional
from wsproto.frame_protocol import CloseReason
from wsproto.frame_protocol import Opcode
from mitmproxy import flow
from mitmproxy.net import websockets
from mitmproxy.coretypes import serializable
from mitmproxy.utils import strutils, human
class WebSocket... |
import os
import logging
from autotest.client import utils
from autotest.client.shared import error
from virttest import data_dir
from virttest import qemu_virtio_port
# This decorator makes the test function aware of context strings
@error.context_aware
def run(test, params, env):
"""
QEMU 'Windows virtio-... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : <EMAIL>
**... |
# Example of a generator: re-implement the built-in range function
# without actually constructing the list of values. (It turns out
# that the built-in function is about 20 times faster -- that's why
# it's built-in. :-)
# Wrapper function to emulate the complicated range() arguments
def range(*a):
if len(a) == 1... |
import unittest
from stem.interpreter.arguments import DEFAULT_ARGS, parse, get_help
class TestArgumentParsing(unittest.TestCase):
def test_that_we_get_default_values(self):
args = parse([])
for attr in DEFAULT_ARGS:
self.assertEqual(DEFAULT_ARGS[attr], getattr(args, attr))
def test_that_we_load_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mptt',
'cms',
'menus',
'djangocms_googlemap',
'south',
]
DATABASES = {
... |
"""Additional help about gsutil's interaction with Cloud Storage APIs."""
from gslib.help_provider import HelpProvider
_DETAILED_HELP_TEXT = ("""
<B>OVERVIEW</B>
Google Cloud Storage offers two APIs: an XML and a JSON API. Gsutil can
interact with both APIs. By default, gsutil versions starting with 4.0
interac... |
import getpass
import mock
from apache.thermos.cli.commands.simplerun import simplerun
@mock.patch('apache.thermos.cli.commands.simplerun.really_run')
def test_simplerun(really_run_mock):
options_mock = mock.Mock(
spec_set=('root', 'user', 'name', 'task_id', 'prebound_ports', 'bindings', 'daemon'))
option... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
from binascii import a2b_base64, b2a_base64
from contextlib import contextmanager
from multiprocessing.pool import ThreadPool
from mentos.exceptions import (DetectorClosed, NoLeadingMaster,
... |
from veripy.models import ComplianceTestSuite
from veripy.models.decorators import must, should
import client
#import relay_agent
import server
class StatelessDHCPv6ServiceClientSpecification(ComplianceTestSuite):
"""
Stateless Dynamic Host Configuration Protocol Service for IPv6 (DHCPv6 Client)
These te... |
import sys
import commands
import pykolab
from pykolab.auth import Auth
from pykolab import utils
from pykolab.translate import _
log = pykolab.getLogger('pykolab.cli')
conf = pykolab.getConf()
def __init__():
commands.register('remove_mail', execute, description=description())
def description():
return "... |
"""
Make sure PGO is working properly.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('pgo.gyp', chdir=CHDIR)
def IsPGOAvailable():
"""Returns true if the Visual Studio available here supports PGO... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.k8s.common import K8sAnsibleMixin
from ansible.errors import AnsibleError
try:
from openshift.dynamic import DynamicClient
from openshift.dynamic.... |
from functools import update_wrapper
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.db import models
from django.http import HttpResponseRedirect
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Action(models.Model):
name ... |
""" Tests for the linecache module """
import linecache2 as linecache
import unittest2 as unittest
import os.path
import tempfile
from fixtures import NestedTempfile
FILENAME = os.__file__
if FILENAME.endswith('.pyc'):
FILENAME = FILENAME[:-1]
NONEXISTENT_FILENAME = FILENAME + '.missing'
INVALID_NAME = '!@$)(!@#... |
from sqlalchemy.sql.expression import (
Alias,
ClauseElement,
ColumnCollection,
ColumnElement,
CompoundSelect,
Delete,
FromClause,
Insert,
Join,
Select,
Selectable,
TableClause,
Update,
alias,
and_,
asc,
between,
bindparam,
case,
cast,
... |
def node_exists(api, address):
# hack to determine if node exists
result = False
try:
api.LocalLB.NodeAddressV2.get_object_status(nodes=[address])
result = True
except bigsuds.OperationFailed, e:
if "was not found" in str(e):
result = False
else:
#... |
"""
Falcon-based tile server for tile databases generated with osgende-mapgen.
Use with uWSGI.
"""
import datetime
import os
import sys
import threading
import hashlib
from math import pi,exp,atan
import falcon
import mapnik
RAD_TO_DEG = 180/pi
class TileProjection:
def __init__(self,levels=18):
self.Bc... |
"""
Acceptance tests for Studio's Settings Details pages
"""
from unittest import skip
from .base_studio_test import StudioCourseTest
from ...fixtures.course import CourseFixture
from ...pages.studio.settings import SettingsPage
from ...pages.studio.overview import CourseOutlinePage
from ...tests.studio.base_studio_te... |
import airflow.api
from airflow.api.common.experimental import pool as pool_api
from airflow.api.common.experimental import trigger_dag as trigger
from airflow.api.common.experimental import delete_dag as delete
from airflow.api.common.experimental.get_task import get_task
from airflow.api.common.experimental.get_task... |
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict_... |
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_ozw as sensorObj
def main():
# This function lets you run code on exit
def exitHandler():
print("Exiting")
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
defaultDev = "/... |
# -*- coding: utf-8 -*-
"""
twp support functions
@author: Jev Kuznetsov
Licence: GPL v2
"""
from scipy import polyfit, polyval
import datetime as dt
#from datetime import datetime, date
from pandas import DataFrame, Index, Series
import csv
import matplotlib.pyplot as plt
import numpy as np
import p... |
import sys
if __name__ == '__main__':
import os
pkg_dir = (os.path.split(
os.path.split(
os.path.split(
os.path.abspath(__file__))[0])[0])[0])
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
... |
from Components.config import config
from Renderer import Renderer
from enigma import eLabel, eTimer
from boxbranding import getMachineProcModel
from Components.VariableText import VariableText
class RollerCharLCD(VariableText, Renderer):
def __init__(self):
Renderer.__init__(self)
VariableText.__init__(self)
i... |
# strings
assert 'a'.__class__ == str
assert isinstance('a',str)
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
hello = """\
Usage: thingy [OPTIONS]
-h Display... |
"""Distributed MNIST training and validation, with model replicas.
A simple softmax model with one hidden layer is defined. The parameters
(weights and biases) are located on one parameter server (ps), while the ops
are executed on two worker nodes by default. The TF sessions also run on the
worker node.
Multiple invo... |
"""
Protocol implementation.
"""
try:
from hashlib import md5
except ImportError:
from md5 import md5
try:
import json
except ImportError:
import simplejson as json
from avro import schema
#
# Constants
#
# TODO(hammer): confirmed 'fixed' with Doug
VALID_TYPE_SCHEMA_TYPES = ('enum', 'record', 'error', 'fixed'... |
import nest
import numpy as np
import unittest
class FacetsTestCase(unittest.TestCase):
"""
This script is testing the accumulation of spike pairs and
the weight update mechanism as implemented in the FACETS hardware.
Author: Thomas Pfeil
Date of first version: 21.01.2013
"""
def test_fa... |
__author__ = '<EMAIL> (Jeff Scudder)'
import unittest
import gdata.blogger.client
import gdata.blogger.data
import gdata.gauth
import gdata.client
import atom.http_core
import atom.mock_http_core
import atom.core
import gdata.data
import gdata.test_config as conf
conf.options.register_option(conf.BLOG_ID_OPTION)
... |
from parallel_executor_test_base import TestParallelExecutorBase, DeviceType
import paddle.fluid as fluid
import paddle.fluid.core as core
import numpy as np
import paddle
import paddle.dataset.mnist as mnist
import unittest
import os
def _feed_data_helper():
img = fluid.layers.data(name='image', shape=[784], dty... |
from gnuradio import gr, digital, filter
from gnuradio import blocks
from gnuradio import channels
from gnuradio import eng_notation
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import sys
try:
import scipy
except ImportError:
print "Error: could not import scipy (http://www.sci... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
classification.py
---------------------
Date : July 2015
Copyright : (C) 2015 by Arnaud Morvan
Email : arnaud dot morvan at camptocamp dot com
**********... |
from django.conf import settings
from django.forms import ValidationError # noqa
from django import http
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables # noqa
from horizon import exceptions
from horizon import forms
from horizon import messages
f... |
# -*- coding: utf-8 -*-
import os, time
import hashlib
import datetime
from warnings import warn
from .helpers import request_except_handler, require_auth
from app.configparser import config
from app.utils import get_json_localization
from app.mixins.auth import AuthMixin
from app.mixins.routes import JsonResponseM... |
"""
This module contains a base type which provides list-style mutations
without specific data storage methods.
See also http://static.aryehleib.com/oldsite/MutableLists.html
Author: Aryeh Leib Taurog.
"""
from functools import total_ordering
from django.utils import six
from django.utils.six.moves import range
@t... |
import numpy as np
import matplotlib.pyplot as plt
from ....wcs import WCS
from ....tests.helper import pytest, remote_data
from .. import WCSAxes
from ..frame import BaseFrame
from ....tests.image_tests import IMAGE_REFERENCE_DIR
from .test_images import BaseImageTests
class HexagonalFrame(BaseFrame):
spine_... |
"""API for PID relations concepts."""
from __future__ import absolute_import, print_function
from flask import Blueprint
from invenio_db import db
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
from ..api import PIDConceptOrdered
from ..models import PIDRelation
from ..utils import resolve_relat... |
# -*- coding: utf-8 -*-
__license__ = 'GPL 3'
__copyright__ = '2009, John Schember <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import re
class TCRCompressor(object):
'''
TCR compression takes the form header+code_dict+coded_text.
The header is always "!!8-Bit!!". The code dict is a list of 256 strin... |
import testtools
import webob.exc
from nova.api.openstack.compute.contrib import hosts as os_hosts_v2
from nova.api.openstack.compute.plugins.v3 import hosts as os_hosts_v21
from nova.compute import power_state
from nova.compute import vm_states
from nova import context as context_maker
from nova import db
from nova i... |
__all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2', 'oldtypecodes']
import numpy as np
oldtype2dtype = {'1': np.dtype(np.byte),
's': np.dtype(np.short),
# 'i': np.dtype(np.intc),
# 'l': np.dtype(int),
# 'b': np.dtype(np.ubyte),
... |
import base64
import datetime
import re
from uuid import UUID
from math import isnan, isinf
import logging
LOG = logging.getLogger(__name__)
import bson
import bson.json_util
from mongo_connector.compat import PY3
if PY3:
long = int
unicode = str
RE_TYPE = type(re.compile(""))
try:
from bson.regex im... |
microcode = '''
def macroop CMPS_M_M {
# Find the constant we need to either add or subtract from rdi
ruflag t0, 10
movi t3, t3, dsz, flags=(CEZF,), dataSize=asz
subi t4, t0, dsz, dataSize=asz
mov t3, t3, t4, flags=(nCEZF,), dataSize=asz
ld t1, seg, [1, t0, rsi]
ld t2, es, [1, t0, rdi]
... |
#FLM: RoboFab Intro, Generating Fonts
#
#
# demo generating fonts with robofab
#
#
# Generating fonts with RoboFab is super easy! Let's have a look.
# (you will need to have a font open in FontLab)
from robofab.world import CurrentFont
import os
# A little function for making folders. we'll need it later.
def make... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.