code stringlengths 1 199k |
|---|
"""
Test the views of jurisdiction models
"""
from django.test import TestCase
from nose.tools import assert_is_not, eq_
from muckrock.core.test_utils import http_get_response
from muckrock.jurisdiction import factories, views
class TestExemptionDetailView(TestCase):
"""The exemption detail view provides informatio... |
""" This class is a base class for nearly all configuration
elements like service, hosts or contacts.
"""
import time
import cPickle # for hashing compute
try:
from hashlib import md5
except ImportError:
from md5 import md5
from copy import copy
from shinken.graph import Graph
from shinken.commandcall import ... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
import itertools
from datetime import timedelta
import ddt
from django.core.exceptions import ValidationError
from django.test import Test... |
__metaclass__ = type
__all__ = [
'BranchRevision',
]
from storm.locals import (
Int,
Reference,
Storm,
)
from zope.interface import implements
from lp.code.interfaces.branchrevision import IBranchRevision
class BranchRevision(Storm):
"""See `IBranchRevision`."""
__storm_table__ = 'Branch... |
from gavel import app
from gavel.models import *
from gavel.constants import *
import gavel.settings as settings
import gavel.utils as utils
from flask import (
redirect,
render_template,
request,
url_for,
)
import urllib.parse
@app.route('/admin/')
@utils.requires_auth
def admin():
annotators = Ann... |
import os
import subprocess
import shutil
karma = os.path.join(os.path.dirname(__file__), '../node_modules/.bin/karma')
def javascript_tests():
if not shutil.which('nodejs'):
print("W: nodejs not available, skipping javascript tests")
return 0
elif os.path.exists(karma):
chrome_exec = sh... |
from IPy import IP
import re
ASN = re.compile(r'AS\d+', re.IGNORECASE)
def validate(resources):
outcome = True
for resource in resources:
if ASN.match(resource):
continue
else:
try:
IP(resource)
except ValueError as error:
outco... |
"""
Studio editing view for OpenAssessment XBlock.
"""
import copy
import logging
from uuid import uuid4
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy
from voluptuous import MultipleInvalid
from xblock.fields import List, Scope
from xblock.core import XBlock
from web... |
from odoo import models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def group_by_account_and_tax(self):
grouped_lines = {}
for line in self:
group_key = (line.account_id, line.tax_line_id)
if group_key not in grouped_lines:
grouped_... |
from django.conf.urls.defaults import *
from videos.views import rpc_router
urlpatterns = patterns(
'videos.views',
url(r'^watch/$', 'watch_page', name='watch_page'),
url(r'^watch/featured/$', 'featured_videos', name='featured_videos'),
url(r'^watch/latest/$', 'latest_videos', name='latest_videos'),
... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import viewsets, routers
from voting_app.models import Topic
from voting_app.views import Vote
from voting_app.serializer import TopicSerializer
admin.autodiscover()
class TopicViewSet(viewsets.ModelViewSet):
mo... |
import pytest
from io import BytesIO
from rinoh.backend.pdf import cos
from rinoh.backend.pdf.reader import PDFObjectReader
def test_read_boolean():
def test_boolean(bytes_boolean, boolean):
reader = PDFObjectReader(BytesIO(bytes_boolean))
result = reader.next_item()
assert isinstance(result... |
import os
from fnmatch import fnmatch
from yum.plugins import TYPE_INTERACTIVE
from yum.plugins import PluginYumExit
requires_api_version = '2.0'
plugin_type = (TYPE_INTERACTIVE,)
def posttrans_hook(conduit):
pkgs = []
patch_required = False
# If we aren't root, we can't have updated anything
if os.gete... |
"""
This package contains all python modules implementing the DROP
Manager concepts, including their external interface, a web UI and a client
""" |
import threading
import time
from ea.libs.NetLayerLib import ServerAgent as NetLayerLib
from ea.libs.NetLayerLib import Messages as Messages
from ea.libs.NetLayerLib import FifoCallBack as FifoCallBack
from ea.serverinterfaces import EventServerInterface as ESI
from ea.serverinterfaces import AgentServerInterface as AS... |
import datetime
import inspect
import os
import sys
import time
import urllib
_g_fmbt_adapterlogtimeformat="%s.%f"
_g_actionName = "undefined"
_g_testStep = -1
_g_simulated_actions = []
def _fmbt_call_helper(func,param = ""):
if simulated():
return ""
sys.stdout.write("fmbt_call %s.%s\n" % (func,param))... |
"""
RHEL-7 installation
"""
import os
import oz.ozutil
import oz.RedHat
import oz.OzException
class RHEL7Guest(oz.RedHat.RedHatLinuxCDYumGuest):
"""
Class for RHEL-7 installation
"""
def __init__(self, tdl, config, auto, output_disk=None, netdev=None,
diskbus=None, macaddress=None):
... |
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
import dbus
def parse_account(s):
lines = s.splitlines()
pairs = []
manager = None
protocol = None
for line in lines:
if not line.strip():
continue
k, v = line.split(':', 1)
k = k.strip()
... |
from __future__ import absolute_import
import collections
import logging
import threading
Callback = collections.namedtuple('Callback',
['conn', 'dom', 'body', 'opaque'])
def _null_cb(*args, **kwargs):
pass
_NULL = Callback(None, None, _null_cb, tuple())
class Handler(object):
... |
import hexablock
import os
doc = hexablock.addDocument ("default")
vx = doc.addVector (1,0,0)
vy = doc.addVector (0,1,0)
vz = doc.addVector (0,0,1)
vxy = doc.addVector (1,1,0)
nbr_files = 0
def save_vtk () :
global nbr_files
nom = "monica%d.vtk" % nbr_files
nbr_files += 1
doc.saveVtk (nom)
def c... |
import datetime
import unittest
from lxml import etree
from rpclib.application import Application
from rpclib.auxproc.thread import ThreadAuxProc
from rpclib.auxproc.sync import SyncAuxProc
from rpclib.decorator import rpc
from rpclib.decorator import srpc
from rpclib.interface.wsdl import Wsdl11
from rpclib.model.comp... |
from leapp.topics import Topic
class ApiTestTopic(Topic):
name = 'api_test' |
import os
import sys
from spack import *
class Vtk(CMakePackage):
"""The Visualization Toolkit (VTK) is an open-source, freely
available software system for 3D computer graphics, image
processing and visualization. """
homepage = "http://www.vtk.org"
url = "https://www.vtk.org/files/release/9.0... |
import HOST_RESOURCES_MIB
OIDMAP = {
'1.3.6.1.2.1.25': HOST_RESOURCES_MIB.host,
'1.3.6.1.2.1.25.1': HOST_RESOURCES_MIB.hrSystem,
'1.3.6.1.2.1.25.2': HOST_RESOURCES_MIB.hrStorage,
'1.3.6.1.2.1.25.2.1': HOST_RESOURCES_MIB.hrStorageTypes,
'1.3.6.1.2.1.25.3': HOST_RESOURCES_MIB.hrDevice,
'1.3.6.1.2.1.25.3.1': HOST_RESOURCE... |
import os
if os.path.exists("/usr/local/include/jack/jack.h"):
path = "/usr/local/include/jack/jack.h"
elif os.path.exists("/usr/include/jack/jack.h"):
path = "/usr/include/jack/jack.h"
else:
print("You don't seem to have the jack headers installed.\nPlease install them first")
exit(-1)
test = open(path).read()... |
from gi.repository import Gdk
from xml.etree.ElementTree import ElementTree, Element
import re
ESCAPE_PATTERN = re.compile(r'\\u\{([0-9A-Fa-f]+?)\}')
ISO_PATTERN = re.compile(r'[A-E]([0-9]+)')
def parse_single_key(value):
key = Element('key')
uc = 0
if hasattr(__builtins__, 'unichr'):
def unescape(m... |
import os
import shutil
from nxdrive.client.base_automation_client import DOWNLOAD_TMP_FILE_PREFIX, \
DOWNLOAD_TMP_FILE_SUFFIX
from nxdrive.engine.processor import Processor as OldProcessor
from nxdrive.logging_config import get_logger
log = get_logger(__name__)
class Processor(OldProcessor):
def __init__(self,... |
import os
import subprocess
from pathlib import Path
import pyinstaller_versionfile
import tomli
packaging_path = Path(__file__).resolve().parent
def get_version() -> str:
project_dir = Path(__file__).resolve().parent.parent
f = project_dir / "pyproject.toml"
return str(tomli.loads(f.read_text())["tool"]["p... |
from nose.tools import *
from utilities import execution_path, save_data, contains_word
import os, mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def test_dataraster_coloring():
srs = '+init=epsg:326... |
from datetime import date
import re
import pytest
from pyopenmensa.feed import LazyBuilder
@pytest.fixture
def canteen():
return LazyBuilder()
def test_date_converting(canteen):
day = date(2013, 3, 7)
assert canteen.dayCount() == 0
canteen.setDayClosed('2013-03-07')
assert canteen.dayCount() == 1
... |
'''
Puck: FreeBSD virtualization guest configuration server
Copyright (C) 2011 The Hotel Communication Network inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the Lice... |
from UM.Math.Vector import Vector
from UM.Math.Float import Float
class Plane:
"""Plane representation using normal and distance."""
def __init__(self, normal = Vector(), distance = 0.0):
super().__init__()
self._normal = normal
self._distance = distance
@property
def normal(self... |
from __future__ import absolute_import
import logging
import os
import sys
import datetime
import psutil
from six import StringIO
from twisted.web import http, resource
from Tribler.Core.Utilities.instrumentation import WatchDog
import Tribler.Core.Utilities.json_util as json
HAS_MELIAE = True
try:
from meliae impo... |
import os
import unittest
from rabdam.Subroutines.CalculateBDamage import rabdam
class TestClass(unittest.TestCase):
def test_bnet_values(self):
"""
Checks that RABDAM calculates expected Bnet values for a selection of
PDB entries
"""
import os
import requests
... |
from cqparts.constraint import Mate, Coincident
from .base import Fastener
from ..screws import Screw
from ..utils import VectorEvaluator, Selector, Applicator
class ScrewFastener(Fastener):
"""
Screw fastener assembly.
Example usage can be found here: :ref:`cqparts_fasteners.built-in.screw`
"""
Eva... |
VERSION = (1, 2, 21)
def get_version():
return '%d.%d.%d'%VERSION
__author__ = 'Marinho Brandao'
__license__ = 'GNU Lesser General Public License (LGPL)'
__url__ = 'http://django-plus.googlecode.com'
__version__ = get_version()
def get_dynamic_template(slug, context=None):
from models import DynamicTemplate
... |
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, prim... |
import sys
ver_info = sys.version_info
if ver_info[0] < 3 and ver_info[1] < 7:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename", help="input log file", metavar="LOG_FILE")
parser.add_option("-t", "--dbtype", dest="dbtype", help="database type", ... |
from vertebra.actor import actor
class test_00_actor:
def test_00_instantiate(self):
"""actor: can instantiate a base actor"""
a = actor()
assert isinstance(a,actor), "instantiated actor is actually an actor" |
#!/usr/bin/env python
'''
Copyright (C) 2011-2014 German Aerospace Center DLR
(Deutsches Zentrum fuer Luft- und Raumfahrt e.V.),
Institute of System Dynamics and Control
and BAUSCH-GALL GmbH, Munich
All rights reserved.
This file is licensed under the "BSD New" license
(see also http://opensource.org/licenses/BSD-3-Cl... |
from collections import OrderedDict
import copy
import dolfin
import ufl
from caches import *
from equation_solvers import *
from exceptions import *
from fenics_overrides import *
from fenics_utils import *
from pre_assembled_forms import *
from statics import *
from time_levels import *
from time_functions import *
_... |
import datetime
from django.db import models
from django.core import validators
from django.utils.translation import ugettext_lazy as _
from nmadb_contacts.models import Municipality, Human
class School(models.Model):
""" Information about school.
School types retrieved from `AIKOS
<http://www.aikos.smm.lt/... |
"""
This test illustrate how to generate an XML Mapnik style sheet from a pycnik
style sheet written in Python.
"""
import os
from pycnik import pycnik
import artefact
actual_xml_style_sheet = 'artefacts/style_sheet.xml'
expected_xml_style_sheet = 'style_sheet.xml'
class TestPycnik(artefact.TestCaseWithArtefacts):
... |
"""This module contains some mixins for the different nodes.
"""
from .exceptions import (AstroidBuildingException, InferenceError,
NotFoundError)
class BlockRangeMixIn(object):
"""override block range """
def set_line_info(self, lastchild):
self.fromlineno = self.l... |
from setuptools import setup
import sys
import os
import re
sys.path.append("src")
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except IOError:
return "File '%s' not found.\n" % fname
def readVersion():
txt = read("src/moddy/version.py")
ver = ... |
"""
Unit tests for module PySetTrie (see settrie.py).
Author: Márton Miháltz
https://sites.google.com/site/mmihaltz/
"""
import unittest
from settrie import SetTrie, SetTrieMap, SetTrieMultiMap
class TestSetTrie(unittest.TestCase):
"""
UnitTest for SetTrie class
"""
def setUp(self):
self.t = SetTrie([{1, 3}... |
big = 2000000 # B = the number below which primes are summed
p = [True] * big # P = whether a number is prime, all are initially true and will later be falsified
print("running sieve...")
s = 0 # S = the sum of primes less than big which... |
from rbnics.utils.decorators import ABCMeta, AbstractBackend, abstractmethod
@AbstractBackend
class ReducedVertices(object, metaclass=ABCMeta):
def __init__(self, space):
pass
@abstractmethod
def append(self, vertex_and_component):
pass
@abstractmethod
def save(self, directory, filen... |
import os
def change(values):
pass
def removeFile(path):
index = path.rfind(os.sep)
return path[:index] |
import string
import uuid
import random
from util import iDict
import exception
__all__ = ['RedirectionManager', 'LocalRedirection', 'RemoteRedirection']
def str2bool(x):
if x is None:
return False
if x.lower() in ('true', 't', '1'):
return True
else:
return False
def strip_xpath(x):... |
"""Mendel's First Law
Usage:
IPRB.py <input>
IPRB.py (--help | --version)
Options:
-h --help show this help message and exit
-v --version show version and exit
"""
problem_description = """Mendel's First Law
Problem
Probability is the mathematical study of randomly occurring phenomena. We will
model su... |
import scrapy
import re
from research.items import ResearchItem
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class CaltechSpider(scrapy.Spider):
name = "WISC"
allowed_domains = ["cs.wisc.edu"]
start_urls = ["https://www.cs.wisc.edu/research/groups"]
def parse(self, response):
item = ResearchItem()
for... |
from __future__ import division #brings in Python 3.0 mixed type calculation rules
import logging
import numpy as np
import pandas as pd
class TerrplantFunctions(object):
"""
Function class for Stir.
"""
def __init__(self):
"""Class representing the functions for Sip"""
super(TerrplantF... |
'''Convert video JSON data into CSV list.
The JSON documents should be from
https://api.twitch.tv/kraken/videos/top?limit=20&offset=0&period=all
'''
import argparse
import csv
import json
import glob
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('directory')
arg_parser.add_argu... |
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 field 'Project.is_forced_active'
db.add_column(u'projects_project', 'is_forced_active',
... |
"""Test the csv/json export functionality."""
import binascii
import textwrap
import dnstwister.tools
import patches
from dnstwister.core.domain import Domain
def test_csv_export(webapp, monkeypatch):
"""Test CSV export"""
monkeypatch.setattr(
'dnstwister.tools.resolve', lambda domain: ('999.999.999.999... |
"""ML Fairness gym location-based attention allocation environment.
This environment is meant to be a general but simple location-based
attention allocation environment.
Situations that could be modeled by this environment are pest-control, or
allocation of social interventions like mobile STD testing clinics.
This is ... |
import os
import pytest
import sdk_install
import sdk_networks
import sdk_utils
from tests import config
overlay_nostrict = pytest.mark.skipif(os.environ.get("SECURITY") == "strict",
reason="overlay tests currently broken in strict")
@pytest.fixture(scope='module', autouse=True)
def configure_package(configure_secu... |
from django.urls import re_path
from .views import PrivateStorageView
urlpatterns = [
re_path(r'^(?P<path>.*)$', PrivateStorageView.as_view(), name='serve_private_file'),
] |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "boot.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really ... |
"""
Exception for errors raised while interpreting nodes.
"""
class NodeException(Exception):
"""Base class for errors raised while interpreting nodes."""
def __init__(self, *msg):
"""Set the error message."""
self.msg = ' '.join(msg)
def __str__(self):
"""Return the message."""
... |
import os
from jenkins_jobs import cmd
from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
@mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock)
class DeleteTests(CmdTestsBase):
@mock.patch('jenkins_jobs.cmd.Builder.delete_job')
def test_delete_single_job(self, delete_... |
import os
import mock
from pecan.testing import load_test_app
from tuskar.db.sqlalchemy import models as db_models
from tuskar.tests import base
URL_ROLES = '/v1/overcloud_roles'
class OvercloudRolesTests(base.TestCase):
def setUp(self):
super(OvercloudRolesTests, self).setUp()
config_file = os.path... |
"""Tests the Compute client."""
import mock
from tests.unittest_utils import ForsetiTestCase
from google.cloud.security.common.gcp_api import _base_client
from google.cloud.security.common.gcp_api import compute
from tests.common.gcp_api.test_data import fake_firewall_rules
class ComputeTest(ForsetiTestCase):
"""Te... |
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
... |
def load_table_uri_parquet(table_id):
# [START bigquery_load_table_gcs_parquet]
from google.cloud import bigquery
# Construct a BigQuery client object.
client = bigquery.Client()
# TODO(developer): Set table_id to the ID of the table to create.
# table_id = "your-project.your_dataset.your_table_... |
import django_filters
from django_filters import rest_framework as filters
from django_rv_apps.apps.believe_his_prophets.models.spirit_prophecy_chapter import SpiritProphecyChapter, SpiritProphecyChapterLanguage
from django_rv_apps.apps.believe_his_prophets.models.spirit_prophecy import SpiritProphecy
from django_rv_ap... |
import logging
from django.core import management
from django.core.management.base import BaseCommand
from awx.main.models import OAuth2AccessToken
from oauth2_provider.models import RefreshToken
class Command(BaseCommand):
def init_logging(self):
log_levels = dict(enumerate([logging.ERROR, logging.INFO,
... |
from toil.common import Config
from toil.job import CheckpointJobDescription, JobDescription
from toil.jobStores.fileJobStore import FileJobStore
from toil.test import ToilTest, travis_test
from toil.worker import nextChainable
class WorkerTests(ToilTest):
"""Test miscellaneous units of the worker."""
def setUp... |
import unittest
from unittest.mock import MagicMock
import logging
import nat_monitor
import utils
class NatInstanceTest(unittest.TestCase):
def setUp(self):
self.vpc_conn = MagicMock()
self.ec2_conn = MagicMock()
self.instance_id = 'i-abc123'
self.subnet = MagicMock()
self.s... |
"""Training script for RetinaNet segmentation model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
import absl.logging as _logging # pylint: disable=unused-import
import tensorflow.compat.v1 as tf
i... |
from troubleshooting.framework.modules.manager import ManagerFactory
from troubleshooting.framework.variable.variable import *
from troubleshooting.framework.libraries.baseList import list2stringAndFormat
from troubleshooting.framework.libraries.system import createDir
from troubleshooting.framework.modules.configurati... |
"""Wrapper control suite environments that adds Gaussian noise to actions."""
import dm_env
import numpy as np
_BOUNDS_MUST_BE_FINITE = (
'All bounds in `env.action_spec()` must be finite, got: {action_spec}')
class Wrapper(dm_env.Environment):
"""Wraps a control environment and adds Gaussian noise to actions."""... |
import boto3
import botocore
import tarfile
import os
import shutil
class Persistor(object):
def __init__(self, data_dir, aws_region, bucket_name):
self.data_dir = data_dir
self.s3 = boto3.resource('s3', region_name=aws_region)
self.bucket_name = bucket_name
try:
self.s3.... |
from bidi.algorithm import get_display as apply_bidi
from django.conf import settings
from .base import TestGeneratePdfBase
from .factories import create_voters
from .utils_for_tests import extract_pdf_page, extract_textlines, clean_textlines, unwrap_lines
from ..arabic_reshaper import reshape
from ..generate_pdf impor... |
"""
This example demonstrate how status works
"""
from juju import jasyncio
from juju import loop
import logging
import sys
from logging import getLogger
from juju.model import Model
from juju.status import formatted_status
LOG = getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
async def m... |
class Luokka( object ):
def __init__( self, N ):
self.luku = N
def test( self ):
return self.luku
def test_001( data ):
#print >> cloudSnake.output, "Moi kaikki"
#print >> cloudSnake.output, cloudSnake.call( 'mean', [ [1,2,3,4] ] )
print >> cloudSnake.output, "Luokkakoe nro 1"
otus = cloudSnake.call( 'Luokka'... |
"""
Automatic config nagios configurations.
Copyright (C) 2015 Canux CHENG
All rights reserved
Name: __init__.py
Author: Canux canuxcheng@gmail.com
Version: V1.0
Time: Wed 09 Sep 2015 09:20:51 PM EDT
Exaple:
./nagios -h
"""
__version__ = "3.1.0.0"
__description__ = """Config nagios automatic. Any question contact t... |
"""Program tree representation."""
import numpy as np
from aloe.rfill.utils.rfill_consts import RFILL_EDGE_TYPES, RFILL_NODE_TYPES
class ProgNode(object):
"""Token as node in program tree/graph."""
def __init__(self, syntax, value=None, subtrees=None):
"""Initializer.
Args:
syntax: string representati... |
import vendor
vendor.add('lib')
from flask import Flask, render_template, url_for, request, jsonify
app = Flask(__name__)
import translate
@app.route('/')
def index_route():
phrase = request.args.get("q")
if not phrase:
return render_template("index.html", phrase="")
return render_template("index.html", phrase=phr... |
import contextlib
from time import time
from .meter import Meter
from .stats import Stat
from .histogram import Histogram
class Timer(Stat):
def __init__(self):
self.count = 0
self.meter = Meter()
self.histogram = Histogram()
super(Timer, self).__init__()
@contextlib.contextmanag... |
from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
_REQUEST_MESS... |
__all__ = [
'fixed_value',
'coalesce',
]
try:
from itertools import ifilter as filter
except ImportError:
pass
class _FixedValue(object):
def __init__(self, value):
self._value = value
def __call__(self, *args, **kwargs):
return self._value
def fixed_value(value):
return _Fix... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import textwrap
import unittest
from SortKeys.ttypes import SortedStruct, NegativeId
from SortSets.ttypes import SortedSetStruct
from thrift.protocol import TSimpleJSONPro... |
from .TProtocol import TType, TProtocolBase, TProtocolException
from struct import pack, unpack
class TBinaryProtocol(TProtocolBase):
"""Binary implementation of the Thrift protocol driver."""
# NastyHaxx. Python 2.4+ on 32-bit machines forces hex constants to be
# positive, converting this into a long. If we har... |
"""cmput404project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
C... |
"""
Cloud-Custodian AWS Lambda Entry Point
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import logging
import json
from c7n.config import Config
from c7n.structure import StructureParser
from c7n.resources import load_resources
from c7n.policy import PolicyCollection
... |
import proto # type: ignore
from google.protobuf import any_pb2 # type: ignore
from google.protobuf import timestamp_pb2 # type: ignore
__protobuf__ = proto.module(
package="grafeas.v1",
manifest={
"Recipe",
"Completeness",
"Metadata",
"BuilderConfig",
"InTotoProvenanc... |
import re
from django.template.defaultfilters import slugify
def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of th... |
'''Trains a simple convnet on the Fashion MNIST dataset.
Gets to % test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
'''
from __future__ import print_function
import keras
from keras.datasets import fashion_mnist
from keras.models import Sequential
from keras.layers import Dense, Drop... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import torch
import torch.utils.data
import ray
from ray.experimental.sgd.pytorch import pytorch_utils
from ray.experimental.sgd import utils
logger = logging.getLogger(__name__)
class PyTorchRunn... |
from django.db import models
from django.contrib.auth.models import User
from datetime import date
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Science Fiction, French P... |
def benchmark_hash_data():
"""
CommandLine:
python ~/code/ubelt/dev/bench_hash.py --convert=True --show
python ~/code/ubelt/dev/bench_hash.py --convert=False --show
"""
import ubelt as ub
#ITEM = 'JUST A STRING' * 100
ITEM = [0, 1, 'a', 'b', ['JUST A STRING'] * 4]
HASHERS = [... |
import pandas as pd
from google.cloud import datacatalog
from google.protobuf import timestamp_pb2
from google.datacatalog_connectors.commons.prepare.base_entry_factory import \
BaseEntryFactory
from google.datacatalog_connectors.rdbms.common import constants
class DataCatalogEntryFactory(BaseEntryFactory):
NO_... |
import sys
import os
import re
import copy
import glob
import types
try:
from . import base
from . import dag
from . import util
from . import plan
except:
s = "\nXED ERROR: mfile.py could not find mbuild." + \
" Should be a sibling of the xed2 directory.\n\n"
sys.stderr.write(s)
sys.exit(1... |
from invoke import task, run
import requests
import rdflib
import getpass
import os.path
import os
import setlr
from os import listdir
from rdflib import *
import logging
CHEAR_DIR='chear.d/'
HHEAR_DIR='hhear.d/'
SETL_FILE='ontology.setl.ttl'
ontology_setl = Namespace('https://hadatac.org/setl/')
setl = Namespace('http... |
__reversion__ = "$Revision: 20 $"
__author__ = "$Author: holtwick $"
__date__ = "$Date: 2007-10-09 12:58:24 +0200 (Di, 09 Okt 2007) $"
from reportlab.lib.units import inch, cm
from reportlab.lib.styles import *
from reportlab.lib.enums import *
from reportlab.lib.colors import *
from reportlab.lib.pagesizes import *
fr... |
import argparse
import logging
import json
import subprocess
import sys
import os.path
import urllib2
from base64 import b64decode
from distutils.dir_util import mkpath
from tempfile import TemporaryFile
from shutil import copyfileobj
from urlparse import urlparse
from urllib2 import urlopen
from StringIO import String... |
from __future__ import absolute_import
from __future__ import print_function
__author__ = "imron@scalyr.com"
import sys
from scalyr_agent import UnsupportedSystem
from scalyr_agent.test_base import ScalyrTestCase
class MySqlMonitorTest(ScalyrTestCase):
def _import_mysql_monitor(self):
import scalyr_agent.bu... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import itertools
import os
import sys
import tempfile
from absl.testing import absltest
import numpy as np
from six.moves import cPickle
from simulation_research.traffic import file_util
class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.