code stringlengths 1 199k |
|---|
from pyasn1.type import univ, namedtype, namedval, tag
from pyasn1_modules import rfc1155
class Version(univ.Integer):
namedValues = namedval.NamedValues(
('version-1', 0)
)
defaultValue = 0
class Community(univ.OctetString): pass
class RequestID(univ.Integer): pass
class ErrorStatus(univ.Integer):
... |
import webapp2
from google.appengine.ext import db
import logging
import charbuilder
import traits
import traceback
import random
import string
instance_key = "".join(
(random.choice(string.ascii_uppercase + string.digits) for i in xrange(25)))
def getFile(_file):
with open(_file, "r") as f: return f.read().repla... |
"""
AUTHOR : MIN
PURPOSE : the deep learning CNN model, similar as inception
VERSION : 0.1
DATE : 4.2017
"""
__author__ = 'Min'
import math
import time
import tensorflow as tf
from datetime import datetime
NUM_CLASSES = 50
slim = tf.contrib.slim
trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, std... |
from django.conf.urls.defaults import patterns # noqa
from django.conf.urls.defaults import url # noqa
from openstack_dashboard.dashboards.fogbow.usage import views
from openstack_dashboard.dashboards.fogbow.usage.views import IndexView
urlpatterns = patterns('',
url(r'^$', IndexView.as_view(), name='index'),
... |
import confluent.exceptions as exc
import json
def _htmlify_structure(indict):
ret = "<ul>"
if isinstance(indict, dict):
for key in indict.iterkeys():
ret += "<li>{0}: ".format(key)
if type(indict[key]) in (str, unicode, float, int):
ret += str(indict[key])
... |
import mock
from nova.scheduler import solvers
from nova.scheduler.solvers.constraints import \
aggregate_image_properties_isolation
from nova import test
from nova.tests.scheduler import solver_scheduler_fakes as fakes
class TestAggregateImagePropertiesIsolationConstraint(test.N... |
class TestCobalt:
def test_stop_signals(self, mocker):
pass |
import resume.models as rmod
import random
import logging
from django.http import HttpResponse
from datetime import date
logger = logging.getLogger('default')
def generate(request):
cs_objs = rmod.Department.objects.filter(shortname='cs')
if len(cs_objs) == 0:
logger.info('created cs dept')
cs = rmod.Depart... |
import cython
def test_sizeof():
"""
>>> test_sizeof()
True
True
True
True
True
"""
x = cython.declare(cython.bint)
print(cython.sizeof(x) == cython.sizeof(cython.bint))
print(cython.sizeof(cython.char) <= cython.sizeof(cython.short) <= cython.sizeof(cython.int) <= cython.siz... |
from __future__ import unicode_literals
import mock
import requests
GITHUB_TRACKER = "dci.trackers.github.requests"
BUGZILLA_TRACKER = "dci.trackers.bugzilla.requests"
def test_attach_issue_to_job(user, job_user_id, topic_user_id):
with mock.patch(GITHUB_TRACKER, spec=requests) as mock_github_request:
mock_... |
import os
from dataclasses import dataclass
from typing import Iterable
from dbt.contracts.graph.manifest import SourceFile
from dbt.contracts.graph.parsed import ParsedSqlNode, ParsedMacro
from dbt.contracts.graph.unparsed import UnparsedMacro
from dbt.exceptions import InternalException
from dbt.node_types import Nod... |
"""Test the Balboa Spa Client config flow."""
from unittest.mock import patch
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.balboa.const import CONF_SYNC_TIME, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassista... |
import collections
import copy
import functools
import uuid
from dogpile.cache import api
from dogpile.cache import region as dp_region
import six
from keystone.common.cache.backends import mongo
from keystone import exception
from keystone.tests import unit as tests
ks_cache = {
"cache": [
{
"v... |
from __future__ import absolute_import
import sys
import errno
import itertools
import logging
import os
import posixpath
from boto.exception import S3ResponseError
from boto.s3.key import Key
from boto.s3.prefix import Prefix
from django.utils.translation import ugettext as _
from aws import s3
from aws.s3 import norm... |
import math
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ehata import ehata
from itm import pytm
from geo import tropoClim
from geo import refractivity
from geo import ned_indexer
from geo import nlcd_indexer
from geo import land_use
from geo import vincenty
def... |
"""Utilities for VariableMgr."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections as pycoll
import operator
import numpy as np
import tensorflow.compat.v1 as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework imp... |
from bson import ObjectId
import jsonschema
import numpy
from girder.exceptions import ValidationException
from girder.models.file import File
from girder.models.model_base import Model
from girder.models.upload import Upload
from girder.utility.acl_mixin import AccessControlMixin
from .image import Image
from .segment... |
from lexer import RqlLexer, RqlSyntaxError
import random
import math
DEFAULT_CONSTANTS = {
'PI': 3.1415926535897932384,
'NULL': None,
'FALSE': False,
'TRUE': True,
}
DEFAULT_FUNCTIONS = {
'abs': abs,
'min': min,
'max': max,
'sum': lambda *args: sum(args),
'acos': math.acos,
'asin': math.asin,
'ata... |
"""Plugin common functions."""
import logging
import os
import re
import shutil
import tempfile
import OpenSSL
import pkg_resources
import zope.interface
from acme.jose import util as jose_util
from certbot import constants
from certbot import crypto_util
from certbot import errors
from certbot import interfaces
from c... |
import logging
import traceback
from restlib import response
from mint import logerror
from mint import mint_error
from mint.rest.api import models
from mint.rest.modellib import converter
log = logging.getLogger(__name__)
class ErrorCallback(object):
def __init__(self, controller):
self.controller = contro... |
def lenOf(mylist):
return (len(mylist))
print (lenOf("Hello"))
print (lenOf(""))
print (lenOf([123,123,123])) |
import socket
import ssl
import select
import time
import re
import sys
from thread import start_new_thread
from struct import pack
from random import randint
from subprocess import call
import os
import fnmatch
import argparse
import logging
class lakkucast:
def __init__(self):
self.status = None
s... |
import os
import sys
def test(arg):
return os.system('bin/nosetests -s -d -v %s' % arg)
def main(args):
if not args:
print("Run as bin/python run_failure.py <test>, for example: \n"
"bin/python run_failure.py "
"kazoo.tests.test_watchers:KazooChildrenWatcherTests")
re... |
"""Library containing Tokenizer definitions.
The RougeScorer class can be instantiated with the tokenizers defined here. New
tokenizers can be defined by creating a subclass of the Tokenizer abstract class
and overriding the tokenize() method.
"""
import abc
from nltk.stem import porter
from rouge import tokenize
class... |
"""Interface for shares extension."""
try:
from urllib import urlencode # noqa
except ImportError:
from urllib.parse import urlencode # noqa
from manilaclient import api_versions
from manilaclient import base
from manilaclient.common import constants
from manilaclient.openstack.common.apiclient import base as... |
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.docker.subsystems.dockerfile_parser import rules as parser_rules
from pants.backend.docker.target_types import DockerImage
from pants.backend.docker.util_rules.docker_build_context import (
DockerBuildContext,
Docker... |
__all__ = [
'ComponentStore',
]
from pathlib import Path
import copy
import requests
from typing import Callable
from . import _components as comp
from .structures import ComponentReference
class ComponentStore:
def __init__(self, local_search_paths=None, url_search_prefixes=None):
self.local_search_pat... |
from django.apps import AppConfig
class BugzConfig(AppConfig):
name = 'Bugz' |
from django import template
import randomcolor
register = template.Library()
CATEGORY_NAMES = {
'cs.AI': 'Artificial Intelligence',
'cs.CL': 'Computation and Language',
'cs.CC': 'Computational Complexity',
'cs.CE': 'Computational Engineering',
'cs.CG': 'Computational Geometry',
'cs.GT': 'Game Th... |
import os
import csv
def get_value_or_default(value, default=None):
result = value.strip()
if len(result) == 0:
result = default
return result
def read_csv_file(csv_file_name,
delimiter,
quote_char='"',
skip_header=True,
encodin... |
from unittest import TestCase
import numpy as np
import pandas as pd
import h5py
from exatomic import Universe
from exatomic.base import resource
from exatomic.molcas.output import Output, Orb, HDF
class TestOutput(TestCase):
"""Test the Molcas output file editor."""
def setUp(self):
self.cdz = Output(r... |
"""
An L2 learning switch.
It is derived from one written live for an SDN crash course.
It is somwhat similar to NOX's pyswitch in that it installs
exact-match rules for each flow.
"""
from __future__ import division
from random import randrange
from pox.core import core
import pox.openflow.libopenflow_01 as of
from po... |
import unittest
from airflow.contrib.hooks.gcp_video_intelligence_hook import CloudVideoIntelligenceHook
from google.cloud.videointelligence_v1 import enums
from tests.contrib.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id
from tests.compat import mock
INPUT_URI = "gs://bucket-name/input-file"
OUTPUT_... |
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import... |
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.clie... |
"""Provides process view
This module provides a view for
visualizing processes in human-readable formm
"""
import cinder.openstack.common.report.views.jinja_view as jv
class ProcessView(jv.JinjaView):
"""A Process View
This view displays process models defined by
:class:`openstack.common.report.models.proce... |
from util import OpenCenterTestCase
import opencenter.db.api as db_api
from opencenter.webapp import ast
api = db_api.api_from_models()
class ExpressionTestCase(OpenCenterTestCase):
def setUp(self):
self.nodes = {}
self.interfaces = {}
self.nodes['node-1'] = self._model_create('nodes', name=... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
__author__ = 'thatcher'
from django.contrib import admin
from django.contrib.sessions.models import Session
from .models import *
from base.forms import *
def images_thubmnail(self):
return '<img style="max-height: 80px; width: auto;" src="{}" alt="{}" >'.format(self.uri(), self.alt)
# return self.uri()
images_thub... |
import json
import time
import parcon
import operator
import pprint
import os
import sys
import getopt
import re
import optparse
import string
import hashlib
import parse_objc as parser
import sign
VERSION = parser.VERSION
VERSION_STR = sign.source_file_signature(__file__, VERSION)
ID = parser.KEY_ID
pretty_json = pars... |
"""Export global feature tensorflow inference model.
This model includes image pyramids for multi-scale processing.
"""
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 tensorflow as tf
from delf.pyt... |
from __future__ import absolute_import, division, print_function, \
with_statement # use the features of python 3
import collections
import logging
import time
class LRUCache(collections.MutableMapping): # ABCs for read-only and mutable mappings.
"""This class is not thread safe"""
def __in... |
def run_test(n, m, power, bullet):
prev_dict = {}
cur_dict = {}
for i in xrange(n):
ri = n-1-i
for j in xrange(m):
if i == 0:
cur_dict[power[ri][j]] = power[ri][j]
else:
new_k = power[ri][j]
for k, v in prev_dict.items()... |
import ptypes, pecoff
from ptypes import *
from . import error, ldrtypes, rtltypes, umtypes, ketypes, Ntddk, heaptypes, sdkddkver
from .datatypes import *
class PEB_FREE_BLOCK(pstruct.type): pass
class PPEB_FREE_BLOCK(P(PEB_FREE_BLOCK)): pass
PEB_FREE_BLOCK._fields_ = [(PPEB_FREE_BLOCK, 'Next'), (ULONG, 'Size')]
class ... |
import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read max i... |
import os
import argparse
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex_boards.platforms import zcu104
from litex.soc.cores.clock import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.builder import *
from litex.soc.cores.led import LedChaser
from li... |
from JumpScale import j
from GitFactory import GitFactory
j.base.loader.makeAvailable(j, 'clients')
j.clients.git = GitFactory() |
def fat(n):
result = 1
while n > 0:
result = result * n
n = n - 1
return result
print("Fatorial de 3: ", fat(3)); |
import warnings
class DeprecatedCallableStr(str):
do_no_call_in_templates = True
def __new__(cls, value, *args, **kwargs):
return super(DeprecatedCallableStr, cls).__new__(cls, value)
def __init__(self, value, warning, warning_cls):
self.warning, self.warning_cls = warning, warning_cls
d... |
import sympy.core.cache
from sympy.core.compatibility import with_metaclass
from sympy.core.function import AppliedUndef, FunctionClass
from sympy.core.core import BasicMeta
from sympy.core.assumptions import ManagedProperties
from sympy.core.cache import cacheit
'''
Tensor('name') creates a tensor that does not take a... |
import smtplib
from datetime import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def prompt(prompt):
return raw_input(prompt).strip()
fromaddr = 'rpi@hilpisch.com' # prompt("From: ")
toaddrs = 'yves@hilpisch.com' # prompt("To: ")
subject = 'Security Alert.' # prompt("S... |
from actstream.models import Action
from django.test import TestCase
from cyidentity.cyfullcontact.tests.util import create_sample_contact_info
class FullContactActivityStreamTestCase(TestCase):
def test_contact_create(self):
contact_info = create_sample_contact_info()
action = Action.objects.actor(... |
import rtrsub
version = rtrsub.__version__
import codecs
import os
import sys
from os.path import abspath, dirname, join
from setuptools import setup, find_packages
here = abspath(dirname(__file__))
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip()... |
"""
Barycenters
===========
This example shows three methods to compute barycenters of time series.
For an overview over the available methods see the :mod:`tslearn.barycenters`
module.
*tslearn* provides three methods for calculating barycenters for a given set of
time series:
* *Euclidean barycenter* is simply the ar... |
import pump
import pump_bfd
class BFDSinkEx(pump_bfd.BFDSink):
def __init__(self, opts, spec, source_bucket, source_node,
source_map, sink_map, ctl, cur):
super(pump_bfd.BFDSink, self).__init__(opts, spec, source_bucket, source_node,
source_map, sink_ma... |
from __future__ import unicode_literals
from django.db import models, migrations
import django_google_dork.models
import model_utils.fields
import django.utils.timezone
class Migration(migrations.Migration):
replaces = [('django_google_dork', '0001_initial'), ('django_google_dork', '0002_auto_20141116_1551'), ('dja... |
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon Mechanical Turk"
prefix = "mechanicalturk"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super().__init__(prefix, action)
class ARN(BaseARN):
def __init__(self, resource: str = "", region: s... |
import logging
from rest_framework import generics
from ..mixins import CampaignMixin
from .serializers import CampaignSerializer
LOGGER = logging.getLogger(__name__)
class CampaignAPIView(CampaignMixin, generics.RetrieveDestroyAPIView):
"""
Retrieves a campaign
Retrieves the details of a ``Campaign``.
... |
import unittest
from nose2 import events, loader, session
from nose2.plugins.loader import functions
from nose2.tests._common import TestCase
class TestFunctionLoader(TestCase):
def setUp(self):
self.session = session.Session()
self.loader = loader.PluggableTestLoader(self.session)
self.plug... |
from .binary_search_tree import BinarySearchTree |
from pytest import mark
from django.urls import reverse
from email_template.models import Email
from assopy.models import AssopyUser
from conference.accounts import PRIVACY_POLICY_CHECKBOX, PRIVACY_POLICY_ERROR
from conference.models import CaptchaQuestion
from conference.users import RANDOM_USERNAME_LENGTH
from tests.... |
import mock
import os
from shutil import rmtree
from tempfile import mkdtemp
from django.test import TestCase
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test.utils import override_settings
from django.template.base im... |
from hippiehug import RedisStore, Tree, Leaf, Branch
import pytest
def test_evidence():
t = Tree()
# Test positive case
t.add(b"Hello", b"Hello")
t.add(b"World", b"World")
root, E = t.evidence(b"World")
assert len(E) == 2
store = dict((e.identity(), e) for e in E)
t2 = Tree(store... |
from flask import *
from pyZPL import *
from printLabel import printLabel
import xml.etree.ElementTree as ET
import os
app = Flask(__name__)
dn = os.path.dirname(os.path.realpath(__file__))+"/"
tree = ET.parse(dn+"pace.xml")
customElements = tree.findall(".//*[@id]")
customItems = []
for element in customElements:
... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0011_add-index-to-instance-uuid_and_xform_uuid'),
]
operations = [
migrations.AddField(
model_name='xform',
name='kpi_asset_uid',
field=models.Char... |
import copy
import mufsim.utils as util
import mufsim.gamedb as db
import mufsim.stackitems as si
from mufsim.errors import MufRuntimeError
from mufsim.insts.base import Instruction, instr
class InstPushItem(Instruction):
value = 0
def __init__(self, line, val):
self.value = val
super(InstPushIt... |
class MyRange(object):
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.idx < self.n:
val = self.idx
self.idx += 1
return val
else:
raise StopIteration()
myRange = My... |
import sys
import fileinput
def biconditionalElimination(s):
if type(s) is str:
return s
elif type(s) is list and s[0] == "iff":
return(["and",
["if",
biconditionalElimination(s[1]),
biconditionalElimination(s[2])],
["if",
... |
from mpi4py import MPI
from pySDC.helpers.stats_helper import filter_stats, sort_stats
from pySDC.implementations.controller_classes.controller_MPI import controller_MPI
from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right
from pySDC.implementations.problem_classes.HeatEquation_1... |
from django.test import TestCase
from addressbase.models import Address
from addressbase.tests.factories import AddressFactory, UprnToCouncilFactory
class TestAddressFactory(TestCase):
def test_address_factory(self):
address = AddressFactory()
self.assertEqual(len(address.uprn), 9)
self.asse... |
""" Test functions for stats module
"""
import warnings
import re
import sys
import pickle
import os
from numpy.testing import (assert_equal, assert_array_equal,
assert_almost_equal, assert_array_almost_equal,
assert_allclose, assert_, assert_warns,
... |
from __future__ import absolute_import, unicode_literals, division, print_function
from . import model_base
__all__ = ['PhotomModelB4']
class PhotomModelB4(model_base.DataModel):
"""
A data model for photom reference files.
"""
schema_url = "photomb4.schema.yaml"
def __init__(self, init=None, phot_t... |
"""
* Copyright (c) 2012-2017, Nic McDonald and Adriana Flores
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, t... |
import pytest
from collections import namedtuple
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_less
from skopt import dummy_minimize
from skopt.benchmarks import bench1
from skopt.callbacks import TimerCallback
from skopt.callbacks import DeltaYStopper
@pytest.mark.fast_test
de... |
import os
import sys
import re
from bento.compat \
import \
inspect as compat_inspect
from bento.commands.core \
import \
command
SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]")
__HOOK_REGISTRY = {}
__PRE_HOOK_REGISTRY = {}
__POST_HOOK_REGISTRY = {}
__COMMANDS_OVERRIDE = {}
__INIT_FUNCS = {}
def add... |
import os
import nose
import django
NAME = os.path.basename(os.path.dirname(__file__))
ROOT = os.path.abspath(os.path.dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = 'fake_settings'
os.environ['PYTHONPATH'] = os.pathsep.join([ROOT,
os.path.join(ROOT, 'examples')])
i... |
"""Package contenant la commande 'chercherbois'."""
from random import random, randint, choice
from math import sqrt
from primaires.interpreteur.commande.commande import Commande
from primaires.perso.exceptions.stat import DepassementStat
class CmdChercherBois(Commande):
"""Commande 'chercherbois'"""
def __init... |
from __future__ import absolute_import, unicode_literals
import pickle
from io import StringIO, BytesIO
from kombu import version_info_t
from kombu import utils
from kombu.five import python_2_unicode_compatible
from kombu.utils.text import version_string_as_tuple
from kombu.tests.case import Case, Mock, patch, mock
@p... |
'''Unit tests for the admin template gatherer.'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
import StringIO
import tempfile
import unittest
from grit.gather import admin_template
from grit import util
from grit import grd_reader
from grit impo... |
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
testinfo = "s, t 3, s, t 6.1, s, q"
tags = "MoveBy"
import cocos
from cocos.director import director
from cocos.actions import MoveBy
from cocos.sprite import Sprite
import pyglet
class TestLayer(cocos.layer.Layer):
def __init__... |
import subprocess
from devtoolslib.shell import Shell
from devtoolslib import http_server
class LinuxShell(Shell):
"""Wrapper around Mojo shell running on Linux.
Args:
executable_path: path to the shell binary
command_prefix: optional list of arguments to prepend to the shell command,
allowing e.g. ... |
DEPS = [
'recipe_engine/buildbucket',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'recipe_engine/step',
'git',
]
def RunSteps(api):
url = 'https://chromium.googlesource.com/chromium/src.git'
# git.checkout can optionall... |
from django.test import TestCase
import time
from .models import SimpleTree, MPTTTree, TBMP, TBNS
def timeit(method):
""" Measure time of method's execution.
"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '\n%r: %2.2f sec' % \... |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('voting', '0002_auto_20150813_2010'),
]
operations = [
migrat... |
import uuid
import os
import shutil
import urlparse
import re
import hashlib
from lxml import html
from PIL import Image, ImageFile
from django.conf import settings
import views
ImageFile.MAXBLOCKS = 10000000
def match_or_none(string, rx):
"""
Tries to match a regular expression and returns an integer if it can... |
from django.conf import settings
from site_news.models import SiteNewsItem
def site_news(request):
"""
Inserts the currently active news items into the template context.
This ignores MAX_SITE_NEWS_ITEMS.
"""
# Grab all active items in proper date/time range.
items = SiteNewsItem.current_and_acti... |
import logging
import re
import importlib
import django
import six
from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.module_loading import import_string
from django.utils.html import conditional_escape
fro... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kitchen_sink.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import logging
from . import SubprocessHook
logger = logging.getLogger("barython")
class PulseAudioHook(SubprocessHook):
"""
Listen on pulseaudio events with pactl
"""
def __init__(self, cmd=["pactl", "subscribe", "-n", "barython"],
*args, **kwargs):
super().__init__(*args, **kw... |
""" Common filesystem operations """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import stat
import time
import errno
import ntpath
import shutil
import tempfile
import warnings
import posixpath
import contextlib
import subpro... |
from sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("SVR_rbf" , "freidman1" , "db2") |
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL... |
from __future__ import absolute_import
import sys
import os
import imp
import ctypes
if sys.platform == 'win32':
basepath = imp.find_module('numpy')[1]
ctypes.CDLL(os.path.join(basepath, 'core', 'libmmd.dll'))
ctypes.CDLL(os.path.join(basepath, 'core', 'libifcoremd.dll'))
from .adadelta import Adadelta
from... |
import copy
import numpy
import multiprocessing
import scipy
from scipy import special, interpolate, integrate
if int(scipy.__version__.split('.')[1]) < 10: #pragma: no cover
from scipy.maxentropy import logsumexp
else:
from scipy.misc import logsumexp
from galpy.orbit import Orbit
from galpy.util import bovy_c... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
class Location(models.Model):
address = models.CharField(blank=True)
latitude = models.DecimalField(max_digits=10, decimal_places=6)
longitude = models.DecimalField(max_digits=10, decimal_pl... |
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals, absolute_import
import json
import pytest
import requests
import requests.exceptions
f... |
import shutil
import os
import jinja2
import string
import subprocess
import re
from xen.provisioning.HdManager import HdManager
from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEBIA... |
"""
This module implements atom/bond/structure-wise descriptor calculated from
pretrained megnet model
"""
import os
from typing import Dict, Union
import numpy as np
from tensorflow.keras.models import Model
from megnet.models import GraphModel, MEGNetModel
from megnet.utils.typing import StructureOrMolecule
DEFAULT_M... |
from traitlets import Unicode, Bool
from textwrap import dedent
from .. import utils
from . import NbGraderPreprocessor
class ClearSolutions(NbGraderPreprocessor):
code_stub = Unicode(
"# YOUR CODE HERE\nraise NotImplementedError()",
config=True,
help="The code snippet that will replace code... |
import re
import operator
import os
BASE_DIR = (os.path.dirname(os.path.abspath(__file__)))
debug = False
def is_number(s):
try:
float(s) if '.' in s else int(s)
return True
except ValueError:
return False
def load_stop_words(stop_word_file):
"""
Utility function to load stop wor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.