code stringlengths 1 199k |
|---|
from datetime import datetime, timedelta
from typing import List, Optional
from analytics.lib.counts import CountStat
from zerver.lib.timestamp import floor_to_day, floor_to_hour, verify_UTC
def time_range(start: datetime, end: datetime, frequency: str,
min_length: Optional[int]) -> List[datetime]:
v... |
from webob import exc
from nova.api.openstack.compute.contrib import baremetal_nodes
from nova import context
from nova import exception
from nova import test
from nova.virt.baremetal import db
class FakeRequest(object):
def __init__(self, context):
self.environ = {"nova.context": context}
class BareMetalNo... |
import contextlib
from oslo_config import cfg
from oslo_db.sqlalchemy import session
from sqlalchemy import exc
_FACADE = None
MAX_RETRIES = 10
def _create_facade_lazily():
global _FACADE
if _FACADE is None:
_FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True)
return _FACADE
def get_... |
"""Utilities for accessing Python generic type annotations (typing.*)."""
import collections.abc
import typing
def is_generic_union(tp):
"""Returns true if `tp` is a parameterized typing.Union value."""
return (tp is not typing.Union and
getattr(tp, '__origin__', None) is typing.Union)
def is_generic_tupl... |
"""Tests for the cost analyzer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import meta_graph
from tensorflow.... |
import wx
from canvasSubject import canvasSubject
from canvasObject import *
class canvas(wx.wxScrolledWindow, canvasSubject):
def __init__(self, parent, id = -1, size = wx.wxDefaultSize):
# parent 1 ctor
wx.wxScrolledWindow.__init__(self, parent, id, wx.wxPoint(0, 0), size,
... |
from __future__ import division # Omit for Python 3.x
import matplotlib.pyplot as plt
from quantecon.models import LucasTree
fig, ax = plt.subplots()
tree = LucasTree(gamma=2, beta=0.95, alpha=0.90, sigma=0.1)
grid, price_vals = tree.grid, tree.compute_lt_price()
ax.plot(grid, price_vals, lw=2, alpha=0.7, label=r'$p^*... |
import numpy as np
from .utils import trig_sum
def lombscargle_fastchi2(t, y, dy, f0, df, Nf, normalization='standard',
fit_mean=True, center_data=True, nterms=1,
use_fft=True, trig_sum_kwds=None):
"""Lomb-Scargle Periodogram
This implements a fast chi-squared p... |
try:
# Python 2.7
from collections import OrderedDict
except:
# Python 2.6
from gluon.contrib.simplejson.ordered_dict import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Settings for an outbreak of an infectious disease, such as Ebola:
... |
from __future__ import unicode_literals
import unittest
class TestEmailCampaign(unittest.TestCase):
pass |
from gnuradio import gr, eng_notation
from gnuradio.eng_option import eng_option
from optparse import OptionParser
import sys
master_clock = 100e6
class my_top_block(gr.top_block):
def __init__(self):
gr.top_block.__init__(self)
parser = OptionParser(option_class=eng_option)
parser.add_optio... |
"""Miscellaneous utility functions and classes."""
from __future__ import absolute_import, print_function
import errno
import os
import pipes
import pkgutil
import shutil
import subprocess
import re
import sys
import time
def is_shippable():
"""
:rtype: bool
"""
return os.environ.get('SHIPPABLE') == 'tr... |
from ..internal.XFSAccount import XFSAccount
class SharebeastCom(XFSAccount):
__name__ = "SharebeastCom"
__type__ = "account"
__version__ = "0.06"
__status__ = "testing"
__description__ = """Sharebeast.com account plugin"""
__license__ = "GPLv3"
__authors__ = [("Walter Purcaro", "vuolter@gma... |
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from struct import unpack_from
from collections import OrderedDict
from calibre.utils.... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('sota', '0010_auto_20141011_0250'),
]
operations = [
migrations.RemoveField(
model_name='message',
name='log_retry',
),
... |
r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... |
"""Imports unittest as a replacement for testing.pybase.googletest."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import itertools
import os
import sys
import tempfile
from unittest import *
from tensorflow.python.platform import benchmark... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'header_image14.xlsx'
... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'image23.xlsx'
test_d... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_up_down_bars02.xlsx'
... |
from PyQt4.Qt import *
from numpy import *
import Avogadro
import sys
import unittest
from util import *
class TestCamera(unittest.TestCase):
def setUp(self):
# create the GLWidget and load the default engines
self.glwidget = Avogadro.GLWidget()
self.glwidget.loadDefaultEngines()
self.molecule = Avoga... |
import nest
import numpy
import unittest
@nest.ll_api.check_stack
class QuantalSTPSynapseTestCase(unittest.TestCase):
"""Compare quantal_stp_synapse with its deterministic equivalent."""
def test_QuantalSTPSynapse(self):
"""Compare quantal_stp_synapse with its deterministic equivalent"""
nest.Re... |
"""Build wheels/sdists by installing build deps to a temporary environment.
"""
import os
import logging
from pip._vendor import pytoml
import shutil
from subprocess import check_call
import sys
from sysconfig import get_paths
from tempfile import mkdtemp
from .wrappers import Pep517HookCaller
log = logging.getLogger(_... |
from ansible import constants as C
from ansible.cli import CLI
from ansible.errors import AnsibleOptionsError
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.inventory import Inventory
from ansible.parsing import DataLoader
from ansible.parsing.splitter import parse_kv
from ansible.playboo... |
"""
check_texi_refs.py
Interactive Texinfo cross-references checking and fixing tool
"""
import sys
import re
import os
import optparse
import imp
outdir = 'out-www'
log = sys.stderr
stdout = sys.stdout
file_not_found = 'file not found in include path'
warn_not_fixed = '*** Warning: this broken x-ref has not been fixed... |
"""
The host matching URL Map seems to be matching hosts well but fails in
generating/building URLs when there are same endpoints.
This patch makes strict host matching to ensure nothing skips host
matching.
Also see: https://github.com/mitsuhiko/werkzeug/issues/488
:copyright: (c) 2014 by Openl... |
"""
Custom forms-related types
"""
from django.core.exceptions import ValidationError
from django.forms import Field, MultipleHiddenInput
class MultiValueField(Field):
"""
Field class that supports a set of values for a single form field.
The field input can be specified as:
1. a comma-separated-lis... |
"""
Generic GeoRSS events service.
Retrieves current events (typically incidents or alerts) in GeoRSS format, and
shows information on events filtered by distance to the HA instance's location
and grouped by category.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/c... |
from __future__ import unicode_literals
import json
from six.moves.urllib.parse import urlparse, parse_qs
from moto.core.responses import _TemplateEnvironmentMixin
from .models import glacier_backends
from .utils import region_from_glacier_url, vault_from_glacier_url
class GlacierResponse(_TemplateEnvironmentMixin):
... |
import abc
import logging
import operator
import os
import subprocess
import tempfile
from luigi import six
import luigi
import luigi.contrib.hadoop
from luigi.target import FileAlreadyExists, FileSystemTarget
from luigi.task import flatten
if six.PY3:
unicode = str
logger = logging.getLogger('luigi-interface')
cla... |
(dp0
VGaleon 2.0.4
p1
(dp2
S'summary_display'
p3
S'117/149'
p4
sS'total_runs'
p5
L1L
sS'summary_score'
p6
I79
sS'results'
p7
(dp8
S'unapply'
p9
(dp10
S'score'
p11
I65
sS'raw_score'
p12
I0
sS'display'
p13
S'17/26'
p14
ssS'apply'
p15
(dp16
g11
I83
sg12
I0
sg13
S'34/41'
p17
ssS'change'
p18
(dp19
g11
I41
sg12
I0
sg13
S'7/1... |
import abc
from nova import keymgr
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class VolumeEncryptor(object):
"""Base class to support encrypted volumes.
A VolumeEncryptor provides hooks for attaching and detaching volumes, which
are called immediately prior to attachi... |
from datetime import datetime
import datetime as dt
import os
import warnings
import nose
import struct
import sys
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
from pandas.compat import iterkeys
from pandas.core.frame import DataFrame, Series
from pandas.core.common import is_catego... |
import numpy as np
from numpy.testing import assert_array_equal, assert_allclose
import pytest
from sklearn.ensemble._hist_gradient_boosting.binning import (
_BinMapper,
_find_binning_thresholds,
_map_to_bins
)
from sklearn.ensemble._hist_gradient_boosting.common import X_DTYPE
from sklearn.ensemble._hist_g... |
"""
This packages contains modules for clustering events
"""
from .eventmgr import *
from .veto import *
from .coinc import * |
"""
Run ExpGenerator to generate the description and permutations file for a
spatial classification experiment
"""
import os
import json
from optparse import OptionParser
from nupic.swarming.exp_generator.experiment_generator import expGenerator
if __name__ == '__main__':
helpString = \
"""%prog [options] searchDef... |
"""Classes and functions for building TensorFlow graphs.
@@Graph
@@Operation
@@Tensor
@@DType
@@as_dtype
@@device
@@container
@@name_scope
@@control_dependencies
@@convert_to_tensor
@@convert_to_tensor_or_indexed_slices
@@get_default_graph
@@reset_default_graph
@@import_graph_def
@@load_file_system_library
@@load_op_li... |
"""Jobs for recommendations."""
__author__ = 'Xinyu Wu'
import ast
from core import jobs
from core.platform import models
(exp_models, recommendations_models,) = models.Registry.import_models([
models.NAMES.exploration, models.NAMES.recommendations])
class ExplorationRecommendationsRealtimeModel(
jobs.BaseR... |
import json
from telemetry.util import perf_tests_helper
from telemetry import value as value_module
from telemetry.value import histogram_util
class HistogramValueBucket(object):
def __init__(self, low, high, count=0):
self.low = low
self.high = high
self.count = count
def AsDict(self):
return {
... |
"""Argument-less script to select what to run on the buildbots."""
import filecmp
import os
import shutil
import subprocess
import sys
if sys.platform in ['win32', 'cygwin']:
EXE_SUFFIX = '.exe'
else:
EXE_SUFFIX = ''
BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__))
TRUNK_DIR = os.path.dirname(BUILDBOT_DIR)... |
"""
Copyright 2008-2011 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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... |
import math
import numpy
from collections import Counter, defaultdict
from htmresearch.frameworks.nlp.classification_model import ClassificationModel
class ClassificationModelTraditional(ClassificationModel):
"""
Class to run the survey response classification task with TFIDF
"""
def __init__(self, verbosity=1,... |
from . import models
from . import report |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import ExtractorError
from .screenwavemedia import ScreenwaveMediaIE
class CinemassacreIE(InfoExtractor):
_VALID_URL = 'https?://(?:www\.)?cinemassacre\.com/(?P<date_y>[0-9]{4})/(?P<date_m>[0-9]{2})/(?P<date_d>[0-9]{2})... |
"""An analysis that determines the reach of a function definition.
A function definition is said to reach a statement if that function may exist
(and therefore may be called) when that statement executes.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
im... |
"""The Extended Volumes API extension."""
import webob
from webob import exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas.v3 import extended_volumes
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
fro... |
import os
import re
import sys
import unittest2
class TestDiscovery(unittest2.TestCase):
# Heavily mocked tests so I can avoid hitting the filesystem
def test_get_name_from_path(self):
loader = unittest2.TestLoader()
loader._top_level_dir = '/foo'
name = loader._get_name_from_path('/foo/... |
import io
import random
import struct
import unittest
import common
import config
import net_crypto
import mle
import network_data
from ipaddress import ip_address
def any_address():
return random.getrandbits(16)
def any_receiver():
return random.getrandbits(1)
def any_secure():
return random.getrandbits(1)... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_compute_region_disk_info
description:
- Gather info for GCP RegionDisk
short_description: Gather in... |
_qwer_tyuio_asdf_gh = 123
def qwer_tyuio_asdf_gh():
print(<caret>) |
if (<warning descr="Python versions 2.7, 3.5, 3.6, 3.7 do not support assignment expressions">match := pattern.search(data)</warning>) is not None:
pass
while <warning descr="Python versions 2.7, 3.5, 3.6, 3.7 do not support assignment expressions">chunk := file.read(8192)</warning>:
pass
[<warning descr="Python... |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'functional_test.views.home', name='home'),
url(r'^login/(?P<provider_name>\w+)', 'functional_test.views.login', name='login'),
) |
"""
Custom element classes related to text runs (CT_R).
"""
from ..ns import qn
from ..simpletypes import ST_BrClear, ST_BrType
from ..xmlchemy import (
BaseOxmlElement, OptionalAttribute, ZeroOrMore, ZeroOrOne
)
class CT_Br(BaseOxmlElement):
"""
``<w:br>`` element, indicating a line, page, or column break ... |
import os,sys,string,re,time,getopt
import xml.sax
import xml.sax.handler
import xml.sax.xmlreader
import StringIO
class SvnHandler(xml.sax.handler.ContentHandler):
def __init__(self):
self.inUrl = 0
self.inDate = 0
self.mapping = {}
def startElement(self, name, attributes):
if n... |
from peacock.Input.BlockEditor import BlockEditor
from PyQt5.QtWidgets import QMessageBox, QApplication
from peacock.Input.ExecutableInfo import ExecutableInfo
from peacock.Input.InputTree import InputTree
from peacock.Input.ParamsTable import ParamsTable
from peacock.Input.ParamsByGroup import ParamsByGroup
from peaco... |
"""
Module for starting a process object using os.fork() or CreateProcess()
multiprocessing/forking.py
Copyright (c) 2006-2008, R Oudkerk
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
... |
"""The test for the zodiac sensor platform."""
from datetime import datetime
from unittest.mock import patch
import pytest
from homeassistant.components.zodiac.const import (
ATTR_ELEMENT,
ATTR_MODALITY,
DOMAIN,
ELEMENT_EARTH,
ELEMENT_FIRE,
ELEMENT_WATER,
MODALITY_CARDINAL,
MODALITY_FIXE... |
from __future__ import print_function
from airflow.exceptions import AirflowException
from airflow import configuration as conf
from importlib import import_module
from airflow.utils.log.logging_mixin import LoggingMixin
api_auth = None
log = LoggingMixin().log
def load_auth():
auth_backend = 'airflow.api.auth.back... |
from __future__ import print_function, division
from sympy.core import Basic, Integer, Tuple, Dict, S, sympify
from sympy.core.sympify import converter as sympify_converter
from sympy.matrices.matrices import MatrixBase
from sympy.matrices.dense import DenseMatrix
from sympy.matrices.sparse import SparseMatrix, Mutable... |
"""
Daily cleanup job.
Can be run as a cronjob to clean out old data from the database (only expired
sessions at the moment).
"""
from django_extensions.management.jobs import DailyJob
class Job(DailyJob):
help = "Cache (db) cleanup Job"
def execute(self):
from django.conf import settings
import... |
"""
Tests for cinder.api.contrib.quota_classes.py
"""
import mock
from lxml import etree
import webob.exc
from cinder.api.contrib import quota_classes
from cinder import context
from cinder import quota
from cinder import test
from cinder.volume import volume_types
QUOTAS = quota.QUOTAS
def make_body(root=True, gigabyt... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: bigip_gtm_facts
short_description: Collect facts from F5 BIG-IP GTM devices.
description:
- Collect facts from F5 BIG-IP GTM devices.
version_added... |
from . import log_forwarded_for_ip_installed |
"""Define tflite op hints (intrinsic operations).
This essentially allows defining a TensorFlow API for tflite operations in
Python with hints on how they are represented in TensorFlow Lite. This basically
is a form of tflite intrinsic. It wraps a subpart of a TensorFlow execution
graph and is useful for LSTMs and othe... |
from __future__ import absolute_import, unicode_literals
import contextlib
import logging
from mopidy import exceptions
from mopidy.internal import validation
logger = logging.getLogger(__name__)
@contextlib.contextmanager
def _mixer_error_handling(mixer):
try:
yield
except exceptions.ValidationError as... |
f0 = lambda x: ber(0,x)
f1 = lambda x: bei(0,x)
f2 = lambda x: ber(2,x)
f3 = lambda x: bei(2,x)
plot([f0,f1,f2,f3],[0,10],[-10,10]) |
"""Actions required for CA enrolment."""
from grr.client import actions
class SaveCert(actions.ActionPlugin):
"""Accepts a signed certificate from the server and saves it to disk."""
def Run(self, args):
"""Receive the certificate and store it to disk."""
# We dont really care about the certificate any more... |
"""Estimator regression tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import sys
if hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags'):
import ctypes
sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL)
fr... |
import oauth
from models import Nonce, Token, Consumer
from models import generate_random, VERIFIER_SIZE
class DataStore(oauth.OAuthDataStore):
"""Layer between Python OAuth and Django database."""
def __init__(self, oauth_request):
self.signature = oauth_request.parameters.get('oauth_signature', None)
... |
import csv
from decimal import Decimal
from mkt.prices.models import Price, PriceCurrency
def update(tiers):
"""
Updates the prices and price currency objects based on the tiers.
Tiers should be a list containing a dictionary of currency / value pairs.
The value of US is required so that we can look up ... |
"""Newton-CG trust-region optimization."""
from __future__ import division, print_function, absolute_import
import math
import numpy as np
import scipy.linalg
from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
__all__ = []
def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hessp=Non... |
__all__ = ("lookupWsSupport",)
import re
UA_FIREFOX = re.compile(".*Firefox/(\d*).*")
UA_CHROME = re.compile(".*Chrome/(\d*).*")
UA_CHROMEFRAME = re.compile(".*chromeframe/(\d*).*")
UA_WEBKIT = re.compile(".*AppleWebKit/([0-9+\.]*)\w*.*")
UA_WEBOS = re.compile(".*webos/([0-9+\.]*)\w*.*")
UA_HPWEBOS = re.compile(".*hpwO... |
class Emitter(object):
pass |
"""
Tests for L{twisted.words.xmpproutertap}.
"""
from twisted.application import internet
from twisted.trial import unittest
from twisted.words import xmpproutertap as tap
from twisted.words.protocols.jabber import component
class XMPPRouterTapTests(unittest.TestCase):
def test_port(self):
"""
The ... |
"""A module to add gn support to cr."""
import cr
import os
import re
GN_ARG_PREFIX = 'GN_ARG_'
class GnPrepareOut(cr.PrepareOut):
"""A prepare action that runs gn whenever you select an output directory."""
ACTIVE = cr.Config.From(
GN_ARG_is_component_build='true',
)
@property
def priority(self):
r... |
__author__ = 'bromix'
class AbstractSystemVersion(object):
def __init__(self, version, name):
if not isinstance(version, tuple):
self._version = (0, 0, 0, 0)
else:
self._version = version
pass
if not name or not isinstance(name, basestring):
se... |
import socket
import math
from struct import pack, unpack
from socket import inet_ntoa
from threading import Timer, Thread
from time import sleep, time
from hashlib import sha1
from simdht_worker import entropy
from bencode import bencode, bdecode
BT_PROTOCOL = "BitTorrent protocol"
BT_MSG_ID = 20
EXT_HANDSHAKE_ID = 0
... |
from pybrain.rl.explorers.discrete.__init__ import *
from pybrain.rl.explorers.continuous.__init__ import * |
"""Helper class to quickly write a loop over all standard input files.
Typical use is:
import fileinput
for line in fileinput.input():
process(line)
This iterates over the lines of all files listed in sys.argv[1:],
defaulting to sys.stdin if the list is empty. If a filename is '-' it
is also replaced b... |
"""Generate a dot graph from the output of several profilers."""
__author__ = "Jose Fonseca"
__version__ = "1.0"
import sys
import math
import os.path
import re
import textwrap
import optparse
import xml.parsers.expat
try:
# Debugging helper module
import debug
except ImportError:
pass
def times(x):
ret... |
"""Model wrapper class for performing inference with a ShowAndTellModel."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from im2txt import show_and_tell_model
from im2txt.inference_utils import inference_wrapper_base
class InferenceWrapper(inference_wrapp... |
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.upd... |
import rope.base.codeanalyze
import rope.base.evaluate
from rope.base import worder, exceptions, utils
from rope.base.codeanalyze import ArrayLinesAdapter, LogicalLineFinder
class FixSyntax(object):
def __init__(self, pycore, code, resource, maxfixes=1):
self.pycore = pycore
self.code = code
... |
import os
import sys
curdir = os.path.dirname(os.path.abspath(__file__))
os.chdir(curdir)
sys.path.insert(0, '../')
import unittest
import re
def get_ceph_info(info):
# pattern for ceph information
pattern = re.compile(r'\bclient io .*')
ceph_info = pattern.search(info).group()
# pattern to get number
... |
from __future__ import unicode_literals
from django.contrib import admin
from taggit.models import Tag, TaggedItem
class TaggedItemInline(admin.StackedInline):
model = TaggedItem
class TagAdmin(admin.ModelAdmin):
inlines = [
TaggedItemInline
]
list_display = ["name", "slug"]
ordering = ["nam... |
from __future__ import unicode_literals
from django.db.transaction import atomic
class Migration(object):
"""
The base class for all migrations.
Migration files will import this from django.db.migrations.Migration
and subclass it as a class called Migration. It will have one or more
of the following... |
"""Beautiful Soup bonus library: Unicode, Dammit
This class forces XML data into a standard format (usually to UTF-8 or
Unicode). It is heavily based on code from Mark Pilgrim's Universal
Feed Parser. It does not rewrite the XML or HTML to reflect a new
encoding; that's the tree builder's job.
"""
import codecs
from h... |
"""
A software OpenFlow switch
"""
"""
TODO
----
* Don't reply to HELLOs -- just send one on connect
* Pass raw OFP packet to rx handlers as well as parsed
* Once previous is done, use raw OFP for error data when appropriate
* Check self.features to see if various features/actions are enabled,
and act appropriately i... |
"""Build a language detector model
The goal of this exercise is to train a linear classifier on text features
that represent sequences of up to 3 consecutive characters so as to be
recognize natural languages by using the frequencies of short character
sequences as 'fingerprints'.
"""
import sys
from sklearn.feature_ex... |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
"""Tests for predictor.predictor_factories."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.predictor import predictor_factories
from tensorflow.contrib.predictor import testing_common
from tensorflow.core.protobuf import config_pb2... |
from __future__ import absolute_import
from jedi._compatibility import is_py3
from token import *
COMMENT = N_TOKENS
tok_name[COMMENT] = 'COMMENT'
N_TOKENS += 1
NL = N_TOKENS
tok_name[NL] = 'NL'
N_TOKENS += 1
if is_py3:
BACKQUOTE = N_TOKENS
tok_name[BACKQUOTE] = 'BACKQUOTE'
N_TOKENS += 1
else:
RARROW = ... |
"""
Benchmarks of isotonic regression performance.
We generate a synthetic dataset of size 10^n, for n in [min, max], and
examine the time taken to run isotonic regression over the dataset.
The timings are then output to stdout, or visualized on a log-log scale
with matplotlib.
This allows the scaling of the algorithm ... |
"""Windows service. Requires pywin32."""
import os
import win32api
import win32con
import win32event
import win32service
import win32serviceutil
from cherrypy.process import wspbus, plugins
class ConsoleCtrlHandler(plugins.SimplePlugin):
"""A WSPBus plugin for handling Win32 console events (like Ctrl-C)."""
def... |
"""
Tests for instructor.basic
"""
import datetime
import json
import pytz
from mock import MagicMock, Mock, patch
from django.core.urlresolvers import reverse
from django.db.models import Q
from course_modes.models import CourseMode
from courseware.tests.factories import InstructorFactory
from instructor_analytics.bas... |
"""Sparse6
Read and write graphs in sparse6 format.
Format
------
"graph6 and sparse6 are formats for storing undirected graphs in a
compact manner, using only printable ASCII characters. Files in these
formats have text type and contain one line per graph."
See http://cs.anu.edu.au/~bdm/data/formats.txt for details.
"... |
import numpy as np
from bokeh.plotting import figure, show, output_file, vplot
from bokeh.models import BoxSelectTool
N = 100
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
output_file("scatter_selection.html", title="scatter_selection.py example")
TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select"
p1 = figure(title... |
"""Tests for manual component.""" |
import sys, os, random
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import utils
r = utils.import_python_driver()
class Workload:
def __init__(self, options):
self.db = options["db"]
self.table = options["table"]
self.hosts = options[... |
from glanceclient.v1 import images
from openstack_dashboard.test.test_data import utils
class Namespace(dict):
def __repr__(self):
return "<Namespace %s>" % self._info
def __init__(self, info):
super(Namespace, self).__init__()
self.__dict__.update(info)
self.update(info)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.