content string |
|---|
import redis
import click
import boto3
import botocore
import backoff
from itertools import zip_longest
max_tries = 5
class RedisWrapper(object):
def __init__(self, *args, **kwargs):
self.redis = redis.StrictRedis(*args, **kwargs)
@backoff.on_exception(backoff.expo,
(redis.... |
# $Id: get-footprint.py 1352 2007-06-08 01:41:25Z bennylp $
#
# This file is used to generate PJSIP/PJMEDIA footprint report.
# To use this file, just run it in pjsip-apps/build directory, to
# produce footprint.txt and footprint.htm report files.
#
import os
import sys
import string
import time
compile_flags1 = [
... |
"""
Unit tests for getting the list of courses and the course outline.
"""
import json
import lxml
import datetime
from contentstore.tests.utils import CourseTestCase
from contentstore.utils import reverse_course_url, add_instructor
from contentstore.views.access import has_course_access
from contentstore.views.course... |
import sys
import requests
from bs4 import BeautifulSoup
def enumusers(url,p):
r = requests.get(url + '/?attachment_id=' + str(p), allow_redirects=False)
if r.status_code == 200:
soup = BeautifulSoup(r.text)
div=soup.find('div',{'class':'attachment'})
p ... |
"""Policy Engine For Nova."""
import copy
import re
import sys
from oslo_config import cfg
from oslo_log import log as logging
from oslo_policy import policy
from oslo_utils import excutils
import six
from nova import exception
from nova.i18n import _LE, _LW
from nova import policies
CONF = cfg.CONF
LOG = logging.g... |
import pygame
import numpy as np
import time
import transforms3d.euler as euler
from amc_parser import *
from OpenGL.GL import *
from OpenGL.GLU import *
class Viewer:
def __init__(self, joints=None, motions=None):
"""
Display motion sequence in 3D.
Parameter
---------
joints: Dict returned fr... |
from PyQt4 import QtCore, QtGui
import sys
from scene import *
from view import *
class MainWindow(QtGui.QMainWindow):
interval = 40
def __init__(self, *args, **kwargs):
QtGui.QMainWindow.__init__(self, *args, **kwargs)
self.scene = QtGui.QGraphicsScene(self)
self.resize(width + 20, self.scene.height + 20)
... |
"""
Japanese-language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
# fixed: language-dependent
'author': '著者',
'authors': '著者',
'organization': '組織',
'address': '住所',
'contact': '連絡先',
'version': 'バージョン',
'revis... |
from oslo_serialization import jsonutils as json
import six
from sahara.plugins.cdh.client import role_config_groups
from sahara.plugins.cdh.client import roles
from sahara.plugins.cdh.client import types
SERVICES_PATH = "/clusters/%s/services"
SERVICE_PATH = "/clusters/%s/services/%s"
ROLETYPES_CFG_KEY = 'roleTypeCo... |
"""The tests for Philips TV device triggers."""
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.philips_js.const import DOMAIN
from homeassistant.setup import async_setup_component
from tests.common import (
assert_lists_same,
async_get_device_automations,
... |
import codecs
import re
mdFileUrl = 'test.md'
outData = []
htmlStart = '''<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
<link rel='stylesheet' href='markflip.css' type='text/css' />
<title>Generated by MarkFlip</title>
</head>
<body>
'''
htmlEnd = '... |
def test_context_sets_correct_context_and_returns(driver):
def get_context():
return driver.execute('GET_CONTEXT').pop('value')
assert get_context() == driver.CONTEXT_CONTENT
with driver.context(driver.CONTEXT_CHROME):
assert get_context() == driver.CONTEXT_CHROME
assert get_context() ... |
ur"""<rst>
Plugin for the Auvisio PC-Remote.
"""
import eg
eg.RegisterPlugin(
name = "WinUSB Test",
author = "Bitmonster",
version = "1.0.0",
kind = "remote",
guid = "{68EA5E13-712D-47C7-AB95-D4B8707D8D33}",
description = __doc__,
)
from math import atan2, pi
class WinUsbTest(eg.PluginBase)... |
yeslist = [
"yes",
"yasss",
"yea",
"yeah",
"yep",
"yeppers",
"sure",
"yizzir",
"sounds good",
"let's do it",
"no problem",
"let's go",
"absolutely",
"hell yea",
"hell yes",
"ok",
"a little",
"good",
"great",
"of course",
"alright",
... |
from contextlib import contextmanager
import imp
import os.path
from test import support
import unittest
import sys
CASE_INSENSITIVE_FS = True
# Windows is the only OS that is *always* case-insensitive
# (OS X *can* be case-sensitive).
if sys.platform not in ('win32', 'cygwin'):
changed_name = __file__.upper()
... |
__all__ = ["StorageLevel"]
class StorageLevel(object):
"""
Flags for controlling the storage of an RDD. Each StorageLevel records whether to use memory,
whether to drop the RDD to disk if it falls out of memory, whether to keep the data in memory
in a serialized format, and whether to replicate the R... |
import unittest
from ansible.modules.cloud.google.gcp_url_map import _build_path_matchers, _build_url_map_dict
class TestGCPUrlMap(unittest.TestCase):
"""Unit tests for gcp_url_map module."""
params_dict = {
'url_map_name': 'foo_url_map_name',
'description': 'foo_url_map description',
... |
from django.test import SimpleTestCase
from django.utils import translation
from ...utils import setup
class I18nFiltersTests(SimpleTestCase):
libraries = {
'custom': 'template_tests.templatetags.custom',
'i18n': 'django.templatetags.i18n',
}
@setup({'i18n32': '{% load i18n %}{{ "hu"|lan... |
import sys
from yum.plugins import TYPE_CORE
from yum.plugins import PluginYumExit
requires_api_version = '2.6'
plugin_type = (TYPE_CORE,)
def _checkPackage(pkg, property, author, forbid):
if getattr(pkg, property) in forbid:
return True
if author is not None:
found = filter(lambda x: getatt... |
# -*- coding: utf-8 -*-
"""
flask.testsuite.views
~~~~~~~~~~~~~~~~~~~~~
Pluggable views.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import flask
import flask.views
import unittest
from flask.testsuite import FlaskTestCase
from werkzeug.http import par... |
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from lxml import etree
from ..treebuilders.etree import tag_regexp
from gettext import gettext
_ = gettext
from . import _base
from .. import ihatexml
def ensure_str(s):
if s is None:
return None
... |
# -*- coding: utf-8 -*-
r"""
werkzeug.contrib.iterio
~~~~~~~~~~~~~~~~~~~~~~~
This module implements a :class:`IterIO` that converts an iterator into
a stream object and the other way round. Converting streams into
iterators requires the `greenlet`_ module.
To convert an iterator into a stream... |
import oslo_config.cfg
import oslo_utils.importutils
_compute_opts = [
oslo_config.cfg.StrOpt('compute_api_class',
default='manila.compute.nova.API',
help='The full class name of the '
'Compute API class to use.'),
]
oslo_confi... |
import pytest
from pyshell.utils.exception import KeyStoreException
from pyshell.utils.key import CryptographicKey
class TestKey(object):
# not a string and not a unicode
def test_notValidKeyString1(self):
with pytest.raises(KeyStoreException):
CryptographicKey(None)
# string but do... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# File: symmath_check.py
#
# Symbolic mathematical expression checker for edX. Uses sympy to check for expression equality.
#
# Takes in math expressions given as Presentation MathML (from ASCIIMathML), converts to Content MathML using SnuggleTeX
import traceback
from .fo... |
import unittest
MIN_SCORE = .7
g_words = []
def print1(line):
pass
#print(line);
def is_possible_replacement(target_word, possible_word):
global MIN_SCORE
score = 0
print1('*'*40)
if(target_word[0] == possible_word[0]):
score += 100
if(target_word... |
from __future__ import unicode_literals
from django.core.exceptions import FieldError
from django.test import TestCase
from django.utils import six
from .models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild,
SelfReferChildSibling, Worksheet, RegressionModelSplit)
class M2MRegressionTests(TestCase... |
import pycuda.gpuarray
from theano.sandbox import cuda
if cuda.cuda_available is False:
raise ImportError('Optional theano package cuda disabled')
def to_gpuarray(x, copyif=False):
""" take a CudaNdarray and return a pycuda.gpuarray.GPUArray
:type x: CudaNdarray
:param x: The array to transform to p... |
# -*- coding: utf-8 -*-
"""
werkzeug.testsuite.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Internal tests.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import unittest
from datetime import datetime
from warnings import filterwarnings, resetwarnings
from werkz... |
import os.path
from sphinx.application import ENV_PICKLE_FILENAME
from sphinx.util.console import bold
def setup(app):
from sphinx.application import Sphinx
if not isinstance(app, Sphinx):
return
app.connect('build-finished', emit_redirects)
def process_redirect_file(app, path, ent):
parent... |
from mock import patch, call
import pytest
from arctic.scripts import arctic_list_libraries
from ...util import run_as_main
def test_list_library(mongo_host, library, library_name):
with patch('arctic.scripts.arctic_list_libraries.print') as p:
run_as_main(arctic_list_libraries.main, "--host", mongo_hos... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ===========================================
# HipChat module specific support methods.
#
import urllib
DEFAULT_URI = "https://api.hipchat.com/v1"
MSG_URI_V1 = "/rooms/message"
NOTIFY_URI_V2 = "/room/{id_or_name}/notification"
def send_msg_v1(module, token, room, msg_fro... |
from oslo_serialization import jsonutils
import webob
from nova.api.openstack.compute.contrib import extended_virtual_interfaces_net
from nova import compute
from nova import network
from nova import test
from nova.tests.unit.api.openstack import fakes
FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
FAKE_VIFS =... |
import re
import wikipedia
import sys
import jangopath
flag = 0
query = ""
f = open(jangopath.HOME_DIR + '/ans.txt','w')
for arg in sys.argv:
if flag==1:
query = query + arg + " "
if arg.lower()=="for" or arg.lower()=="about":
flag = 1
def strip_non_ascii(string):
''' Returns the string without... |
#!/usr/bin/python
import unittest
import uuid
import ldc
class TestLDCLdapInterface(unittest.TestCase):
def test_ldcusers(self):
rand_str = str(uuid.uuid4())
ldc.ldap.users.add(rand_str, rand_str, "password", "12345", "100", "/home/users/" + rand_str, "/bin/bash")
assert ldc.ldap.users.get... |
"""wxcopyreg -- functions for storing/restoring simple wxPython data types to pickle-friendly formats
importing this module installs the functions automatically!
"""
import pickle, zlib
from wxPython.wx import *
##
def bind( classObject, outFunction, inFunction ):
"""Bind get and set state for the classObject"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask-Scrypt flask extension provides scrypt password hashing and random salt generation.
Hashes and Salts are base64 encoded.
"""
from __future__ import print_function, unicode_literals
import sys
import base64
import hmac
from os import urandom
from werkzeug.security... |
import time
from config import Config
import osci, random, time
import ige.version
from ige import log
import sys, os, os.path
import re
from optparse import OptionParser
# log initialization
log.message("Starting Outer Space Client", ige.version.versionStringFull)
log.debug("sys.path =", sys.path)
log.debug("os.nam... |
import hr
import res_config
import res_users
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
import sys
import struct
import binascii
L2CAP=0
RFCOMM=3
PORT_ANY=0
# Service Class IDs
SDP_SERVER_CLASS = "1000"
BROWSE_GRP_DESC_CLASS = "1001"
PUBLIC_BROWSE_GROUP = "1002"
SERIAL_PORT_CLASS = "1101"
LAN_ACCESS_CLASS = "1102"
DIALUP_NET_CLASS = "1103"
IRMC_SYNC_CLASS = "1104"
OBEX_OBJPUSH_CLASS = "1105"
OBEX_FILET... |
"""Schema processing for discovery based APIs
Schemas holds an APIs discovery schemas. It can return those schema as
deserialized JSON objects, or pretty print them as prototype objects that
conform to the schema.
For example, given the schema:
schema = \"\"\"{
"Foo": {
"type": "object",
"properties": {
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from random import random
from math import floor
from .common import InfoExtractor
from ..compat import (
compat_urllib_request,
)
from ..utils import (
ExtractorError,
)
class IPrimaIE(InfoExtractor):
_VALID_URL = r'https?://play... |
"""Trains the MNIST network using preloaded data stored in a variable.
Run using bazel:
bazel run --config opt \
<...>/tensorflow/examples/how_tos/reading_data:fully_connected_preloaded_var
or, if installed via pip:
cd tensorflow/examples/how_tos/reading_data
python fully_connected_preloaded_var.py
"""
from __f... |
from __future__ import unicode_literals
import os
import pkgutil
import sys
from collections import OrderedDict, defaultdict
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.manageme... |
"""Functional tests for BiasAdd."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
class BiasAddTest(tf.test.TestCase):
def _npBias(self, inputs, bias):
assert len(bias.s... |
""" A few useful function/method decorators. """
from __future__ import print_function
__docformat__ = "restructuredtext en"
import sys
import types
from time import clock, time
from inspect import isgeneratorfunction, getargspec
from logilab.common.compat import method_type
# XXX rewrite so we can use the decorat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Data Analysis plugin tailored for ID31
* integrate_simple: simple demo of a simple integrator
* integrate: a more advanced options
"""
__authors__ = ["Jérôme Kieffer"]
__contact__ = "<EMAIL>"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facil... |
import cmd
import os
import sys
import socket
import threading
from gppylib.commands.base import WorkerPool, REMOTE, ExecutionError
from gppylib.commands.unix import Hostname, Echo
sys.path.insert(1, sys.path[0] + '/lib')
from pexpect import pxssh
class HostNameError(Exception):
def __init__(self, msg, lineno = 0... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_regedit
version_added: '2.0'
short_description: Add, change, or remove registry keys and values
description:
- Add, modify or remove registry keys ... |
"""ZeroOut op Python library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
_zero_out_module = tf.load_op_library(
os.path.join(tf.resource_loader.get_data_files_path(),
'zero_out_op_kernel_1... |
"""Tests for ragged_array_ops.expand_dims."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from tensorflow.python.framework import test_util
from tensorflow.python.ops.ragged import ragged_array_ops
from tensorflow... |
from rdflib.graph import ConjunctiveGraph
from rdflib.term import URIRef, Literal
from rdflib.namespace import RDFS
from rdflib.sparql.Algebra import RenderSPARQLAlgebra
from StringIO import StringIO
import unittest, sys
import nose
testContent = """
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix dc: <http://pu... |
import abc
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import importutils
import six
from neutron.api import extensions
from neutron.db import servicetype_db as sdb
from neutron.i18n import _LE, _LI
from neutron.services import provider_configuration as pconf
LOG = logging.get... |
#!/usr/bin/python
import itertools
import os
import signal
import sys
from argparse import ArgumentParser
from subprocess import call
from threading import Thread
from time import sleep
import gratuitousArp
from mininet.cli import CLI
from mininet.examples.controlnet import MininetFacade
from mininet.link import TCLin... |
"""
Tests for the wrapping layer that provides the XBlock API using XModule/Descriptor
functionality
"""
# For tests, ignore access to protected members
# pylint: disable=protected-access
import webob
import ddt
from factory import (
BUILD_STRATEGY,
Factory,
lazy_attribute,
LazyAttributeSequence,
p... |
from __future__ import unicode_literals
from django.conf import settings
from django.db.backends import BaseDatabaseOperations
class DatabaseOperations(BaseDatabaseOperations):
def __init__(self, connection):
super(DatabaseOperations, self).__init__(connection)
def date_extract_sql(self, lookup_type... |
import logging
import deluge.component as component
import deluge.pluginmanagerbase
from deluge.configmanager import ConfigManager
from deluge.ui.client import client
log = logging.getLogger(__name__)
class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Component):
def __init__(self):
... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.pyc'
"""
from nupic... |
"""
"""
import argparse
import csv
from itertools import *
from .core import *
def read(filename):
states = []
with open(filename) as fp:
rd = csv.DictReader(fp) # default: excel
for row in rd:
states.append(row)
return states
def condition(state: dict):
def to_literal... |
"""
Microsite backend that reads the configuration from the database
"""
from mako.template import Template
from util.cache import cache
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
from util.memcache import fasthash
from util.url import strip_po... |
"""Operators for concise TensorFlow network models.
This module is used as an environment for evaluating expressions
in the "specs" DSL.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.layers.python.layers import layers
from ten... |
from django.db.models.lookups import (
Exact, GreaterThan, GreaterThanOrEqual, In, LessThan, LessThanOrEqual,
)
class MultiColSource(object):
contains_aggregate = False
def __init__(self, alias, targets, sources, field):
self.targets, self.sources, self.field, self.alias = targets, sources, field... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals, print_function, division
import logging
log = logging.getLogger("cryptocoin")
def command_ltc(bot, user, channel, args):
"""Display current LRC exchange rates from BTC-E"""
r = bot.get_url("https://btc-e.com/api/2/ltc_usd/ticker")
j = r.j... |
from openerp.tests.common import TransactionCase
class TestDropshippingSkipCheck(TransactionCase):
def setUp(self):
"""Set up an dropshipping sale order line.
To do that, mock the computed source location to be a supplier.
"""
super(TestDropshippingSkipCheck, self).setUp()
... |
#! /usr/bin/env python
# File: udf/ext_has_spouse_features.py
import sys, json
import ddlib
# For each input tuple
# TODO: Sample Data and the input schema.
# sample json
for row in sys.stdin:
# Unpack input into tuples.
#
obj = json.loads(row)
words, lemmas = obj["words"], obj["lemma"]
span1 = ddlib.Span(... |
"""
Handlers for video module.
StudentViewHandlers are handlers for video module instance.
StudioViewHandlers are handlers for video descriptor instance.
"""
import json
import logging
from webob import Response
from xblock.core import XBlock
from xmodule.exceptions import NotFoundError
from xmodule.fields import R... |
#!/usr/bin/env python
import requests
import time, json, os
import re,pprint
# Change this to match your access token
token="<access_token>"
# This should be your account number. This is the number you see when logged into canvas
# as an admin. i.e. https://schoolname.insructure.com/accounts/SOME_NUMBER_HERE
ACCOUNT... |
import logging
from django.contrib.sessions.backends.base import CreateError, SessionBase
from django.core.exceptions import SuspiciousOperation
from django.db import IntegrityError, router, transaction
from django.utils import timezone
from django.utils.encoding import force_text
class SessionStore(SessionBase):
... |
{
'name': 'Indian Payroll',
'category': 'Localization',
'author': 'OpenERP SA',
'website':'http://www.openerp.com',
'depends': ['hr_payroll'],
'version': '1.0',
'description': """
Indian Payroll Salary Rules.
============================
-Configuration of hr_payroll for India localizati... |
from __future__ import division
from vistrails.core.modules.vistrails_module import Module, InvalidOutput, \
ModuleError
import copy
#################################################################################
## If Operator
class If(Module):
"""
The If Module alows the user to choose the part of th... |
"""This module is deprecated. Please use `airflow.providers.google.cloud.operators.compute`."""
import warnings
from airflow.providers.google.cloud.operators.compute import (
ComputeEngineBaseOperator,
ComputeEngineCopyInstanceTemplateOperator,
ComputeEngineInstanceGroupUpdateManagerTemplateOperator,
... |
"""Laplacian matrix of graphs.
"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils import not_implemented_for
__author__ = "\n".join(['Aric Hagberg <<EMAIL>>',
... |
import csv
import time
from Reading import Reading as Reading
### TODO ### Add documentation to classes and methods
class AccuChekMobileParser(object):
# this file has some summary data in row 2 with the headers in row 1
# the result data is then in row 4 with the headers in row 3
def __init_... |
class ModuleDocFragment(object):
# Ansible Tower documentation fragment
DOCUMENTATION = '''
options:
tower_host:
description:
- URL to your Tower instance.
required: False
default: null
tower_username:
description:
- Username for your Tower instance.
... |
try:
import networkx as nx
except ImportError:
import warnings
warnings.warn('RAGs require networkx')
import numpy as np
from . import _ncut
from . import _ncut_cy
from scipy.sparse import linalg
def cut_threshold(labels, rag, thresh, in_place=True):
"""Combine regions separated by weight less than th... |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import os
class Report(models.Model):
title = models.CharField(max_length=30)
description = models.CharField(max_length = 200)
create_date = models.DateTimeField('date created')
public = models.Bo... |
import json
from django.contrib.postgres import forms, lookups
from django.contrib.postgres.fields.array import ArrayField
from django.core import exceptions
from django.db.models import Field, TextField, Transform
from django.utils import six
from django.utils.encoding import force_text
from django.utils.translation ... |
import threading
from openerp.osv import osv, fields
from openerp import tools, SUPERUSER_ID
from openerp.tools.translate import _
from openerp.tools.mail import plaintext2html
class mail_followers(osv.Model):
""" mail_followers holds the data related to the follow mechanism inside
OpenERP. Partners can c... |
'''
Smart_Strong Extension for Python-Markdown
==========================================
This extention adds smarter handling of double underscores within words.
See <https://pythonhosted.org/Markdown/extensions/smart_strong.html>
for documentation.
Original code Copyright 2011 [Waylan Limberg](http://achinghead.c... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from units.modules.utils import set_module_args
from .iosxr_module import TestIosxrModule, load_fixture
from ansible.modules.network.iosxr import iosxr_system
class TestIosxrSystemModul... |
"""
Pynamodb constants
"""
# Operations
BATCH_WRITE_ITEM = 'BatchWriteItem'
DESCRIBE_TABLE = 'DescribeTable'
BATCH_GET_ITEM = 'BatchGetItem'
CREATE_TABLE = 'CreateTable'
UPDATE_TABLE = 'UpdateTable'
DELETE_TABLE = 'DeleteTable'
LIST_TABLES = 'ListTables'
UPDATE_ITEM = 'UpdateItem'
DELETE_ITEM = 'DeleteItem'
GET_ITEM =... |
""" This is a very crude version of "in-memory HBase", which implements just
enough functionality of HappyBase API to support testing of our driver.
"""
import copy
import re
from oslo_log import log
import six
import aodh
LOG = log.getLogger(__name__)
class MTable(object):
"""HappyBase.Table mock."""
de... |
"""
Tests for the journal app
"""
import datetime
from django.test import TestCase
from .models import Entry, published_filter
from .navigation import get_nodes
class EntryTest(TestCase):
def setUp(self):
self.today = datetime.datetime.today()
self.yesterday = self.today - datetime.timedelta(day... |
# coding: utf-8
import datetime
import random
from django.shortcuts import render
def index(request):
return render(request, 'app6_index.html')
def filters(request):
context = {}
# filter: random, pluralize, length_is, join
context['people'] = (
'Mr Black',
'Mr Pink',
'Mr... |
# -*- coding: utf-8 -*-
"""
A Theil-Sen Estimator for Multiple Linear Regression Model
"""
#
# License: BSD 3 clause
from __future__ import division, print_function, absolute_import
import warnings
from itertools import combinations
import numpy as np
from scipy import linalg
from scipy.special import binom
from sc... |
"""
To run this, you'll need to have installed.
* scikit-learn
Does two benchmarks
First, we fix a training set, increase the number of
samples to classify and plot number of classified samples as a
function of time.
In the second benchmark, we increase the number of dimensions of the
training set, classify a sam... |
import os
import shutil
import unittest
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
def skip_checks(system_manager):
if system_manager.code_manager.test_type != 'galera':
return True, "Requires galera / wsrep server"
return False, ''
server_requirements = [[]]
servers = []
server_manage... |
import tempfile
from sh import rst2pdf
from django.shortcuts import get_object_or_404
from waliki.models import Page
from waliki.utils import send_file
from waliki.settings import WALIKI_PDF_INCLUDE_TITLE
from waliki.settings import WALIKI_PDF_RST2PDF_BIN
from waliki.acl import permission_required
@permission_require... |
#!/usr/bin/env python
# ---- ----------
# | | | |
# | --- |----- |
# | | | | |
# | | | | |
# ---------------------------
from heapq import heapify, heappush, heappop
import math
class Solution:
def getSkyline(self, buildings):
... |
"""The tests for the MQTT light platform.
Configuration for RGB Version with brightness:
light:
platform: mqtt
name: "Office Light RGB"
state_topic: "office/rgb1/light/status"
command_topic: "office/rgb1/light/switch"
brightness_state_topic: "office/rgb1/brightness/status"
brightness_command_topic: "offic... |
"""Module implementing error-catching version of send (sendRobust)"""
from pydispatch.dispatcher import Any, Anonymous, liveReceivers, getAllReceivers
from pydispatch.robustapply import robustApply
def sendRobust(
signal=Any,
sender=Anonymous,
*arguments, **named
):
"""Send signal from sender to all connected re... |
import os
import imp
from nupic.data.dictutils import rUpdate
# This file contains utility functions that are used
# internally by the prediction framework and may be imported
# by description files. Functions that are used only by
# the prediction framework should be in utils.py
#
# This file provides support for t... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
HAS_BOTO = False
try:
import boto
import boto.cloudtrail
from boto.regioninfo import RegionInfo
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
from ansible.module... |
"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm.collections import attribute_mapped_collection
from meta import Base
from pylons.controllers.util import abort
from meta import Session
from person_social_network_map import P... |
"""Example of a generator: re-implement the built-in range function
without actually constructing the list of values.
OldStyleRange is coded in the way required to work in a 'for' loop before
iterators were introduced into the language; using __getitem__ and __len__ .
"""
def handleargs(arglist):
"""Take list of ... |
from django.shortcuts import render
from django.http import HttpResponse
from json import dumps as to_json
from json import loads as from_json
from models import *
from neo import *
def type_all(request):
types = Type.objects.filter(is_approved=True)
json = to_json([t.to_json() for t in types])
return Htt... |
import os
import re
from contextlib import contextmanager
from textwrap import dedent
from pants.backend.jvm.targets.java_agent import JavaAgent
from pants.backend.jvm.targets.jvm_binary import JvmBinary
from pants.backend.jvm.tasks.jar_task import JarBuilderTask, JarTask
from pants.build_graph.build_file_aliases impo... |
"""A class to keep track of devices across builds and report state."""
import json
import logging
import optparse
import os
import psutil
import re
import signal
import smtplib
import subprocess
import sys
import time
import urllib
import bb_annotations
import bb_utils
sys.path.append(os.path.join(os.path.dirname(__f... |
"""
Support for Elasticsearch (1.0.0 or newer).
Provides an :class:`ElasticsearchTarget` and a :class:`CopyToIndex` template task.
Modeled after :class:`luigi.contrib.rdbms.CopyToTable`.
A minimal example (assuming elasticsearch is running on localhost:9200):
.. code-block:: python
class ExampleIndex(CopyToInd... |
# coding=utf-8
"""getinfo - get header information from a RADIANCE file"""
from _commandbase import RadianceCommand
from ..datatype import RadiancePath, RadianceBoolFlag
import os
class Getinfo(RadianceCommand):
get_dimensions = RadianceBoolFlag('d', 'get_dimensions')
output_file = RadiancePath('output', 'ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.