code stringlengths 1 199k |
|---|
"""
The *_redability.pdf files contain slides with different text color
contrasting to the background:
1. bad text contrast(non gray-scale) - should fail with default args
2. good text contrast(gray on white, gray on black) - should pass with
default args
3. bad text contrast(gray on white) - should fail wit... |
'''
User API v1.0 List
'''
__author__ = 'M@Campbell'
from flask import jsonify, request, current_app, url_for, g
from ooiservices.app.main import api
from ooiservices.app import db, security
from ooiservices.app.main.authentication import auth, verify_auth
from ooiservices.app.models import User, UserScope, UserScopeLi... |
"""Runs CloudSuite Web Search benchmark.
Docs:
http://parsa.epfl.ch/cloudsuite/
Runs CloudSuite Web Search to collect the statistics that show
the operations completed per second and the minimum, maximum,
average, 90th, and 99th response times.
"""
import posixpath
import re
import time
from perfkitbenchmarker import c... |
def main():
print "Hello, World!"
if __name__ == "__main__":
main() |
import base
import v2_swagger_client
from v2_swagger_client.rest import ApiException
class Tag_Immutability(base.Base, object):
def __init__(self):
super(Tag_Immutability,self).__init__(api_type = "immutable")
def create_tag_immutability_policy_rule(self, project_id, selector_repository_decoration = "re... |
"""Module for testing the add organization command."""
import unittest
if __name__ == "__main__":
import utils
utils.import_depends()
from brokertest import TestBrokerCommand
class TestOrganization(TestBrokerCommand):
def test_100_addexorg(self):
command = ["add", "organization", "--organization", "... |
import json
import jsonschema
from pprint import pprint
import os
def loadSchema(filename):
with open(filename) as sfile:
schema = json.load(sfile)
jsonschema.Draft4Validator.check_schema(schema)
print 'Loaded and verified schema in %s' % filename
return schema
def loadJson(filename):
with open(file... |
"""
Claim objects for use with resource tracking.
"""
from oslo_log import log as logging
from nova import exception
from nova.i18n import _
from nova import objects
from nova.virt import hardware
LOG = logging.getLogger(__name__)
class NopClaim(object):
"""For use with compute drivers that do not support resource ... |
"""Tests for the CPIO resolver helper implementation."""
import unittest
from dfvfs.lib import definitions
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver_helpers import cpio_resolver_helper
from tests.resolver_helpers import test_lib
class CPIOResolverHelperTest(test_lib.ResolverHelperTestCase)... |
"""Support for Modbus Register sensors."""
import logging
import struct
import voluptuous as vol
from homeassistant.components.modbus import (
CONF_HUB, DEFAULT_HUB, DOMAIN as MODBUS_DOMAIN)
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_OFFSET, CON... |
from .fields import (RelationshipField, ReferenceField)
relationship_fields = (RelationshipField, ReferenceField)
def is_relationship_field(field, model_cls):
""" Determine if `field` of the `model_cls` is a relational
field.
"""
if not model_cls.has_field(field):
return False
field_obj = mo... |
"""Turn Python docstrings into Markdown for TensorFlow documentation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ast
import functools
import inspect
import os
import re
import codegen
import six
IDENTIFIER_RE = '[a-zA-Z_][a-zA-Z0-9_]*'
def docu... |
"""
Home automation channels module for Zigbee Home Automation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/integrations/zha/
"""
import logging
from typing import Optional
import zigpy.zcl.clusters.homeautomation as homeautomation
from homeassistant.helpers.dis... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.core.wrapped_globs import Globs
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.base.build_file_aliases import BuildFileAli... |
"""Tests for Plex setup."""
import copy
from datetime import timedelta
import ssl
import plexapi
import requests
import homeassistant.components.plex.const as const
from homeassistant.config_entries import (
ENTRY_STATE_LOADED,
ENTRY_STATE_NOT_LOADED,
ENTRY_STATE_SETUP_ERROR,
ENTRY_STATE_SETUP_RETRY,
)
... |
from __future__ import unicode_literals
default_app_config = 'stackdio.core.notifications.apps.StackdioNotificationsAppConfig' |
import logging
import os
import socket
import time
from django.contrib.auth.middleware import AuthenticationMiddleware # noqa
from django.contrib.auth.models import Permission # noqa
from django.contrib.auth.models import User # noqa
from django.contrib.contenttypes.models import ContentType # noqa
from django.cont... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
import numpy as np
from six.moves import range
import tensorflow.compat.v1 as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.lite.experimental.examples.lstm.rnn imp... |
import logging
import uuid
import mock
from oslo_config import cfg
from oslo_config import fixture as config_fixture
from oslotest import mockpatch
from pycadf import cadftaxonomy
from pycadf import cadftype
from pycadf import eventfactory
from pycadf import resource as cadfresource
from keystone import notifications
f... |
import socket
import zmq
PUB_IP = '127.0.0.1'
PUB_PORT = 5000
SUB_IP = '127.0.0.1'
SUB_PORT = 5001
TCP_IP = '127.0.0.1'
TCP_PORT = 5000
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
BUFFER_SIZE = 1024
print ("ZMQ Subsystem")
print (" Init ZMQ system with version: %s" %zmq.pyzmq_version())
context = zmq.Context()
print (" ZMQ ... |
from f5_openstack_agent.lbaasv2.drivers.bigip.lbaas_service import \
LbaasServiceObject
import pytest
class FakeConfig(object):
def __init__(self, environment_prefix='Fake'):
self.environment_prefix = environment_prefix
service_def = {
'healthmonitors':
[{'admin_state_up': True,
'd... |
from collections import abc
import functools
import inspect
import time
import types
def def_method(f, *args, **kwargs):
@functools.wraps(f)
def new_method(self):
return f(self, *args, **kwargs)
return new_method
def parameterized_class(cls):
"""A class decorator for running parameterized test c... |
"""
Pascal VOC Segmentation database
This class loads ground truth notations from standard Pascal VOC XML data formats
and transform them into IMDB format. Selective search is used for proposals, see segdb
function. Results are written as the Pascal VOC format. Evaluation is based on mAP
criterion.
"""
import cPickle
i... |
from __future__ import print_function
import six
from paddle.fluid import core
import paddle
def delete_ops(block, ops):
for op in ops:
try:
idx = list(block.ops).index(op)
block._remove_op(idx)
except Exception as e:
print(e)
def find_op_by_input_arg(block, arg_n... |
from twisted.internet import defer
from ._base import BaseHandler
from synapse.api.errors import SynapseError, Codes, CodeMessageException, AuthError
from synapse.api.constants import EventTypes
from synapse.types import RoomAlias, UserID, get_domain_from_id
import logging
import string
logger = logging.getLogger(__nam... |
"""Information about nnvm."""
from __future__ import absolute_import
import sys
import os
import platform
if sys.version_info[0] == 3:
import builtins as __builtin__
else:
import __builtin__
def find_lib_path():
"""Find NNNet dynamic library files.
Returns
-------
lib_path : list(string)
... |
from traits.api import Bool, Property, Float, CInt, List, Str, Any
from traitsui.api import View, Item, HGroup, spring
from threading import Timer as OneShotTimer, Thread, Event
import time
from pychron.core.helpers.timer import Timer as PTimer
from pychron.loggable import Loggable
def convert_to_bool(v):
try:
... |
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOWEST
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Slash escape quotes (' and ")
>>> tamper('1" AND SLEEP(5... |
__author__ = 'Shamal Faily'
class ImpliedProcess:
def __init__(self,ipId,ipName,ipDesc,pName,cNet,ipSpec,chs):
self.theId = ipId
self.theName = ipName
self.theDescription = ipDesc
self.thePersonaName = pName
self.theCodeNetwork = cNet
self.theSpecification = ipSpec
self.theChannels = chs
... |
from artefact.utils.consume_parser import ConsumeParser
import re
import json
class Line(ConsumeParser):
# This char is §, the 'Section' character
split_char = '§'
rules = [
(r'^(?P<cookie_id>-?\d*)' + split_char, False),
(r'^(?P<site_id>\d+)' + split_char, False),
(r'^(?P<d... |
"""The tests for the Reddit platform."""
import copy
import unittest
from unittest.mock import patch
from homeassistant.components.reddit import sensor as reddit_sensor
from homeassistant.components.reddit.sensor import (
DOMAIN,
ATTR_SUBREDDIT,
ATTR_POSTS,
CONF_SORT_BY,
ATTR_ID,
ATTR_URL,
A... |
import re
try:
from urllib import quote
except ImportError:
from urllib.parse import quote
from robot.errors import DataError
from robot.htmldata import HtmlFileWriter, ModelWriter, JsonWriter, LIBDOC
from robot.utils import get_timestamp, html_escape, html_format, NormalizedDict
from robot.utils.htmlformatters... |
from __future__ import absolute_import, division, print_function
import math
import os
import sys
import numpy as np
from numba import unittest_support as unittest
from numba import njit
from numba.compiler import compile_isolated, Flags, types
from numba.runtime import rtsys
from numba.config import PYVERSION
from .su... |
import matplotlib.pyplot as plt
from hyperion.model import ModelOutput
from hyperion.util.constants import pc
mo = ModelOutput('class1_example.rtout')
sed = mo.get_sed(aperture=-1, distance=140. * pc)
fig = plt.figure(figsize=(5, 4))
ax = fig.add_subplot(1, 1, 1)
ax.loglog(sed.wav, sed.val.transpose(), color='black')
a... |
import os
import sys
from contextlib import contextmanager
from glob import glob
from shutil import rmtree, copy, copytree
from tempfile import mkdtemp
from invoke import ctask as task, Collection, run
@contextmanager
def tmpdir():
tmp = mkdtemp()
try:
yield tmp
finally:
rmtree(tmp)
def unpa... |
from django.apps import AppConfig
from django.core.checks import register, Tags
from django.utils.translation import gettext_lazy as _
class SignageConfig(AppConfig):
name = 'geotrek.signage'
verbose_name = _("Signage")
def ready(self):
from .forms import SignageForm, BladeForm
def check_hid... |
import batoid
import numpy as np
from test_helpers import timer, do_pickle, all_obj_diff, init_gpu, rays_allclose
@timer
def test_properties():
rng = np.random.default_rng(5)
for i in range(100):
R = rng.normal(0.0, 0.3) # negative allowed
conic = rng.uniform(-2.0, 1.0)
quad = batoid.Qu... |
"""
Utility base TestCase classes for testing APIs.
"""
from django.core.urlresolvers import reverse
from tests.case.view import WebTest
from django_webtest import DjangoTestApp
from moztrap.model import API_VERSION
import urllib
import json
class ApiTestCase(WebTest):
"""A test-case for API tests."""
def get_r... |
from flask_restful import Api
from werkzeug.wrappers import Response
from flask import make_response
from redash.utils import json_dumps
from redash.handlers.base import org_scoped_rule
from redash.handlers.permissions import ObjectPermissionsListResource, CheckPermissionResource
from redash.handlers.alerts import Aler... |
import re
from io import BytesIO
import pytest
from jinja2 import DictLoader
from jinja2 import Environment
from jinja2 import nodes
from jinja2 import pass_context
from jinja2.exceptions import TemplateAssertionError
from jinja2.ext import Extension
from jinja2.lexer import count_newlines
from jinja2.lexer import Toke... |
import os, re, sys, string
import argparse
import jsmin
import bz2
import textwrap
class Error(Exception):
def __init__(self, msg):
Exception.__init__(self, msg)
def ToCArray(byte_sequence):
result = []
for chr in byte_sequence:
result.append(str(ord(chr)))
joined = ", ".join(result)
return textwrap.f... |
def _get_data_from_xml(doclist, fieldname, nohitreturn=None):
"""Get the fieldname (i.e. author, title etc)
from minidom.parseString().childNodes[0].childNodes list
"""
result = []
for element in doclist:
try:
fields = element[fieldname]
except KeyError:
field... |
import web
from .. import account
from .. import forms
from ..flash import flash
from ..models import Organization, User
from ..template import render_template
urls = (
"/orgs", "org_list",
"/orgs/(\d+)", "org_view",
"/orgs/(\d+)/add-member", "org_new_member",
"/orgs/(\d+)/new-workshop", "new_workshop",... |
"""This module contains functions to handle ``stginga`` plugins.
See :ref:`stginga-run`.
"""
from ginga.misc.Bunch import Bunch
__all__ = ['load_plugins', 'show_plugin_install_info']
def load_plugins(ginga):
"""Load the ``stginga`` plugins.
Parameters
----------
ginga
The ginga app object that i... |
from phovea_server import launch
if __name__ == '__main__':
launch.run()
else:
application = launch.create_embedded()
print('run as embedded version: %s', application) |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittest
import json
import sys
import os
import uuid
import logging
i... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ...extern.six.moves.urllib.parse import parse_qs
from ...extern.six.moves.urllib.request import urlopen
from ...extern.six.moves import input
from ...utils.data import get_pkg_data_contents
from .standard_p... |
"""
Test index support in time series models
1. Test support for passing / constructing the underlying index in __init__
2. Test wrapping of output using the underlying index
3. Test wrapping of prediction / forecasting using the underlying index or
extensions of it.
Author: Chad Fulton
License: BSD-3
"""
import pyt... |
from optparse import make_option
import threading
from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand
class AbstractLocalServerCommand(AbstractDeclarativeCommand):
server = None
launch_path = "/"
def __init__(self):
options = [
make_option("--httpd-port", action="store"... |
import numpy as np
from astropy.io import fits
from . import FitsTestCase
class TestDivisionFunctions(FitsTestCase):
"""Test code units that rely on correct integer division."""
def test_rec_from_string(self):
with fits.open(self.data('tb.fits')) as t1:
s = t1[1].data.tobytes()
np.re... |
"""
Utility for saving locals.
"""
import sys
try:
import types
frame_type = types.FrameType
except:
frame_type = type(sys._getframe())
def is_save_locals_available():
return save_locals_impl is not None
def save_locals(frame):
"""
Copy values from locals_dict into the fast stack slots in the gi... |
import gzip
import pandas as pd
import numpy as np
import pandas.util.testing as tm
import os
import dask
from operator import getitem
import pytest
from toolz import valmap
import tempfile
import shutil
from time import sleep
import dask.array as da
import dask.dataframe as dd
from dask.dataframe.io import (read_csv, ... |
import sys
import matplotlib
if matplotlib.get_backend() != "TKAgg":
matplotlib.use("TKAgg")
import pmagpy.pmag as pmag
import pmagpy.pmagplotlib as pmagplotlib
def main():
"""
NAME
dmag_magic2.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
... |
"""Test to make sure we can open /dev/tty"""
f = open("/dev/tty", "r+")
a = f.readline()
f.write(a)
f.close() |
from django.db import migrations
DEMO_PROJECT_CONTENT = """
Welcome to Pontoon! Translate this sentence and press Enter.
Congratulations, you have translated your first "string"!
Keep translating, we'll show you tips and tricks about Pontoon.
In this sentence, click the dot-dot-dot at the end…
Nice! The "placeable" has... |
"""
Functions to operate on polynomials.
"""
from __future__ import division, absolute_import, print_function
__all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd',
'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d',
'polyfit', 'RankWarning']
import re
import warnings
import numpy.core.num... |
import numpy as np
from scipy import sparse
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array, warn_if_not_float, check_is_fitted
from sklearn.utils.sparsefuncs import inplace_column_scale, \
mean_variance_axis
def _mean_and_std(X, axis=0, with_mean=True, with... |
''' Provide a base class for all objects (called Bokeh Models) that can go in
a Bokeh |Document|.
'''
from __future__ import absolute_import, print_function
import logging
logger = logging.getLogger(__file__)
from contextlib import contextmanager
from json import loads
from operator import itemgetter
from six import it... |
"""
Plugin for probing vnc
"""
from framework.dependency_management.dependency_resolver import ServiceLocator
DESCRIPTION = " VNC Probing "
def run(PluginInfo):
resource = ServiceLocator.get_component("resource").GetResources('VncProbeMethods')
return ServiceLocator.get_component("plugin_helper").CommandDump('T... |
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources ... |
import pickle
import sys
import time
import datetime
import tempfile
import stripe
import stripe.resource
from stripe.test.helper import (
StripeUnitTestCase, StripeApiTestCase,
MySingleton, MyListable, MyCreatable, MyUpdateable, MyDeletable,
MyResource, SAMPLE_INVOICE, NOW,
DUMMY_CARD, DUMMY_CHARGE, DU... |
import __init__
import settings
tweenk_core = settings.core()
tweenk_balance = settings.balance()
import optparse
import db
import random
import achv
import time
import statistics
import os, sys, inspect
import re
class converter():
mongo = db.mongoAdapter()
buff = ''
BASE_DIR = os.path.abspath(os.path.split(inspect... |
from test.test_support import run_unittest, check_py3k_warnings
import unittest
class AugAssignTest(unittest.TestCase):
def testBasic(self):
x = 2
x += 1
x *= 2
x **= 2
x -= 8
x //= 5
x %= 3
x &= 2
x |= 5
x ^= 1
x /= 2
i... |
DOIT_CONFIG = {'default_tasks': ['use_cmd', 'use_python']}
def task_compute():
def comp():
return {'x':5,'y':10, 'z': 20}
return {'actions': [(comp,)]}
def task_use_cmd():
return {'actions': ['echo x=%(x)s, z=%(z)s'],
'getargs': {'x': ('compute', 'x'),
'z': ('compute', ... |
"""
The List Member Goals API endpoint
Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/goals/
Schema: https://api.mailchimp.com/schema/3.0/Lists/Members/Goals/Collection.json
"""
from __future__ import unicode_literals
from mailchimp3.baseapi import BaseApi
from mailchimp3.... |
"""
Request Management
"""
module = request.controller
resourcename = request.function
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
def index():
""" Module's Home Page """
return s3db.cms_index(module, alt_function="index_alt")
def index_alt():
"""
... |
import os
from subprocess import Popen, PIPE
def parse_solver_output(output):
# TODO: analyze output the first line from setcover.sol
# to determine if we get optimal solution or we stops since time limit
lines = output.split('\n')
for i in xrange(len(lines)):
if lines[i].startswith('===========... |
import rdtest
import struct
import renderdoc as rd
def real_action_children(action):
return [c for c in action.children if not c.flags & rd.ActionFlags.PopMarker]
class VK_Indirect(rdtest.TestCase):
demos_test_name = 'VK_Indirect'
def check_overlay(self, pass_samples, *, no_overlay = False):
pipe: r... |
"""
Function for drawing nodes in a context as a .dot file.
This is outside context.py as it doesn't need to by
cythoned and it's convenient to use inner functions,
which isn't supported in cython.
"""
from nodes import MDFNode, MDFVarNode,_now_node
from nodetypes import MDFQueueNode
import pydot
import os
def _to_dot... |
import VS
import GUI
import custom
import Base
import debug
from functools import reduce
text_height=0.1
def parse_dialog_box(args):
i=0
elementsToCreate=[]
currentList=elementsToCreate
while i<len(args):
type=args[i]
i+=1
if type=='list':
id=str(args[i])
... |
"""
***************************************************************************
MultilineTextPanel.py
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
********************************************... |
from invenio.htmlutils import HTMLWasher, cfg_html_buffer_allowed_tag_whitelist,\
cfg_html_buffer_allowed_attribute_whitelist
class EmailWasher(HTMLWasher):
"""
Wash comments before being send by email
"""
def handle_starttag(self, tag, attrs):
"""Function called fo... |
import pytest
from cfme.containers.overview import ContainersOverview
from cfme.containers.provider import ContainersProvider
from cfme.containers.container import Container
from cfme.containers.service import Service
from cfme.containers.route import Route
from cfme.containers.project import Project
from cfme.containe... |
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Institute.name'
db.alter_column('institute', 'name', self.gf(
'django.db.models.fields.CharField')(unique=True, max_length=255))
def backwards(sel... |
import util, pexpect, sys, time, math, shutil, os
from common import *
import mavutil, random
testdir=os.path.dirname(os.path.realpath(__file__))
HOME_LOCATION='-35.362938,149.165085,585,354'
WIND="0,180,0.2" # speed,direction,variance
homeloc = None
def takeoff(mavproxy, mav):
'''takeoff get to 30m altitude'''
... |
"""DEPRECATED UI FUNCTIONALITY""" |
"""
Unit tests for `biggus.save()`.
"""
from __future__ import absolute_import, division, print_function
from six.moves import (filter, input, map, range, zip) # noqa
import unittest
import numpy as np
import numpy.ma
import biggus
from biggus.tests import mock
class _WriteCounter(object):
"""
Acts like an HDF... |
from iiboost import Booster
from sklearn.externals import joblib # to load data
import matplotlib.pyplot as plt
gt = joblib.load("../../testData/gt.jlb")
img = joblib.load("../../testData/img.jlb")
model = Booster()
model.train( [img], [gt], numStumps=100, debugOutput=True)
pred = model.predict( img )
plt.ion()
plt.fig... |
import numpy as np
from hyperspy.datasets.artificial_data import \
get_core_loss_eels_line_scan_signal
from hyperspy.signal_tools import EdgesRange
class Owner:
"""for use in Test_EdgesRange"""
def __init__(self, edge):
self.description = edge
class Test_EdgesRange:
def setup_method(self, method... |
from plex.objects.core.base import Descriptor, Property
from plex.objects.library.part import Part
class Media(Descriptor):
parts = Property(resolver=lambda: Part.from_node)
id = Property(type=int)
video_codec = Property('videoCodec')
video_frame_rate = Property('videoFrameRate')
video_resolution = ... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
module: na_cdot_svm
short_description: Manage NetApp cDOT svm
extends_documentation_fragment:
- netapp.ontap
version_added: '2.3'
author: Sumit Kumar (sumit4@netapp.c... |
import logging
import os
from HTMLParser import HTMLParseError, HTMLParser
from tempfile import mkstemp
from urlparse import urljoin, urlparse
from twisted.internet import defer, threads
from twisted.web.error import PageRedirect
from deluge.component import Component
from deluge.configmanager import get_config_dir
fro... |
""" File Catalog Client Command Line Interface. """
__RCSID__ = "$Id$"
import cmd
import sys
import pprint
import os
import atexit
import readline
from DIRAC.Core.Utilities.ColorCLI import colorize
from DIRAC.FrameworkSystem.Client.SystemAdministratorClient import SystemAdministratorClient
from DIRAC.FrameworkSystem.Cl... |
"""State describing the masking behaviour of the SANS reduction."""
from __future__ import (absolute_import, division, print_function)
import json
import copy
from sans.state.state_base import (StateBase, BoolParameter, StringListParameter, StringParameter,
PositiveFloatParameter, Flo... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import locations.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel... |
from __future__ import absolute_import
import importlib
import json
import logging
import threading
import time
import boto
import structlog
import wsme.rest.json
from boto.sqs import message as sqs_message
logger = structlog.get_logger()
class _StopListening(Exception):
pass
class AWS(object):
def __init__(sel... |
"""
This script is meant to pull the translations from Transifex .
Technically, it will pull the translations from Transifex,
compare it with the po files in the repository and replace it if needed
Installation
============
For using this utility, you need to install these dependencies:
* github3.py library for handlin... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('registration', '0005_merge'),
]
operations = [
migrations.RemoveField(
model_name='registrationprofile',
name='interests',
... |
import os
import platform
import sys
from logging.handlers import SysLogHandler
def get_logger_config(log_dir,
logging_env="no_env",
edx_filename="edx.log",
dev_env=False,
syslog_addr=None,
debug=False,
... |
from __future__ import absolute_import
from __future__ import division # Ensures that a/b is always a float.
__all__ = [
'UnstructuredFrequencyModel'
]
import numpy as np
from qinfer.utils import binomial_pdf
from qinfer.abstract_model import Model, DifferentiableModel
class UnstructuredFrequencyModel(Model):
r"""
R... |
from areas.models import Area, Generation
def code_version():
return 'gss'
def check(name, type, country, geometry):
"""Should return True if this area is NEW, False if we should match against ONS code,
or an Area to be used as an override instead"""
# There appears to be a regression, in that new ar... |
"""
Forms for eLCID
"""
from django import forms
class BulkCreateUsersForm(forms.Form):
"""
Form for uploading a CSV of users to add.
"""
users = forms.FileField() |
from wtforms import TextField, SelectField
from wtforms.validators import DataRequired, NumberRange
from ..base import BaseReactForm
class ReactForm(BaseReactForm):
''' Class that creates a Reaction form for the dashboard '''
apikey = TextField(
"API Key",
validators=[DataRequired(message='API K... |
from spack import *
class PyRsa(PythonPackage):
"""Pure-Python RSA implementation"""
homepage = "https://stuvel.eu/rsa"
pypi = "rsa/rsa-3.4.2.tar.gz"
version('4.7.2', sha256='9d689e6ca1b3038bc82bf8d23e944b6b6037bc02301a574935b2dd946e0353b9')
version('4.0', sha256='1a836406405730121ae9823e19c6e806c... |
from spack import *
class PacbioDamasker(MakefilePackage):
"""Damasker: The Dazzler Repeat Masking Suite. This is a special fork
required for some pacbio utilities."""
homepage = "https://github.com/PacificBiosciences/DAMASKER"
url = "https://github.com/PacificBiosciences/DAMASKER"
version('... |
"""Module with functions to parse the input file and convert
Psithon into standard Python. Particularly, forms psi4
module calls that access the C++ side of Psi4.
"""
import re
import os
import sys
import uuid
from psi4 import core
from psi4.driver.p4util.util import set_memory
from psi4.driver.p4util.exceptions import... |
import numpy, collections
from tabulate import tabulate
"""Dictionary of Donors and Amounts Donated"""
donors = {"nick padgett": [12312, 34230, 38593],
"julia allen": [49203, 5023, 9052],
"pete tamisin": [9503, 2093, 10932, 40923],
"charles elliott": [209, 50912, 9026],
"andy roc... |
"""
The PyBuilder exception utils module for Python version 2.x
"""
def raise_exception(ex, tb):
raise ex, None, tb |
"""Tests for Keras activation 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
def _ref_softmax(values):
m = np.max(values)
e = n... |
import Queue
import threading
THREAD_COUNT = 1
EACH_MACHINE_TASK_COUNT = 3000
MACHINE_ID = 0
finished_tasks = set() # 已完成的任务集合
UNEXIST_USER_FILEPATH = 'log/unexist-user.txt'
NOBLOG_USER_FILEPATH = 'log/noblog-user.txt'
dir_count = 0 # 计数当前目录编号
dir_root = 'data/data1' # 保存文件的根目录
MAX_FILE_COUNT = 1000 # 每个文件夹最多保存的文件数... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.