content stringlengths 4 20k |
|---|
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._text import to_native
from ansible.module_utils.basic ... |
import hashlib
import os
import pytest
from Bootstrapper import BootstrapperPlugin
from Bootstrapper.BootstrapperDb import BootstrapperDb
from Peer import Peer
from Crypt import CryptRsa
from util import helper
@pytest.fixture()
def bootstrapper_db(request):
BootstrapperPlugin.db.close()
BootstrapperPlugin.... |
"""
Definition of a report.
"""
_reports = dict()
def register_plugin(report, report_type=None):
"""
Register the plugin class definition into the module.
:param report: report definition class. Must have a class variable of report_type.
:param report_type: the type of report being identified, if non... |
"""
Utility functions for Image transfer and manipulation.
"""
import os
import tarfile
from lxml import etree
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import encodeutils
from oslo_utils import strutils
from oslo_utils import units
from oslo_... |
from ..Qt import QtCore, QtGui, USE_PYSIDE, USE_PYQT5
from .. import exporters as exporters
from .. import functions as fn
from ..graphicsItems.ViewBox import ViewBox
from ..graphicsItems.PlotItem import PlotItem
if USE_PYSIDE:
from . import exportDialogTemplate_pyside as exportDialogTemplate
elif USE_PYQT5:
f... |
from werkzeug.datastructures import MultiDict
from udata.forms import ModelForm, fields
from udata.models import db
from udata.tests import TestCase
from udata.utils import faker
class Nested(db.Document):
name = db.StringField()
class Fake(db.Document):
name = db.StringField()
nested = db.ListField(db... |
#!/usr/bin/python
#
# Find a sequence of duk_hobject hash sizes which have a desired 'ratio'
# and are primes. Prime hash sizes ensure that all probe sequence values
# (less than hash size) are relatively prime to hash size, i.e. cover the
# entire hash. Prime data is packed into about 1 byte/prime using a
# pre... |
"""SGDR learning rate decay function."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops, control_flow_ops... |
"""Registry for layers and their parameters/variables.
This represents the collection of all layers in the approximate Fisher
information matrix to which a particular FisherBlock may belong. That is, we
might have several layer collections for one TF graph (if we have multiple K-FAC
optimizers being used, for example.... |
import xadmin
xadmin.autodiscover()
from django.conf.urls import include, url
from views import index,skin_config,Login,Logout,upload,exec_cmd,setting,web_terminal,download
from xadmin.plugins import xversion
xversion.register_models()
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^skin_conf... |
import datetime
import os
import warnings
from django import forms
from django.core import checks
from django.core.files.base import File
from django.core.files.images import ImageFile
from django.core.files.storage import default_storage
from django.db.models import signals
from django.db.models.fields import Field
f... |
import glob
import os
import re
import subprocess
import sys
import version_resolver as resolver
extra_os = ['mac', 'win']
def subprocessCall(args):
print args
return subprocess.call(args)
def subprocessCheckOutput(args):
print args
return subprocess.check_output(args)
class DEPSParser:
def __in... |
#!/usr/bin/env python
from os import getcwd
from os.path import basename
from os import environ
import json
from nunja.core import engine
from nunja.stock.model import fsnav
from nunja.stock.model.base import Definition
nav = fsnav.Base(
Definition(
'baseid',
basename(__file__) + '?{+path}',
... |
from __future__ import unicode_literals
import os
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.template.loader import select_template
from django.utils.translation import ugettext_lazy as _
from . import models
from .conf import settings
from filer.settings import FILER... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt impor... |
import nengo
import numpy as np
class Pendulum(object):
def __init__(self, mass=1.0, length=1.0, dt=0.001, g=10.0, seed=None,
max_torque=2, max_speed=8, limit=2.0):
self.mass = mass
self.length = length
self.dt = dt
self.g = g
self.max_torque = max_torque
... |
"""
Total Least Squares Figure
--------------------------
Figure 8.6
A linear fit to data with correlated errors in x and y. In the literature, this
is often referred to as total least squares or errors-in-variables fitting. The
left panel shows the lines of best fit; the right panel shows the likelihood
contours in s... |
import os
import re
import sys
import optparse
import volk_arch_defs
import volk_machine_defs
import volk_kernel_defs
from Cheetah import Template
def __escape_pre_processor(code):
out = list()
for line in code.splitlines():
m = re.match('^(\s*)#(\s*)(\w+)(.*)$', line)
if m:
p0, p1,... |
# -*- coding: utf-8 -*-
"""
This module is an implementation of the Gauss Seidel method
"""
def norm(vector_x):
"""
Module calculates the norm of a vector
Args:
vector_x (list): Vector
Returns:
Norm of a vector
"""
norm_v = sum([x ** 2 for x in vector_x]... |
# -*- coding: utf-8 -*-
"""
markupsafe
~~~~~~~~~~
Implements a Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
import string
from collections import Mapping
from markupsafe._compat import text_type, string_types, int_types, \
u... |
# -*- coding: utf-8 -*-
# This file is part of the Horus Project
__author__ = 'Jesús Arroyo Torrens <<EMAIL>>'
__copyright__ = 'Copyright (C) 2014-2016 Mundo Reader S.L.'
__license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html'
from horus.util import profile
from horus.gui.engine import dr... |
import sys
import spotipy
''' shows the albums and tracks for a given artist.
'''
def get_artist(name):
results = sp.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
return items[0]
else:
return None
def show_album_tracks(album):
tra... |
from stream_framework.activity import Activity
from stream_framework.storage.base import BaseActivityStorage, BaseTimelineStorage
from stream_framework.verbs.base import Love as PinVerb
from stream_framework.tests.utils import FakeActivity, Pin
from mock import patch
import datetime
import unittest
def implementation... |
# -*- coding: utf-8 -*-
"""
Impact
Impact resources used by the old Assessment module
"""
if deployment_settings.has_module("assess"):
# Impact as component of incident reports
s3mgr.model.add_component("impact_impact", irs_ireport="ireport_id")
def impact_tables():
""" Load the Impact... |
from django.conf import settings
from dojango.conf import settings as dojango_settings
from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
from django.utils._os import safe_join
from django.utils.encoding import force_str
from django.views.static import serve
from os import path, li... |
import numpy as np
import matplotlib.pyplot as plt
def LineFitWt(x, y, sig):
"""
Returns slope and y-intercept of weighted linear fit to
(x,y) data set.
Inputs: x and y data array and uncertainty array (unc)
for y data set.
Outputs: slope and y-intercept of best fit to data and
... |
# coding: utf-8
""" Utilities for nonlinear dynamics """
from __future__ import division, print_function
__author__ = "adrn <<EMAIL>>"
# Standard library
import logging
# Third-party
import numpy as np
# Project
from ..util import gram_schmidt
__all__ = ['lyapunov_spectrum', 'fast_lyapunov_max', 'lyapunov_max']
... |
import torch
import torch.nn as nn
from torch.autograd import Variable
try:
from cv2 import cv2
except:
import cv2
import VideoClassification.Config.Config as Config
from VideoClassification.model.resnet_twostream.resnet_twostream import resnet152_TemporalNet,resnet101_TemporalNet
from VideoClassification.uti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from pkgutil import walk_packages
import cumulusci
def find_packages(path='.', prefix=""):
yield prefix
prefix = prefix + "."
for _, name, ispkg in walk_packages(path, prefix):
if ispkg:
yield name
with open('... |
#!/usr/bin/env python
import socket
import struct
import time
import select
import screen
import signal
import sys
NR_CHANNELS = 4
visibleMs = 200
selectMs = 60
# Each queue element is tuple with ( time-to-vanish, channel-id, bin-id )
queue = []
bind_port = ( '127.0.0.1', 3000 )
interrupted = False
# Control+C ... |
"""Tests for osf.utils.manager.IncludeQueryset"""
import pytest
from framework.auth import Auth
from osf.models import Node
from osf_tests.factories import ProjectFactory, NodeFactory, UserFactory
pytestmark = pytest.mark.django_db
@pytest.fixture()
def create_n_nodes():
def _create_n_nodes(n, roots=True):
... |
"""
Contains the BaseManager which must be
implemented fully in regards to the persistence
mechanism you are using.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from ripo... |
from rest_framework.renderers import JSONRenderer
from api.publisher.serializers import PublisherSerializer
from solr.indexing import BaseIndexing
from solr.utils import get_child_attr, value_string
class DatasetIndexing(BaseIndexing):
def dataset_publisher(self):
publisher = get_child_attr(self.record,... |
# Test mock_tk.Text class against tkinter.Text class by running same tests with both.
import unittest
from test.support import requires
from _tkinter import TclError
import tkinter as tk
class TextTest(object):
hw = 'hello\nworld' # usual initial insert after initialization
hwn = hw+'\n' # \n present at in... |
'''expand expressions into changelog and summaries
This extension allows the use of a special syntax in summaries, which
will be automatically expanded into links or any other arbitrary
expression, much like InterWiki does.
A few example patterns (link to bug tracking, etc.) that may be used
in your hgrc::
[interh... |
from neutron.api import extensions
from neutron.api.v2 import attributes
from neutron.api.v2 import base
from neutron.db import servicetype_db
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
RESOURCE_NAME = "service_provider"
COLLECTION_NAME = "%ss" % RESOURCE_NAME
SERVICE_ATTR =... |
"""Additional `SessionRunHook` implementations to complement those in
tensorflow/python/training.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import timel... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import re
from calibre im... |
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import weakref
import sip
... |
import numbers
from telemetry import value as value_module
from telemetry.value import list_of_scalar_values
class ScalarValue(value_module.Value):
def __init__(self, page, name, units, value, important=True):
"""A single value (float or integer) result from a test.
A test that counts the number of DOM ele... |
import unittest
from win32com.client.gencache import EnsureDispatch
from win32com.client.dynamic import DumbDispatch
import win32com.test.util
class RegexTest(win32com.test.util.TestCase):
def _CheckMatches(self, match, expected):
found = []
for imatch in match:
found.append(imatch.Firs... |
"""
(c) 2013 LinkedIn Corp. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");?you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing... |
import models
import wizard |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import librosa
import numpy
import scipy
def feature_extraction_lfcc(audio_filename_with_path, statistics=True):
print audio_filename_with_path
with open(audio_filename_with_path,'r') as f:
feature_matrix = numpy.loadtxt(f)
#f.close()
# Collect into data... |
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. F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j. F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.... |
from __future__ import print_function, absolute_import
import time
import sys
import argparse
from faker import Faker
import itertools
from random import choice
from modularodm import Q
from framework.auth import Auth
from website.app import init_app
from website import models, security
from tests.factories import N... |
"""
This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`,
the reStructuredText parser.
Usage
=====
1. Create a parser::
parser = docutils.parsers.rst.Parser()
Several optional arguments may be passed to modify the parser's behavior.
Please see `Customizing the Parser`_ below f... |
import pytest
from ansible.module_utils.database import (
pg_quote_identifier,
SQLParseError,
)
# These are all valid strings
# The results are based on interpreting the identifier as a table name
VALID = {
# User quoted
'"public.table"': '"public.table"',
'"public"."table"': '"public"."table"',
... |
try:
import boto.ec2
import boto.vpc
from boto.exception import EC2ResponseError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
if __name__ != '__main__':
raise
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import AnsibleAWSError, connect_to_aw... |
"""
Nose test running.
This module implements ``test()`` and ``bench()`` functions for NumPy modules.
"""
import os
import sys
def get_package_name(filepath):
"""
Given a path where a package is installed, determine its name.
Parameters
----------
filepath : str
Path to a file. If the de... |
import sys
import os
import unittest
import cStringIO
import warnings
import re
try:
import json
except ImportError:
import simplejson as json
from support import html5lib_test_files
from html5lib.tokenizer import HTMLTokenizer
from html5lib import constants
class TokenizerTestParser(object):
def __init_... |
__version__=''' $Id '''
__doc__="""Routines to print code page (character set) drawings. Predates unicode.
To be sure we can accurately represent characters in various encodings
and fonts, we need some routines to display all those characters.
These are defined herein. The idea is to include flowable, drawable
and gr... |
"""
Django settings for plants project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... |
from . import wizard
from . import report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import re
import uuid
import six
from django.test import TestCase
from django_extensions.db.fields import PostgreSQLUUIDField
from .testapp.models import (
UUIDTestAgregateModel, UUIDTestManyToManyModel, UUIDTestModel_field,
UUIDTestModel_pk,
)
class UUIDFieldTest(TestCase):
def test_UUID_field_create(... |
import volatility.timefmt as timefmt
import volatility.obj as obj
import volatility.utils as utils
import volatility.commands as commands
#pylint: disable-msg=C0111
class DateTime(commands.Command):
"""A simple example plugin that gets the date/time information from a Windows image"""
def calculate(self):
... |
import math
import re
# units
from pint import UnitRegistry
units = UnitRegistry()
# my guess as to why 508 is the magic number is the motor steps and the belt TPI
# i am guessing the belt is 2.54 TPI, and the motor can provide 200 steps
# 2.54 * 200 = 508
units.define('steps = inch / 508.0 = step')
# For SVG files,... |
import sys
import optparse
from django_manage_commands_provider import _xml
class Option:
def __init__(self):
self.long = []
self.short = []
self.arg = None
self.help = None
def dump(self, dumper):
dumper.add_command_option(self.long, self.short, self.help, self.arg)
... |
from django.test import TestCase
from django.test.utils import override_settings
from readthedocs.projects.models import Project
from django.core.urlresolvers import reverse
from readthedocs.redirects.utils import redirect_filename
class RedirectFilenameTests(TestCase):
fixtures = ["eric", "test_data"]
def ... |
import datetime
import time
from oslo.config import cfg
from quantum.openstack.common.gettextutils import _
from quantum.openstack.common import log as logging
from quantum.openstack.common import timeutils
periodic_opts = [
cfg.BoolOpt('run_external_periodic_tasks',
default=True,
... |
"""
Created on Fri Aug 1 15:24:25 2014
@author: thierry
"""
class Switchport():
"""@brief Switchport definition and features
@param interface : interface name
@param active : True or False
@param description
@param vlan : number of the VLAN, native VLAN if mode trunk for Cisco
@param mod... |
import time
import json
class DarkSkyTest:
def __init__(self):
with open('config.json', 'r') as f:
self.config = json.load(f)
self.pixel = {}
def lightningStrobe(self, red, green, blue):
# Wipe white across display a pixel at a time very quickly
list = [5, 20, 3,... |
"""
.. dialect:: mysql+pymysql
:name: PyMySQL
:dbapi: pymysql
:connectstring: mysql+pymysql://<username>:<password>@<host>/<dbname>\
[?<options>]
:url: http://www.pymysql.org/
Unicode
-------
Please see :ref:`mysql_unicode` for current recommendations on unicode
handling.
MySQL-Python Compatibility
... |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
""" sample code for demonstrating shapely functionality """
import shapely
import shapely.wkt
import os
import sys
from osgeo import ogr
if len(sys.argv) < 2:
print "Usage: {} <shp_file> [buffer_distance]".format(sys.argv[0])
exit(1)
shapename = sys.argv[1]
shapefil... |
#!/usr/bin/env python
#
# Generated Mon May 2 14:23:33 2011 by parse_xsd.py version 0.4.
#
import saml2
from saml2 import SamlBase
from saml2 import md
NAMESPACE = 'urn:oasis:names:tc:SAML:metadata:ui'
class DisplayName(md.LocalizedNameType_):
"""The urn:oasis:names:tc:SAML:metadata:ui:DisplayName element ""... |
import unittest
from datetime import date, timedelta
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.test import TestCase
from django.utils.six import PY3
class TokenGeneratorTest(TestCase):
def test_make... |
import logging
from django.contrib.auth.models import User
from django.db import models
log = logging.getLogger(__name__)
class CourseUserGroup(models.Model):
"""
This model represents groups of users in a course. Groups may have different types,
which may be treated specially. For example, a user can... |
# Test case for property
# more tests are in test_descr
import sys
import unittest
class PropertyBase(Exception):
pass
class PropertyGet(PropertyBase):
pass
class PropertySet(PropertyBase):
pass
class PropertyDel(PropertyBase):
pass
class BaseClass(object):
def __init__(self):
self._sp... |
#!/usr/bin/env python
'''Test an unformatted document is editable.
Examine and type over the text in the window that appears. The window
contents can be scrolled with the mouse wheel.
Press ESC to exit the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: STYLE.py 1754 2008-02-10 13:26:52Z Alex.Holk... |
from __future__ import absolute_import, division, print_function
import math
from cryptography import utils
from cryptography.exceptions import (
InvalidSignature, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.openssl.utils import (
_calculate_digest_and_algorithm, _check_not_prehashed,
... |
import django_filters
from .models import Source, Change
from rest_framework import viewsets, mixins, generics, filters
from rest_framework.permissions import IsAuthenticated
from .serializers import ChangeSerializer
class ChangePost(mixins.CreateModelMixin, generics.GenericAPIView):
permission_classes = (IsAuthe... |
from __future__ import division, absolute_import, print_function
import sys
import os
import shutil
from tempfile import NamedTemporaryFile, TemporaryFile, mktemp, mkdtemp
from numpy import memmap
from numpy import arange, allclose, asarray
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_e... |
"""Support for raspihats board binary sensors."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.const import (
CONF_ADDRESS, CONF_DEVICE_CLASS, CONF_NAME, DEVICE_DEFAULT_NAME)
import homeassistant.helpers.co... |
"""A collection of Unity-specific emulators."""
from time import sleep
from autopilot.introspection import (
get_proxy_object_for_existing_process,
ProcessSearchError
)
from autopilot.introspection.dbus import CustomEmulatorBase
from autopilot.introspection.backends import DBusAddress
from dbus import DB... |
import os
from xdg import BaseDirectory
class SnapcraftCache:
"""Generic cache base class.
This class is responsible for cache location, notification and pruning.
"""
def __init__(self):
self.cache_root = os.path.join(
BaseDirectory.xdg_cache_home, 'snapcraft')
def cache(sel... |
"""Special separate FFI module for keyboard constants.
These are enums that take many long seconds to build and they don't change at
all, so having them in a separate FFI unit makes startup faster when we've
changed the cdef and have to rebuild.
"""
import cffi
ffi = cffi.FFI()
ffi.cdef("""
typedef enum {
SDLK_... |
# -*- coding: utf-8 -*-
from prettyPrint import *
from sqlite3 import *
from os import listdir,system
class DB:
def __init__(self):
self.db = 'db/nss.db'
self.plugin = 'plugins'
self.mongodb = 'mongodb'
self.multi = 'multi'
self.sep = "/"
def initDB(self):
... |
# -*- coding: utf-8 -*-
from . import QueryRequest
import json
class TextRequest(QueryRequest):
"""
TextRequest request class
Send simple text queries.
Query can be string or array of strings.
"""
@property
def query(self):
"""
Query parameter, can be st... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
onesidebuffer.py
---------------------
Date : Janaury 2015
Copyright : (C) 2015 by Giovanni Manghi
Email : giovanni dot manghi at naturalgis dot pt
*****... |
# -*- coding: utf-8 -*-
"""
sphinx.ext.ifconfig
~~~~~~~~~~~~~~~~~~~
Provides the ``ifconfig`` directive that allows to write documentation
that is included depending on configuration variables.
Usage::
.. ifconfig:: releaselevel in ('alpha', 'beta', 'rc')
This stuff is only in... |
"""
A script to analyze applomics data.
author: <EMAIL>
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df1 = pd.read_csv('../input/apple_inoculation_expt_160508.csv')
# count colonies adjusted for dilution and volume plated
df1['cfu_per_apple'] = df1.colonies * \
... |
import json
from zope import interface
from twisted.python import usage, filepath
from twisted.internet import reactor, endpoints
from twisted.cred import portal, checkers
from twisted.web import guard, resource, server
from twisted.application import internet
import klein
class Outline(object):
app = klein.Kl... |
import base_report_designer_modify
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#!/usr/bin/env python3
import json
import os
from wsgiref.handlers import CGIHandler
from philologic.runtime.DB import DB
from philologic.runtime.Query import get_expanded_query
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import WebConfig
except ImportError:
from phi... |
"""Defer to run_test_cases.py."""
import os
import optparse
import sys
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def pop_known_arguments(args):
"""Extracts known arguments from the args if present."""
rest = []
run_test_cases_extra_args = []
for arg in args... |
#!/usr/bin/env python
import sys
from gzip import open
from pysam import Fastafile
from collections import defaultdict as dd
def usage():
return "usage: %s <reference genome fasta> <refGenes.txt.gz>" % sys.argv[0]
if len(sys.argv) == 3:
fa = Fastafile(sys.argv[1])
assert sys.argv[2].endswith('.gz'),... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from temba.msgs.models import Msg, HANDLED, IVR
from temba.orgs.models import Org
from temba.flows.models import FlowStep, ActionSet, SayAction
from django.conf import settings
class Migration(migrations.Migratio... |
""" Test refcounting and behavior of SCXX.
"""
from __future__ import absolute_import, print_function
import sys
from numpy.testing import (TestCase, dec, assert_, assert_raises,
run_module_suite)
from scipy.weave import inline_tools
class TestDictConstruct(TestCase):
#--------------... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Not installing aliases from python-future; it's unreliable and slow.
from builtins import * # noqa
from mock import patch
from hamcrest import ( any_of, assert_that, c... |
"""Tests the graph freezing tool."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import os
from tensorflow.examples.image_retraining import label_image
from tensorflow.examples.image_retraining import retrain
from tensorflow.pyth... |
"""A module providing a function for serializing JSON values with Infinity.
Python provides no way to override how json.dumps serializes
Infinity/-Infinity/NaN; if allow_nan is true, it encodes them as
Infinity/-Infinity/NaN, in violation of the JSON spec and in violation of what
JSON.parse accepts. If it's false, it ... |
#!/usr/bin/env python
import argparse
from bokeh.server.websocket import make_app
import logging
def build_parser():
parser = argparse.ArgumentParser(description="start bokeh websocket")
parser.add_argument("--url-prefix",
help="url prefix",
type=str,
... |
#!/usr/bin/env python
import json
def pretty_json(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ':'))
def twitter_small_relation_key():
relation_key = {
"userName" : "chushumo",
"programName" : "multiway_join",
"relationName" : "twitter_small"
}
retur... |
# META: timeout=long
import pytest
import time
from tests.actions.support.keys import ALL_EVENTS, Keys
from tests.actions.support.refine import filter_dict, get_keys, get_events
@pytest.mark.parametrize("name,expected", ALL_EVENTS.items())
def test_webdriver_special_key_sends_keydown(session,
... |
# Python program to print transitive closure of a graph
# Part of Cosmos by OpenGenus Foundation
from collections import defaultdict
# This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self,vertices):
# No. of vertices
self.V= vertices
... |
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use... |
import re
import os
import sys
import socket
try:
import IDF
except ImportError:
# this is a test case write with tiny-test-fw.
# to run test cases outside tiny-test-fw,
# we need to set environment variable `TEST_FW_PATH`,
# then get and insert `TEST_FW_PATH` to sys path before import FW module
... |
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
from random import *
import server
class Combat(server.Task):
"""A very simple combat system example."""
def attack_operation(self, op):
""" The attack op is FROM the the character that initiated com... |
# Offers example of inline C for binary search algorithm.
# Borrowed from Kalle Svensson in the Python Cookbook.
# The results are nearly in the "not worth it" catagory.
#
# C:\home\ej\wrk\scipy\compiler\examples>python binary_search.py
# Binary search for 3000 items in 100000 length list of integers:
# speed in pytho... |
from django.core.urlresolvers import (RegexURLPattern,
RegexURLResolver, LocaleRegexURLResolver)
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.utils import six
__all__ = ['handler403', 'handler404', 'handler500', 'include', 'patterns', 'url']
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.