content stringlengths 4 20k |
|---|
"""Initialize tensor_forest/hybrid/python."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensor_forest.hybrid.python import layers
from tensorflow.contrib.tensor_forest.hybrid.python import models
from tensorflow.contrib.tensor_f... |
import model
import message
import wizard |
"""Tests server responding with RESOURCE_EXHAUSTED."""
import threading
import unittest
import logging
import grpc
from grpc import _channel
from grpc.framework.foundation import logging_pool
from tests.unit import test_common
from tests.unit.framework.common import test_constants
_REQUEST = b'\x00\x00\x00'
_RESPON... |
from numpy import vectorize
from numpy.random import random_sample
__all__ = ['randwppf', 'randwcdf']
# XXX: Are these needed anymore?
#####################################
# General purpose continuous
######################################
def randwppf(ppf, args=(), size=None):
"""returns an array of randomly ... |
from card import card
from globals import *
class missile(card):
def __init__(self, max_payload=10, name="missile"):
self.max_payload = max_payload
self.__name = name
def __str__(self):
if self.__name == "missile":
return "missile(%u)"%self.max_payload
else:
return self.__name
def __repr__(self):
... |
from cStringIO import StringIO
from textwrap import dedent
from tempfile import NamedTemporaryFile
import json
import sys
import unittest
from cfn_pyplates import cli
try:
from mock import patch
mock_error = None
except ImportError:
patch = None
mock_error = 'skipped -- install mock to run this test'
... |
try:
import re
import os
import sys
import tempfile
import subprocess
from lib.core.exceptions import CrowbarExceptions
except Exception, err:
from lib.core.exceptions import CrowbarExceptions
raise CrowbarExceptions(str(err))
class Nmap:
def __init__(self):
self.nmap_path = "/usr/bi... |
""" Patch utility to apply unified diffs
Brute-force line-by-line non-recursive parsing
Copyright (c) 2008-2010 anatoly techtonik
Available under the terms of MIT license
Project home: http://code.google.com/p/python-patch/
$Id$
$HeadURL$
"""
__author__ = "techtonik.rainforce.org"
__versi... |
"""
Implement the Schwartizan Transform method of sorting
a list by an arbitrary metric (see the Python FAQ section
4.51).
--------------------------------------------------------------------
This program is licensed under the GNU General Public License (GPL).
See http://www.fsf.org for details of the license.
Andrew... |
#coding:utf-8
import os
import logging
import tempfile
import shutil
from cactus.compat.paths import StaticCompatibilityLayer
from cactus.utils.file import calculate_file_checksum, file_changed_hash
from cactus.utils.filesystem import alt_file, mkdtemp
from cactus.utils.url import ResourceURLHelperMixin
logger = log... |
__all__ = ['BuildInstructions']
from typing import Optional, Dict, Any
from pprint import pprint as pp
import warnings
import os
import shutil
import json
import attr
import docker
import yaml
def converter_args(args: Dict[str, Any]) -> Dict[str, str]:
return {k: str(v) for (k, v) in args.items()}
@attr.s(fro... |
__RCSID__ = "$Id$"
import socket
import select
import time
import os
from DIRAC.Core.DISET.private.Transports.BaseTransport import BaseTransport
from DIRAC.FrameworkSystem.Client.Logger import gLogger
from DIRAC.Core.Utilities.ReturnValues import S_ERROR, S_OK
class PlainTransport( BaseTransport ):
def initAsClien... |
"""
error_tracker: A hook for tracking errors in loading XBlocks.
Used for example to get a list of all non-fatal problems on course
load, and display them to the user.
Patterns for using the error handler:
try:
x = access_some_resource()
check_some_format(x)
except SomeProblem as err:
... |
# -*- coding: utf-8 -*-
SURVEY_DAYS = 30
ROLES = {}
# FIXME: VERIFY CONSTANTS AGAINST V4 TEXTIT
ROLES[1] = 'Contractor'
ROLES[2] = 'Architect/Engineer'
ROLES[3] = 'Permit Consultant'
ROLES[4] = 'Homeowner'
ROLES[5] = 'Business Owner'
ROLES['Contractor'] = 1
ROLES['Contratista'] = 1
ROLES['Architect/Engineer'] = 2
ROL... |
import subprocess
import os
from ansible.plugins.callback import CallbackBase
FAILED_VOICE="Zarvox"
REGULAR_VOICE="Trinoids"
HAPPY_VOICE="Cellos"
LASER_VOICE="Princess"
SAY_CMD="/usr/bin/say"
class CallbackModule(CallbackBase):
"""
makes Ansible much more exciting on OS X.
"""
CALLBACK_VERSION = 2.0
... |
import os
try:
from debops import *
from debops.cmds import *
except ImportError:
pass
try:
from ansible.plugins.lookup import LookupBase
except ImportError:
LookupBase = object
from distutils.version import LooseVersion
from ansible import __version__ as __ansible_version__
'''
This file imple... |
if __name__ == "__main__":
import sys
import Ice
import omero
import omero.clients
import omero.tables
from omero.util import Dependency
# Logging hack
omero.tables.TablesI.__module__ = "omero.tables"
omero.tables.TableI.__module__ = "omero.tables"
class TablesDependency(Depe... |
import unittest
import sys
import pytest
try:
import Crypto
Crypto
crypto = True
except ImportError:
crypto = False
from libcloud.common.types import InvalidCredsError
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import xmlrpclib
from libcloud.utils.py3 import next
from libcloud.com... |
from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
from cms import api
from cms.exceptions import ToolbarAlreadyRegistered, ToolbarNotRegistered
from cms.test_utils.testcases import CMSTestCase
from cms.toolbar_base import CMSToolbar
from cms.toolbar_pool import ... |
"""
Nose test running.
This module implements ``test()`` and ``bench()`` functions for NumPy modules.
"""
from __future__ import division, absolute_import, print_function
import os
import sys
import warnings
from numpy.compat import basestring
import numpy as np
from .utils import import_nose, suppress_warnings
d... |
from sys import argv
from sys import stdout
from sys import stderr
import logging
from argparse import ArgumentParser
parser = ArgumentParser("Sorting Particles by the halo label",
description=
""" Sorting particles by the Halo Label.
Particles not in any halo is put to the end. The first halo
... |
import argparse
import botutil
import json
import os
import subprocess
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('adb_path', help='Path to adb command')
parser.add_argument('agi_dir', help='Path to AGI build')
parser.add_argument('out_dir', help='Path to output dire... |
""" Fantasm: A taskqueue-based Finite State Machine for App Engine Python
Docs and examples: http://code.google.com/p/fantasm/
Copyright 2010 VendAsta Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may ob... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import io
import os
import re
import types
from datetime import datetime, timedelta
from unittest import TestCase
from django.core.exceptions import ValidationError
from django.core.validators import (
BaseValidator, DecimalValidator, EmailValidator,... |
""" Coordinate transformations.
"""
import numpy
def cartesian_to_spherical_rho(x, y, z):
""" Calculates the magnitude in spherical coordinates from Cartesian
coordinates.
Parameters
----------
x : {numpy.array, float}
X-coordinate.
y : {numpy.array, float}
Y-coordinate.
z... |
import logbook
from opbeat.handlers.logbook import OpbeatHandler
from tests.helpers import get_tempstoreclient
from tests.utils.compat import TestCase
class LogbookHandlerTest(TestCase):
def setUp(self):
self.logger = logbook.Logger(__name__)
def test_logger(self):
client = get_tempstoreclie... |
# (C) 2012-2017 Arntraud Bacher
# Institut für Ionenphysik und Angewandte Physik
# Universitaet Innsbruck
import numpy as np
import json
import os
def readElements(iniData):
# Falls die Dateien mit Monomer und Core Ion nicht existieren, werden leere
# Listen zurückgegeben
coreIonFile = iniData['Paths'].ge... |
"""Tests for Keras metrics functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.keras.python import keras
from tensorflow.python.platform import test
class KerasMetricsTest(test.TestCase):
def test_m... |
#coding: utf-8
import numpy as np
import cPickle
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from autoencoder import Autoencoder, load_data
import matplotlib.pyplot as plt
if __name__ == "__main__":
# テストに使うデータミニバッチ
x = T.matrix('x')
# ファイルから学習したパラメ... |
from template import Template
from template.test import TestCase, main
class Foo:
def __init__(self, **kwargs):
self.__dict = kwargs
def present(self, view):
return "{ %s }" % ", ".join(
"%s => %s" % item for item in sorted(self.__dict.items()))
def reverse(self, view):
return "{ %s }" % ", ... |
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.test import TestCase
from . import ValidationTestCase
from .models import (Author, Article, ModelToValidate,
GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest)
class BaseModelV... |
# coding=utf-8
"""
The function of MountStatsCollector is to parse the detailed per-mount NFS
performance statistics provided by `/proc/self/mountstats` (reads, writes,
remote procedure call count/latency, etc.) and provide counters to Diamond.
Filesystems may be included/excluded using a regular expression filter,
lik... |
"""Thread-local objects.
(Note that this module provides a Python version of the threading.local
class. Depending on the version of Python you're using, there may be a
faster one available. You should always import the `local` class from
`threading`.)
Thread-local objects support the management of thread-... |
from StringIO import StringIO
from geraldo.generators import PDFGenerator
from pysped.nfe.danfe.danferetrato import DANFERetrato
from pysped.nfe.leiaute import ProtNFe_310, RetCancNFe_200, ProcCancNFe_200
from pysped.nfe.leiaute import ProcEventoCancNFe_100
class DANFE(object):
def __init__(self):
self.im... |
import os
import subprocess
from ..utils import RepoStats, ThreadedSegment
def get_PATH():
"""Normally gets the PATH from the OS. This function exists to enable
easily mocking the PATH in tests.
"""
return os.getenv("PATH")
def hg_subprocess_env():
return {"PATH": get_PATH()}
def _get_hg_branc... |
from __future__ import unicode_literals
import logging
import os
import re
from sorl.thumbnail.compat import string_type, text_type
from sorl.thumbnail.conf import settings, defaults as default_settings
from sorl.thumbnail.helpers import tokey, serialize
from sorl.thumbnail.images import ImageFile, DummyImageFile
fro... |
import os
import unittest
from mantid.api import AnalysisDataService
from mantid.kernel import config, ConfigService
from mantid.simpleapi import (CreateSampleWorkspace, MaskDetectors, DeleteWorkspace, LoadNexusProcessed, Load, Rebin)
from sans.algorithm_detail.calculate_transmission_helper import (get_masked_det_ids,... |
import datetime
import logging
import time
import cv2
import imutils
import requests
from imutils.video import WebcamVideoStream
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("MotionTracker")
def build_json_payload(flag):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
... |
"""abydos.distance._positional_q_gram_jaccard.
Positional Q-Gram Jaccard coefficient
"""
from collections import defaultdict
from typing import Any, DefaultDict, List, Optional
from ._distance import _Distance
from ..tokenizer import QGrams, WhitespaceTokenizer, _Tokenizer
__all__ = ['PositionalQGramJaccard']
cla... |
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.test import TestCase
from nodeshot.core.base.tests import user_fixtures
from nodeshot.networking.net.models import Interface
from ..models import Link, Topology
from ..models.choices import LINK_STATUS, LINK_TY... |
from __future__ import print_function
import unittest as ut
import espressomd
import numpy as np
@ut.skipIf(not espressomd.has_features(['EXCLUSIONS']), "Skipping test")
class Exclusions(ut.TestCase):
s = espressomd.System(box_l=[1.0, 1.0, 1.0])
s.seed = s.cell_system.get_state()['n_nodes'] * [1234]
def ... |
import shutil
import glob
import os
import fnmatch
import sys
# pack description format: [root_mask, file_name_mask, file_path_exclusion_mask]
# pack will contain
# all files under (and including) the expansion of root_mask,
# whose names match file_name_mask,
# whose full path (with root_mask) does not match ... |
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime
from textwrap import dedent
DEFAULT_DATE = datetime(2016, 1, 1)
args = {
'owner': 'airflow',
'start_date': DEFAULT_DATE,
}
dag = DAG(dag_id='test_default_impersonation', default_args=args)
... |
from sqlalchemy.dialects.postgresql import UUID, ENUM
from sqlalchemy.orm import relationship, backref
from sqlalchemy import *
from decaf_storage.database import Base
from scenario_net import ScenarioNet
from scenario_instance import ScenarioInstance
from decaf_storage.utils import StdObject
__author__ = ''
class ... |
rows = 6
row_rule_len = 6
row_rules = [
[0, 0, 0, 2, 2, 3],
[1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 3],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 2, 2, 1]]
cols = 14
col_rule_len = 3
col_rules = [
[0, 0, 4],
[0, 1, 1],
[0, 1, 1],
[0, 1, 1],
[0, 0, 0],
[0, 1, 1],
... |
import json
from django import forms
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ImproperlyConfigured, PermissionDenied, ValidationError
from django.http import Http404, HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse
from django.shortcuts impor... |
"""
Helper for looping over sequences, particular in templates.
Often in a loop in a template it's handy to know what's next up,
previously up, if this is the first or last item in the sequence, etc.
These can be awkward to manage in a normal Python loop, but using the
looper you can get a better sense of the context.... |
"""GCS file system configuration for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from tensorflow.contrib.cloud.python.ops import gen_gcs_config_ops
from tensorflow.python.framework import dtypes
from tensorflow.python.framewo... |
#!/usr/bin/env python3
import json
import os
import random
import argparse
def getlink(file):
if os.path.islink(file):
path = os.path.dirname(os.readlink(file))
else:
path = os.path.dirname(file)
return os.path.dirname(path)
def quote():
abspath = getlink(__file__)
if os.name ... |
"""
DataFrame-based machine learning APIs to let users quickly assemble and configure practical
machine learning pipelines.
"""
from pyspark.ml.base import Estimator, Model, Transformer, UnaryTransformer
from pyspark.ml.pipeline import Pipeline, PipelineModel
__all__ = ["Transformer", "UnaryTransformer", "Estimator", ... |
from django.template import TemplateSyntaxError, TemplateDoesNotExist, Variable
from django.template import Library, Node, TextNode
from django.template.loader import get_template
from django.conf import settings
from django.utils.safestring import mark_safe
register = Library()
BLOCK_CONTEXT_KEY = 'block_context'
c... |
import logging
import time
from openerp import models, api, fields, exceptions
from openerp.tools.translate import _
from res_partner import PAYMENT_TYPES
from tools import _get_exception_message
_logger = logging.getLogger(__package__)
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
_grou... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDeletingObjects(Koan):
def test_del_can_remove_slices(self):
lottery_nums = [4, 8, 15, 16, 23, 42]
del lottery_nums[1]
del lottery_nums[2:4]
self.assertEqual(___, lottery_nums)
def test_del_can... |
import os
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def start_processes(remote, *processes):
for proc in processes:
if proc == "namenode":
remote.execute_command("sudo service hadoop-hdfs-namenode start")
elif proc == "datanode":
remote.execute... |
"""Helper classes for computing scores."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import six
from six.moves import range
def _ToUnicode(line):
return six.ensure_text(line, 'utf-8')
def _Tokenize(string):
retur... |
from shapely.geometry import LineString
from shapely.geometry import Point
class ObstacleDecider:
def __init__(self):
self.obstacle_lat_ttc = {}
self.obstacle_lon_ttc = {}
self.obstacle_lat_dist = {}
self.obstacle_lon_dist = {}
self.front_edge_to_center = 3.89
self.... |
config = {
# environment this app is running on: localhost, testing, production
'environment': "production",
# webapp2 sessions
'webapp2_extras.sessions' : {'secret_key': 'Rgs5tJE$5n6jsfrg'},
# webapp2 authentication
'webapp2_extras.auth' : {'user_model': 'boilerplate.models.User',
'cookie_n... |
"""
Connection utilities
"""
import base64
import paramiko
import os
import logging
from ..config import config
from ..contextutil import safe_while
log = logging.getLogger(__name__)
def split_user(user_at_host):
"""
break apart user@host fields into user and host.
"""
try:
user, host = user... |
import sys
from anki.hooks import runHook
from aqt.qt import *
from aqt.utils import openLink
from anki.utils import isMac, isWin
import anki.js
# Bridge for Qt<->JS
##########################################################################
class Bridge(QObject):
@pyqtSlot(str, result=str)
def run(self, str):... |
from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
from airflow.utils.db import provide_session
from airflow.utils.state import State
class DagrunRunningDep(BaseTIDep):
NAME = "Dagrun Running"
IGNOREABLE = True
@provide_session
def _get_dep_statuses(self, ti, session, dep_context):
dag = ... |
from importlib import import_module
import warnings
from django.core.urlresolvers import (RegexURLPattern,
RegexURLResolver, LocaleRegexURLResolver)
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils.deprecation import RemovedInDjango110Warning
__all__ = ['hand... |
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def rax_facts(module, address, name, server_id):
changed = False
cs = pyrax.cloudservers
if cs is None:
module.fail_json(msg='Failed to instantiate client. This '
'typically indicate... |
from gobjcreator2.metadef.types import Type
from gobjcreator2.metadef.package import PackageElement
class GType(PackageElement, Type):
def __init__(self, name, package=None, is_external=False):
PackageElement.__init__(self, name, package, is_external)
Type.__init__(self)
def get_name... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_iis_webapplication
version_added: "2.0"
short_description: Configures IIS web applications
description:
- Creates, removes, and configures IIS ... |
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder
# **************************** read test data ****************************************
df_train_data = pd.read_csv('C:\\Users\\fuxt2\\Documents\\code\\python\\house_price\\data\\tr... |
from invenio.dbquery import run_sql
from operator import itemgetter
from itertools import groupby
from msgpack import packb as serialize
depends_on = ['invenio_release_1_1_0']
def info():
return "Introduces aidPERSONIDDATA datablob column"
def do_upgrade():
column_exists = run_sql("SHOW COLUMNS FROM `aidPERS... |
from taiga.base import filters
from taiga.base import response
from taiga.base.api import ModelCrudViewSet
from taiga.base.api import ModelListViewSet
from taiga.base.decorators import detail_route
from . import models
from . import serializers
from . import permissions
from . import tasks
class WebhookViewSet(Mode... |
"""This module contains acceptance tests of scripts that bring up dockerized
test environment.
"""
__author__ = "Jakub Kudzia"
__copyright__ = "Copyright (C) 2016 ACK CYFRONET AGH"
__license__ = "This software is released under the MIT license cited in " \
"LICENSE.txt"
from tests import *
from tests.uti... |
from functools import partial
from unittest import TestCase
from mock import Mock, MagicMock, patch
from cloudshell.cp.openstack.domain.services.waiters.instance import InstanceWaiter
from cloudshell.cp.openstack.models.exceptions import InstanceErrorStateException
class TestTaskWaiterService(TestCase):
def set... |
from __future__ import absolute_import
from django.db import connection
from django.db.models import Q
from django.contrib.gis.geos import GEOSGeometry, LineString
from django.contrib.gis.measure import D # alias for Distance
from django.contrib.gis.tests.utils import oracle, postgis, spatialite, no_oracle, no_spatial... |
"""Implements a state space model with level and local linear trends."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import state_space_model
from tensorflow.python.framework impor... |
"""Methods to allow dict of numpy arrays."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from tensorflow.python.estimator.inputs.queues import feeding_functions
# Key name to pack the target into dict of `features`. See
# `_get_uniqu... |
#
# A VCR index.
#
import os
import string
error='VcrIndex.error'
VERSION_STRING='#!VcrIndex 1.1\n'
PREV_VERSION_STRING='#!VcrIndex 1.0\n'
class VcrIndex:
def __init__(self, name):
self.curmovie = None
self.curscene = None
self.modified = 0
self.filename = name
self.basename = os.path.basename(name)
self... |
import copy
import eventlet
from heat_integrationtests.common import test
from heat_integrationtests.functional import functional_base
template = {
'heat_template_version': 'pike',
'resources': {
'test1': {
'type': 'OS::Heat::TestResource',
'properties': {
'val... |
from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any... |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:8332")
else:
access = Ser... |
import orange
############ THIS IS WHAT YOU CAN DO WITH DISCRETE ATTRIBUTES
data = orange.ExampleTable("lenses")
############ THIS IS WHAT YOU CAN DO WITH DISCRETE ATTRIBUTES
print "\nYoung or presbyopic with astigmatism"
fya = orange.Filter_values(domain = data.domain)
fya["age"] = "young"
print "\nYoung examples... |
"""Gradients for operators defined in data_flow_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import dtypes
from tensorflow.python.framework impo... |
import click, requests, json
from terminaltables import AsciiTable
from ..conf.conf import errors
from ..util.file import *
from ..util.checker import *
@click.command()
@click.option('--pkey', prompt="Enter Project private key (create one in website if you don't have one)",)
@click.option('--email', prompt="Enter you... |
"""
Twisted inetd.
Maintainer: Andrew Bennetts
Future Plans: Bugfixes. Specifically for UDP and Sun-RPC, which don't work
correctly yet.
"""
import os
from twisted.internet import process, reactor, fdesc
from twisted.internet.protocol import Protocol, ServerFactory
from twisted.protocols import wire
# A dict of k... |
import requests
import zlib
from django.conf import settings
from vendor.readability import readability
from utils import log as logging
class TextImporter:
def __init__(self, story, request=None):
self.story = story
self.request = request
@property
def headers(self):
ret... |
import unittest2 as unittest
from webkitpy.common.net.buildbot import Builder
from webkitpy.common.system.executive import ScriptError
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.port.test import TestPort
from webkitpy.tool.commands.perfalizer import PerfalizerTask
from webkitpy.tool.m... |
## test to see if new branch is working
import sys
class HelpfulException(Exception):
"""Allows for stacked exceptions.
Initalization:
message: The error message to the user. ex: Device could not be found.
exc: The original exception object
reasons: Reasons why the exceptio... |
import os
import json
from profile_chrome import controllers_unittest
from profile_chrome import perf_controller
from profile_chrome import ui
from pylib import constants
class PerfProfilerControllerTest(controllers_unittest.BaseControllerTest):
def testGetCategories(self):
if not perf_controller.PerfProfiler... |
#!/usr/bin/env python
# coding: utf-8
"""Download and parse Tanakh from <https://chabad.org/>.
Each chapter is in a separate HTML file (e.g., `01 - Genesis - 001.html`) and contains
navigation and textual information.
The relevant structure is:
```
<h1>...</h1>
<table class="Co_TanachTable">
<tr class="Co_Verse">
... |
"""The TensorFlow Federated library."""
import sys
from tensorflow_federated.version import __version__ # pylint: disable=g-bad-import-order
from tensorflow_federated import experimental
from tensorflow_federated.python import aggregators
from tensorflow_federated.python import analytics
from tensorflow_federated.p... |
import unittest
from test import support
import io # C implementation.
import _pyio as pyio # Python implementation.
# Simple test to ensure that optimizations in the IO library deliver the
# expected results. For best testing, run this under a debug-build Python too
# (to exercise asserts in the C code).
lengths =... |
#http://www.compaq.com/fortran/docs/
import os
import sys
from numpy.distutils.fcompiler import FCompiler
from distutils.errors import DistutilsPlatformError
compilers = ['CompaqFCompiler']
if os.name != 'posix' or sys.platform[:6] == 'cygwin' :
# Otherwise we'd get a false positive on posix systems with
# ca... |
# -*- coding: utf-8 -*-
from django import template
from django.conf import settings
from django.utils import timezone
from opps.polls.models import Poll, PollBox, PollConfig
register = template.Library()
@register.simple_tag(takes_context=True)
def get_poll(context, slug, relation='channel', template_name=None):
... |
#!/usr/bin/env python
from __future__ import unicode_literals
import itertools
import json
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from youtube_dl.compat import (
compat_print,
compat_urllib_request,
)
from youtube_dl.utils import format_... |
#coding: utf-8
import os
import weakref
from ConfigParser import SafeConfigParser
class SingletonMixin(object):
"""
Adds a singleton behaviour to an existing class.
weakrefs are used in order to keep a low memory footprint.
As a result, args and kwargs passed to classes initializers
must be of w... |
try:
from Crypto.Hash import keccak
sha3_256 = lambda x: keccak.new(digest_bits=256, data=x).digest()
except:
import sha3 as _sha3
sha3_256 = lambda x: _sha3.sha3_256(x).digest()
from bitcoin import privtopub
import sys
import rlp
from rlp.sedes import big_endian_int, BigEndianInt, Binary
from rlp.utils... |
from st2actions.runners.pythonrunner import Action
from lib.get_scan_results import GetScanResults
class ScanResults(Action):
def run(self, scan_exec_id=None, new_vulns=False, new_ports=False):
"""
The template class for
Returns: An blank Dict.
Raises:
ValueError: On ... |
# coding: utf-8
from __future__ import unicode_literals
import types
import unittest
from collections import OrderedDict
import rows.fields as fields
from rows.utils import create_table, ipartition, slug
class UtilsTestCase(unittest.TestCase):
def test_slug(self):
self.assertEqual(slug('Álvaro Justen... |
from __future__ import print_function
from .SceneClass import Scene
from ..backends.base_backend import DrawingData
class ScenesManager(object):
def __init__(self):
self._scenes = {}
self._models = None
self.sounds = None
self._engine = None
self.currentSceneID = ""
... |
#!/usr/bin/env python
"""
This file is part of Pyew
Copyright (C) 2009, 2010 Joxean Koret
This program 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 2 of the License, or
(at your option) any la... |
from django.shortcuts import render
from django.utils.crypto import get_random_string
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, make_password
from django.contrib.auth import login
from django.conf import settings
from altauth.models import AlternativePasswor... |
import testify as T
from pushmanager.testing.testservlet import TemplateTestCase
class NewRequestTemplateTest(TemplateTestCase):
authenticated = True
newrequest_page = 'modules/newrequest.html'
form_elements = ['title', 'tags', 'review', 'repo', 'branch', 'description', 'comments', 'watchers', 'takeover... |
try:
# installed by bootstrap.py
import sqla_plugin_base as plugin_base
except ImportError:
# assume we're a package, use traditional import
from . import plugin_base
import pytest
import argparse
import inspect
import collections
import os
try:
import xdist # noqa
has_xdist = True
except Imp... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.SimpleHoster import SimpleHoster
class FileuploadNet(SimpleHoster):
__name__ = "FileuploadNet"
__type__ = "hoster"
__version__ = "0.06"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(en\.)?file-upload\.net/downloa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.