content stringlengths 4 20k |
|---|
import unittest
import pysal
from pysal.core.IOHandlers.arcgis_txt import ArcGISTextIO
import tempfile
import os
import warnings
class test_ArcGISTextIO(unittest.TestCase):
def setUp(self):
self.test_file = test_file = pysal.examples.get_path('arcgis_txt.txt')
self.obj = ArcGISTextIO(test_file, 'r... |
from __future__ import absolute_import, unicode_literals
import json
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.widgets import AdminChooser
class AdminSnippetChooser(AdminChooser):
target_content_type = None
def __i... |
"""Set of utility functions for working with virtual machines."""
import contextlib
import logging
import os
import random
import re
import string
import subprocess
import tempfile
import threading
import time
import jinja2
from perfkitbenchmarker import background_tasks
from perfkitbenchmarker import data
from perf... |
from distutils.version import StrictVersion
from pyparsing import (
__version__, alphanums, alphas, CaselessKeyword, CaselessLiteral, Combine,
delimitedList, FollowedBy, Forward, Group, LineEnd, Literal, OneOrMore,
Optional, printables, quotedString, Regex, Word, ZeroOrMore,
)
grammar = Forward()
express... |
# -*- coding: utf-8 -*-
from os import path
import wx
from wx.lib.filebrowsebutton import DirBrowseButton
from ...common.i18n import _
class ShareLocationBrowser(DirBrowseButton):
"""
Derive the class DirBrowseButton to apply the share name as child folder
each time user changes the directory by clicking... |
import sys
import time
from django.conf import settings
from django.db.utils import load_backend
# The prefix to put on the default database name when creating
# the test database.
TEST_DATABASE_PREFIX = 'test_'
class BaseDatabaseCreation(object):
"""
This class encapsulates all backend-specific differences... |
from __future__ import unicode_literals
import re
import sys
"""
Python 3 Stuff
=============================================================================
"""
PY3 = sys.version_info[0] == 3
if PY3:
string_type = str
text_type = str
int2str = chr
else:
string_type = basestring
text_type = unico... |
from gnuradio import gr
from gnuradio import audio
from gnuradio.eng_option import eng_option
from optparse import OptionParser
try:
from gnuradio import analog
except ImportError:
sys.stderr.write("Error: Program requires gr-analog.\n")
sys.exit(1)
class my_top_block(gr.top_block):
def __init__(self... |
from twisted.trial import unittest
from twisted.python import log
from dht.node import Node
from dht.utils import digest
from dht.routing import RoutingTable
from market.protocol import MarketProtocol
from dht.tests.utils import mknode
class MarketProtocolTest(unittest.TestCase):
def setUp(self):
self.cat... |
import os
import urllib2
from mercurial import error, httprepo, util, wireproto
from mercurial.i18n import _
import lfutil
LARGEFILES_REQUIRED_MSG = ('\nThis repository uses the largefiles extension.'
'\n\nPlease enable it in your Mercurial config '
'file.\n')
d... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PackageMetric'
db.create_table(u'parsr_packagemetric', (
... |
import sys
if sys.version > '3':
xrange = range
import numpy as np
from pyspark.mllib.common import callMLlibFunc
from pyspark.rdd import RDD
class KernelDensity(object):
"""
Estimate probability density at required points given an RDD of samples
from the population.
>>> kd = KernelDensity()
... |
import fileinput
collections = { "gram": [],
"keyword": [],
"reserved": [],
"binop": [],
"unop": [] }
in_coll = False
coll = ""
for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")):
if in_coll:
if line.startswith("~~~~"):
... |
from cStringIO import StringIO
from socket import error as socketerror
protocol_name = 'BitTorrent protocol'
# header, reserved, download id, my id, [length, message]
class NatCheck:
def __init__(self, resultfunc, downloadid, peerid, ip, port, rawserver):
self.resultfunc = resultfunc
self.downloa... |
import argparse
import logging
import mxnet as mx
import numpy as np
from data import get_movielens_iter, get_movielens_data
from model import matrix_fact_net
import os
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser(description="Run matrix factorization with sparse embedding",
... |
from core.himesis import Himesis
class HeclassOUTeSuperTypesSolveRefEClassEClassEClassEClass(Himesis):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HeclassOUTeSuperTypesSolveRefEClassEClassEClassEClass.
"""
# Flag this instance as compiled now
... |
"""
Implementation of "credit" XBlock service
"""
import logging
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from opaque_keys.edx.keys import CourseKey
from student.models import CourseEnrollment
from xmodule.modulestore.django import modulestore
log = logging.g... |
"""This file defines the Concrete Array --- a leaf node in the expression graph
A concrete array is constructed from a Data Descriptor Object which handles the
indexing and basic interpretation of bytes
"""
from __future__ import absolute_import, division, print_function
import datashape
from ..compute.ops import ... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_firewall
version_added: "2.4"
short_description: Manages Windows Firewall
description:
- Manages Windows Firewall
options:
profile:
d... |
''' useful functions for finding content and its position '''
from logging import getLogger
from .exceptions import (ItemNotFoundError, NoPathToItem)
LOGGER = getLogger(__name__)
def path_to_location(modulestore, usage_key, full_path=False):
'''
Try to find a course_id/chapter/section[/position] path to loc... |
"""
This module houses the GEOSCoordSeq object, which is used internally
by GEOSGeometry to house the actual coordinates of the Point,
LineString, and LinearRing geometries.
"""
from ctypes import c_double, c_uint, byref
from django.contrib.gis.geos.base import GEOSBase, numpy
from django.contrib.gis.geos.err... |
import logging
import json
import os
import sys
import tempfile
import time
import traceback
import zipfile
from django.conf import settings
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core.servers.basehttp import FileWra... |
import fs.osfs
import os, os.path
from capa.capa_problem import LoncapaProblem
from mock import Mock, MagicMock
import xml.sax.saxutils as saxutils
TEST_DIR = os.path.dirname(os.path.realpath(__file__))
def tst_render_template(template, context):
"""
A test version of render to template. Renders to the re... |
import os
import os.path
import sys
import re
###############################################################################
# Main
################################################################################
if __name__ == "__main__":
print "Starting exclusion"
print "- - - - - - - - - - - - - - - - - - - -... |
# from winbase.h
STDOUT = -11
STDERR = -12
try:
from ctypes import windll
except ImportError:
windll = None
SetConsoleTextAttribute = lambda *_: None
else:
from ctypes import (
byref, Structure, c_char, c_short, c_uint32, c_ushort
)
handles = {
STDOUT: windll.kernel32.GetStdHan... |
"""
PostgreSQL database backend for Django.
Requires psycopg 2: http://initd.org/projects/psycopg2
"""
import sys
from django.db import utils
from django.db.backends import *
from django.db.backends.signals import connection_created
from django.db.backends.postgresql.operations import DatabaseOperations as Postgresq... |
# -*- encoding: utf-8 -*-
"""
$Id: Type.py,v 1.6.2.1 2007/05/22 20:20:39 customdesigned Exp $
This file is part of the pydns project.
Homepage: http://pydns.sourceforge.net
This code is covered by the standard Python License.
TYPE values (section 3.2.2)
"""
A = 1 # a host address
NS = 2 # an... |
#!/usr/bin/env python
print("Use this script to tell master-clock what time your slave clock displays.")
print("Type Ctrl+C to cancel.");
#External settings
import settings
#External modules
import os
import sys
#def getScriptPath():
# # http://stackoverflow.com/a/4943474
# return os.path.dirname(os.path.real... |
import datetime
import decimal
import unicodedata
from importlib import import_module
from django.conf import settings
from django.utils import dateformat, datetime_safe, numberformat, six
from django.utils.encoding import force_str
from django.utils.functional import lazy
from django.utils.safestring import mark_safe... |
from paddle.trainer.PyDataProvider2 import *
UNK_IDX = 0
def hook(settings, word_dict, label_dict, predicate_dict, **kwargs):
settings.word_dict = word_dict
settings.label_dict = label_dict
settings.predicate_dict = predicate_dict
#all inputs are integral and sequential type
settings.slots = [
... |
#!/usr/bin/env python
import sys
def gen_test(n):
print "CREATE TABLE t (a CHAR(%d));" % (n)
print "--replace_regex /MariaDB/XYZ/ /MySQL/XYZ/"
print "--error ER_UNSUPPORTED_EXTENSION"
print "ALTER TABLE t CHANGE COLUMN a a CHAR(%d) BINARY;" % (n)
if n+1 < 256:
print "--replace_regex /MariaD... |
"""
Make sure fixed base setting is extracted properly.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('fixed-base.gyp', chdir=CHDIR)
test.build('fixed-base.gyp', test.ALL, chdir=CHDIR)
def GetHeaders(exe):
... |
"""
Exceptions that may happen in all the webdriver code.
"""
class WebDriverException(Exception):
"""
Base webdriver exception.
"""
def __init__(self, msg=None, screen=None, stacktrace=None):
self.msg = msg
self.screen = screen
self.stacktrace = stacktrace
def __str__(sel... |
#!/usr/bin/env python3.5
"""
PACE
TODO:
* model training/testing
* more models (technically)
* multithreading
"""
import sys
import os
import argparse
import hashlib
import typing
from enforce import runtime_validation as types
from tqdm import tqdm
import numpy as np
import numpy.linalg as lin... |
from datetime import timedelta
from configman import Namespace, RequiredConfig, class_converter
from socorrolib.lib.converters import (
change_default,
)
from socorrolib.lib.datetimeutil import (
utc_now,
string_to_datetime,
)
from socorro.external.postgresql.dbapi2_util import execute_query_fetchall
#=... |
from PyQt4.QtGui import *
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
import datetime
from electrum.util import format_satoshis
try:
import matplotlib.pyplot as plt
import matplotlib.dates as md
from matplotlib.patches import Ellipse
from matplotlib.offsetbox import Anc... |
"""
Path operations common to more than one OS
Do not use directly. The OS specific modules import the appropriate
functions from this module themselves.
"""
import os
import stat
__all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime',
'getsize', 'isdir', 'isfile', 'samefile', 'sameopenfil... |
from __future__ import with_statement
import datetime
import time
import sickbeard
from sickbeard import db, logger, common, exceptions, helpers
from sickbeard import generic_queue
from sickbeard import search
from sickbeard import ui
BACKLOG_SEARCH = 10
RSS_SEARCH = 20
MANUAL_SEARCH = 30
class Searc... |
'''Commandline scripts.
These scripts are called by the executables defined in setup.py.
'''
from __future__ import with_statement, print_function
import abc
import sys
from optparse import OptionParser
import rsa
import rsa.bigfile
import rsa.pkcs1
HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys())
def keygen(... |
import httplib as http
import logging
import os
from addons.base.models import (BaseOAuthNodeSettings, BaseOAuthUserSettings,
BaseStorageAddon)
from django.db import models
from dropbox.client import DropboxClient, DropboxOAuth2Flow
from dropbox.rest import ErrorResponse
from flask impo... |
from dispel4py.core import GenericPE
from dispel4py.base import IterativePE
class MyFirstPE(GenericPE):
def __init__(self):
GenericPE.__init__(self)
self._add_input('input')
self._add_output('prime')
self._add_output('output')
self.divisor = None
def _process(self, in... |
"""Mailing templatetags"""
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from open_connect.mailer.utils import (
unsubscribe_url, url_representation_encode, generate_code
... |
import re
import sys
class Func(object):
# FIXME: parse ftype into params and values
def __init__(self, name="unknown", params=[], values=[], address=0, size=0, ftype=""):
self.name = name
self.params = params
self.values = values
self.address = address
self.size = size
self.ftype = ftype
class Llabel(ob... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Mike Place <<EMAIL>>`
'''
# Import Python libs
from __future__ import absolute_import
import os
# Import Salt Testing libs
from salttesting import skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import patch, NO_MOCK, NO_MOCK_REASON
e... |
from odoo import fields, models, api, _
from odoo.exceptions import ValidationError
class PurchaseRequest(models.Model):
_inherit = 'purchase.request'
operating_unit_id = fields.Many2one(
'operating.unit',
string='Operating Unit',
states={'to_approve': [('readonly', True)],
... |
#! /usr/bin/env python3
# Variant of "which".
# On stderr, near and total misses are reported.
# '-l<flags>' argument adds ls -l<flags> of each file found.
import sys
if sys.path[0] in (".", ""): del sys.path[0]
import sys, os
from stat import *
def msg(str):
sys.stderr.write(str + '\n')
def main():
pathli... |
from collections import deque
import logging
from lib.aws import requests
from lib.aws.exception import AccessDeniedException
from lib.iam.exception import IamEntityAlreadyExistsException, IamLimitExceededException
from lib.utility import misc
from scli import api_wrapper, prompt
from scli.constants import EbDefault, ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.utils.listify import listify_lookup_plugin_terms
from ansible.utils.boolean import boolean
FLAGS = ('skip_missing',)
class Lookup... |
# $Id: icmp6.py 23 2006-11-08 15:45:33Z dugsong $
"""Internet Control Message Protocol for IPv6."""
import dpkt, ip6
ICMP6_DST_UNREACH = 1 # dest unreachable, codes:
ICMP6_PACKET_TOO_BIG = 2 # packet too big
ICMP6_TIME_EXCEEDED = 3 # time exceeded, code:
ICMP6_PARAM_PROB... |
import torch
import torch.nn as nn
def quant_noise(module, p, block_size):
"""
Wraps modules and applies quantization noise to the weights for
subsequent quantization with Iterative Product Quantization as
described in "Training with Quantization Noise for Extreme Model Compression"
Args:
... |
import json
import os
import sys
import unittest
from samples_data_source import SamplesDataSource
from servlet import Request
class SamplesDataSourceTest(unittest.TestCase):
def setUp(self):
self._base_path = os.path.join(sys.path[0],
'test_data',
... |
import pyfits
import numpy
derotator = 359.6
azimuth = 139.5
mode = 'STAT'
angleTable = pyfits.getdata('RTC.'+mode+'.ANGLE_TABLE.fits')
HOIM = pyfits.getdata('RTC.'+mode+'.HOIM.fits')
if mode == 'SKY':
index = numpy.argsort(numpy.abs(angleTable[:,0]-azimuth))[0]
value = numpy.average(HOIM[:,index])
elif mo... |
from bottle import ResourceManager
import os.path
import unittest
class TestResourceManager(unittest.TestCase):
def test_path_normalize(self):
tests = ('/foo/bar/', '/foo/bar/baz', '/foo/baz/../bar/blub')
for test in tests:
rm = ResourceManager()
rm.add_path(test)
... |
import logging
import pprint
from django.contrib.auth import authenticate, login
logger = logging.getLogger('api.editor.middleware')
class AuthMiddleware(object):
"""
Simple middleware if there is a token and user in the request
that has been generated with the api. This middleware class needs
to be... |
#!usr/bin/env python
# coding=utf-8
"""
author:wubaichuan
"""
from django.conf.urls import patterns, url
urlpatterns = patterns('blog',
<<<<<<< HEAD
url(r'^(?P<page>\d*)$', 'views.common.index', name='index'),
url(r'^login/$', 'views.auth.user_login', name='user_login'),... |
"""Load configuration from environment
"""
import os
import ccxt
import yaml
class Configuration():
"""Parses the environment configuration to create the config objects.
"""
def __init__(self):
"""Initializes the Configuration class
"""
with open('defaults.yml', 'r') as config_f... |
"""Module for implementing question tags."""
__author__ = '<EMAIL> (Sean Lip)'
import os
import jinja2
from common import jinja_utils
from common import schema_fields
from common import tags
from controllers import lessons
from models import custom_modules
from models import progress
RESOURCES_PATH = '/modules/opp... |
try:
import lib.uasyncio as asyncio
except ImportError:
import uasyncio as asyncio
try:
import logging
except ImportError:
import lib.logging as logging
from WaterPumps.flowMeters import flowMeter
from WaterPumps.flowMeters import callbackflow
from WaterPumps.pumps import pump
from WaterPumps.leds... |
#!/usr/bin/env python
# encoding: utf-8
from vilya.config import DOMAIN
from dispatches.notifications import NotificationDispatcher
from vilya.libs.irc import IrcMsg
from vilya.models.actions.team_add_member import TeamAddMember
from vilya.models.notification import Notification
class Dispatcher(NotificationDispatch... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .client_message_serializer import ClientMessageSerializer
from .constants import MSG_CONNECT
__all__ = ['ConnectMessageSerializer']
class ConnectMessageSerializer(ClientMessageSerializer):
MESSAGE_T... |
from traits.api import Button
from traitsui.api import View, UItem, VGroup, EnumEditor, \
HGroup, CheckListEditor, spring, Group, HSplit
from pychron.core.ui.combobox_editor import ComboboxEditor
from pychron.core.ui.qt.tabular_editors import FilterTabularEditor
from pychron.core.ui.tabular_editor import myTabular... |
#
# DSA.py : Digital Signature Algorithm
#
# Part of the Python Cryptography Toolkit
#
# Distribute and use freely; there are no restrictions on further
# dissemination and usage except those imposed by the laws of your
# country of residence. This software is provided "as is" without
# warranty of fitness for use ... |
import logging
import django
from django.conf import settings
import json
from django.views.generic.base import View
from django.http import HttpResponse, Http404
from dajaxice.exceptions import FunctionNotCallableError
from dajaxice.core import dajaxice_functions, dajaxice_config
log = logging.getLogger('dajaxice')
... |
"""
This module houses the ctypes function prototypes for OGR DataSource
related data structures. OGR_Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*,
OGR_Fld_* routines are relevant here.
"""
from ctypes import c_char_p, c_double, c_int, c_long, c_void_p, POINTER
from django.contrib.gis.gdal.envelope import OGREnvelope
from djan... |
'''
Abbreviation Extension for Python-Markdown
==========================================
This extension adds abbreviation handling to Python-Markdown.
Simple Usage:
>>> import markdown
>>> text = """
... Some text with an ABBR and a REF. Ignore REFERENCE and ref.
...
... *[ABBR]: Abbreviation
... |
from core.services import PDFGeneratorView, ICSView
from wagtail.wagtailcore.models import Page
from django.shortcuts import render, redirect, get_object_or_404
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from wagtail.wagtailadmin import messages as wagtail_messages
from django.utils.transla... |
from __future__ import absolute_import, division, print_function
import os
import sys
import time
import signal
import argparse
import subprocess
import logging
import importlib
import json
import sqlite3
import tempfile
import shutil
import glob
import requests
import psutil
# add iceprod to PY... |
import ConfigParser
import os
import pipes
try:
import MySQLdb
except ImportError:
mysqldb_found = False
else:
mysqldb_found = True
# ===========================================
# MySQL module specific support methods.
#
def db_exists(cursor, db):
res = cursor.execute("SHOW DATABASES LIKE %s", (db.rep... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.profiler
~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides a simple WSGI profiler middleware for finding
bottlenecks in web application. It uses the :mod:`profile` or
:mod:`cProfile` module to do the profiling and writes the stats to the
stream provide... |
import re
import os
import urllib
import time
NAME_PREFIX = 'WEATHER_'
PARAMS = {
}
URL = "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=51.746%2C-1.296&sp=IOXFORDS54"
LAST_COLLECTION = 0
# collect new data every 2 minutes
TIME_DIFFERENCE = 120
CACHE = { 'wind_direction' : 0,
'wind_s... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'CourseEnrollment.is_active'
db.add_column('student_courseenrollment', 'is_active',
... |
import openerp
from openerp.tools.safe_eval import safe_eval as eval
class DiagramView(openerp.addons.web.http.Controller):
_cp_path = "/web_diagram/diagram"
@openerp.addons.web.http.jsonrequest
def get_diagram_info(self, req, id, model, node, connector,
src_node, des_node, label,... |
from django.test import TestCase
from django.shortcuts import resolve_url
from MMTest.core.tests.view_testing_utils import ViewTestMixin
from MMTest.core.tests.view_testing_utils import FormErrorTestMixin
from MMTest.core.tests.view_testing_utils import FormSuccessTestMixin
from MMTest.core.tests.view_testing_utils im... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.encoding import force_str, python_2_unicode_compatible
# Levels
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
CRITICAL = 50
@python_2_unicode_compatible
class CheckMessage(object):
def __init__(self, level, msg, hint=None, obj=Non... |
from django.core.management.base import BaseCommand
from certificates.models import certificate_status_for_student
from certificates.queue import XQueueCertInterface
from django.contrib.auth.models import User
from optparse import make_option
from django.conf import settings
from xmodule.course_module import CourseDesc... |
import unittest
from polymorphism_ext import *
class PolymorphTest(unittest.TestCase):
def testReturnCpp(self):
# Python Created Object With Same Id As
# Cpp Created B Object
# b = B(872)
# Get Reference To Cpp Created B Object
a = getBCppObj()
# Python Created B Object a... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Hotel(models.Model):
name = models.CharField(max_length=200)
web = models.TextField()
address = models.CharField(max_length=100)
# category = models.CharField(max_length=20)
# stars = models.Integer... |
import remap
# --- create file i/o objects to be used ----
def create_vertex_reader( filename ):
return remap.TextFileReader( filename, yieldkv=False )
def create_vertex_partitioner( outputdir, partition, mapperid ):
return remap.TextPartitioner( outputdir, partition, mapperid )
NUM_VERTICES = 10
# ---- pag... |
#!/usr/bin/env python
"""
Your task is to complete the 'porsche_query' function and in particular the query
to find all autos where the manufacturer field matches "Porsche".
Please modify only 'porsche_query' function, as only that will be taken into account.
Your code will be run against a MongoDB instance that we ha... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def handle(val, cur_val,... |
""" A test DB in DIRAC, using MySQL as backend
"""
from DIRAC.Core.Base.DB import DB
from DIRAC import gLogger, S_OK, S_ERROR
class UserDB(DB):
""" Database system for users """
def __init__(self):
"""
Initialize the DB
"""
super(UserDB, self).__init__('UserDB', 'Framework/UserDB')
retVal ... |
"""
Retrieve tiles from different tile servers (TMS/TileCache/etc.).
"""
import sys
from mapproxy.image.opts import ImageOptions
from mapproxy.source import SourceError
from mapproxy.client.http import HTTPClientError
from mapproxy.source import InvalidSourceQuery
from mapproxy.layer import BlankImage, map_extent_from... |
import io
import unittest
from contextlib import redirect_stdout
from datetime import datetime, timedelta
from unittest import mock
from parameterized import parameterized
from tabulate import tabulate
from airflow import AirflowException, models
from airflow.bin import cli
from airflow.cli.commands import task_comma... |
# META: timeout=long
import pytest
from tests.support.asserts import assert_dialog_handled, assert_error, assert_success
from tests.support.inline import inline
def forward(session):
return session.transport.send(
"POST", "session/{session_id}/forward".format(**vars(session)))
@pytest.fixture
def page... |
from django.db import models
from django.db.models.fields import *
from baseapp.models import *
import caching.base
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
from django.db.models.signals import post_save, post_delete
from imagekit import ImageSpec, register
from imag... |
import mock
import unittest
from cfgm_common.analytics_client import Client
class TestOpenContrailClient(unittest.TestCase):
def setUp(self):
super(TestOpenContrailClient, self).setUp()
self.client = Client('http://127.0.0.1:8081', {'arg1': 'aaa'})
self.get_resp = mock.MagicMock()
... |
"""Tests for new version of accumulate_n op that will eventually go into
`ops.math_ops`.
These test cases spefically exercise the `eager` APIs. They need to be in a
separate file from the remaining tests because eager mode is currently something
you can turn on but can't turn off for the lifetime of the current proces... |
import numpy as np
import dipy as dp
import nibabel as ni
dname = '/home/eg01/Data_Backup/Data/Eleftherios/CBU090133_METHODS/20090227_145404/Series_003_CBU_DTI_64D_iso_1000'
#dname = '/home/eg01/Data_Backup/Data/Frank_Eleftherios/frank/20100511_m030y_cbu100624/08_ep2d_advdiff_101dir_DSI'
data,affine,bvals,gradients... |
"""This test checks that waiting for a table at different levels of readiness returns at the right time."""
import threading, os, sys, time
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import driver, scenario_common, utils, vcoptparse
r = utils.import_python_dri... |
# -*-coding:Utf-8 -*
# ====================================================================
# ====================================================================
# Packages
# ====================================================================
import sys
import numpy as np
from muLAn.models.multipole import hexamag... |
from couchpotato.core.event import fireEvent
from couchpotato.core.helpers.encoding import tryUrlencode
from couchpotato.core.helpers.rss import RSS
from couchpotato.core.logger import CPLog
from couchpotato.core.providers.nzb.base import NZBProvider
from dateutil.parser import parse
import base64
import time
import xm... |
import os
from pathlib import Path
import unittest
import shared
class SharedTestCodeTest(unittest.TestCase):
def test_create_dir(self):
empty_dir = shared.create_dir()
self.assertListEqual([], os.listdir(empty_dir))
content = {Path('foo'): 'a', Path('bar/baz'): 'b'}
content_dir ... |
"""
Canada-specific Form helpers
"""
from __future__ import absolute_import
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, CharField, Select
from django.utils.encoding import smart_unicode
from django.utils.translation import ... |
"""Tools for interpolating to a vertical slice/cross section through data."""
import numpy as np
import xarray as xr
from ..package_tools import Exporter
from ..units import units
from ..xarray import check_axis
exporter = Exporter(globals())
@exporter.export
def interpolate_to_slice(data, points, interp_type='lin... |
from libpandaexpress import BufferedDatagramConnection
from libpandaexpress import SocketAddress
from libpandaexpress import SocketIP
from libpandaexpress import SocketTCP
from libpandaexpress import SocketTCPListen
from libpandaexpress import SocketUDPOutgoing
from libpandaexpress import SocketUDPIncoming
from ... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
import os
import re
import time
HAS_XMPP = True
try:
import xmpp
except ImportError:
HAS_XMPP = False
def main():
module = AnsibleModule(
argument_spe... |
from django.http import JsonResponse, HttpResponse
from django.contrib.auth import hashers
from django.forms.models import model_to_dict
from django.shortcuts import render
from django.core.exceptions import ObjectDoesNotExist
from .models import *
from .forms import *
def _success(data_dict, model_name, code):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutSandwichCode in the Ruby Koans
#
from runner.koan import *
import re # For regular expression string comparisons
class AboutWithStatements(Koan):
def count_lines(self, file_name):
try:
f = open(file_name)
try:
... |
import os
import shutil
from itertools import chain
from optparse import make_option
from clint.textui import progress
from subsample.file_input import FileInput
from subsample.algorithms import two_pass_sample
from calaccess_raw.management.commands import CalAccessCommand
from calaccess_raw import get_download_directo... |
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.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.