content stringlengths 4 20k |
|---|
from __future__ import unicode_literals
import re
from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text
from django.utils.ipv6 import is_valid_ipv6_address
from django.utils.six.moves.urllib.par... |
import logging
from airflow.hooks import MySqlHook
from airflow.models import BaseOperator
from airflow.utils import apply_defaults
class MySqlOperator(BaseOperator):
"""
Executes sql code in a specific MySQL database
:param mysql_conn_id: reference to a specific mysql database
:type mysql_conn_id: ... |
# examples/increment_example.py
# from weave import ext_tools
# use the following so that development version is used.
from __future__ import absolute_import, print_function
import sys
sys.path.insert(0,'..')
import ext_tools
def build_increment_ext():
""" Build a simple extension with functions that increment... |
from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Converts a module namespace to a Python dictionary."""
return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)}
class Command(BaseCommand):
help = """Displays diff... |
import collections
# BFS
class Solution:
def minKnightMoves(self, x: int, y: int) -> int:
if x == 0 and y == 0:
return 0
Q = collections.deque([(0, 0)])
visited = set([(0, 0)])
step = 0
x, y = abs(x), abs(y)
while Q:
step += 1
for _... |
'''
Bernie's L System demo in Python.
This program implements a simple context free L System,
and renders two dimensional images in a window.
It needs (at least) python 2.6, and uses the turtle
graphics library, which is based on TK graphics.
To try it out, either load into Python and run the
demo functions, or run... |
import unittest
from docido_sdk.toolbox.ha import RetryDelaySeries, HA
class TestHA(unittest.TestCase):
def test_teb_policy(self):
teb = RetryDelaySeries.get(
'truncated_exponential_backoff',
max_collisions=5,
delay=10)
self.assertEquals(next(teb), 0)
s... |
{
'name' : 'Procurements',
'version' : '1.0',
'website': 'https://www.odoo.com/page/manufacturing',
'category' : 'Hidden',
'depends' : ['base', 'product'],
'description': """
This is the module for computing Procurements.
==============================================
This procurement module on... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote
class EHowIE(InfoExtractor):
IE_NAME = 'eHow'
_VALID_URL = r'https?://(?:www\.)?ehow\.com/[^/_?]*_(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.ehow.com/video_12245069_hardwoo... |
import abc
import six
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import base
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as qexception
from neutron import manager
from neutron.plugins.common import constants
from neutron.se... |
import ldap as l
from flask import Flask, g, request, session, redirect, url_for
from flask_simpleldap import LDAP
app = Flask(__name__)
app.secret_key = 'dev key'
app.debug = True
app.config['LDAP_HOST'] = 'ldap.example.org'
app.config['LDAP_BASE_DN'] = 'OU=users,dc=example,dc=org'
app.config['LDAP_USERNAME'] = 'CN=... |
import gdb
import os
import re
from linux import modules
if hasattr(gdb, 'Breakpoint'):
class LoadModuleBreakpoint(gdb.Breakpoint):
def __init__(self, spec, gdb_command):
super(LoadModuleBreakpoint, self).__init__(spec, internal=True)
self.silent = True
self.gdb_comman... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pylab as pl
from scipy.stats import t, laplace, norm
a = np.random.randn(30)
outliers = np.array([8, 8.75, 9.5])
pl.hist(a, 7, weights=[1 / 30] * 30, rwidth=0.8)
#fit without outliers
x = np.linspace(-5, 10, 500)
loc, scale = norm.fit(a)
n = norm.pdf(x, loc... |
from msrest.serialization import Model
class ExpressRouteServiceProviderBandwidthsOffered(Model):
"""Contains bandwidths offered in ExpressRouteServiceProvider resources.
:param offer_name: The OfferName.
:type offer_name: str
:param value_in_mbps: The ValueInMbps.
:type value_in_mbps: int
""... |
"""Instruments classes and jar files.
This script corresponds to the 'emma_instr' action in the java build process.
Depending on whether emma_instrument is set, the 'emma_instr' action will either
call one of the instrument commands, or the copy command.
Possible commands are:
- instrument_jar: Accepts a jar and inst... |
from __future__ import with_statement
import sys
import webkit2.messages
def main(argv=None):
if not argv:
argv = sys.argv
input_path = argv[1]
with open(input_path) as input_file:
# Python 3, change to: print(webkit2.messages.generate_message_handler(input_file), end='')
sys.std... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from numpy import abs
from numpy import asarray
from numpy import array
from numpy import ceil
from numpy import dot
from numpy import hstack
from numpy import kron
from numpy import max
from numpy import maxim... |
import os
from nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription
# the sub-experiment configuration
config = \
{
'dataSource': 'file://' + os.path.join(os.path.dirname(__file__),
'../datasets/category_0.csv'),
... |
address = {
0x40: 'Matsui TV',
}
digits = {
0: ['0', '0'],
1: ['1', '1'],
2: ['2', '2'],
3: ['3', '3'],
4: ['4', '4'],
5: ['5', '5'],
6: ['6', '6'],
7: ['7', '7'],
8: ['8', '8'],
9: ['9', '9'],
}
# Commands. Items that are not listed are reserved/unknown.
command = {
0x... |
"""
This module contains "quick" tests that are run on a demo database
without any fixture. You can run only these tests by issuing::
$ python manage.py test cbss.QuickTest
$ django-admin.py test --settings=lino_welfare.projects.eupen.settings.demo cbss.QuickTest
"""
from builtins import str
import datetime
im... |
""" @package antlr3
@brief ANTLR3 runtime package
This module contains all support classes, which are needed to use recognizers
generated by ANTLR3.
@mainpage
\note Please be warned that the line numbers in the API documentation do not
match the real locations in the source code of the package. This is an
unintended... |
# pylint: disable=too-few-public-methods, no-absolute-import,missing-docstring,import-error,wrong-import-position
# pylint: disable=wrong-import-order
def decorator(fun):
"""Decorator"""
return fun
class DemoClass(object):
"""Test class for method invocations."""
@staticmethod
def static_method(... |
from __future__ import absolute_import
from gnuradio import gr, gr_unittest
from gnuradio import fec
from _qa_helper import _qa_helper
class test_fecapi_cc(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_parallelism0_00(sel... |
#
# The Python Imaging Library.
# $Id$
#
##
# Image plugin for Palm pixmap images (output only).
##
__version__ = "1.0"
import Image, ImageFile
_Palm8BitColormapValues = (
( 255, 255, 255 ), ( 255, 204, 255 ), ( 255, 153, 255 ), ( 255, 102, 255 ),
( 255, 51, 255 ), ( 255, 0, 255 ), ( 255, 255, 204 ), ( ... |
import yaml
import re
from proboscis.asserts import assert_equal
from fuelweb_test import logger
class FuelActions(object):
class BaseActions(object):
def __init__(self, admin_remote):
self.admin_remote = admin_remote
self.container = None
def execute_in_container(self, ... |
# -*- coding: utf-8 -*-
from selenium.webdriver.firefox.webdriver import WebDriver
import unittest
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class add_pozov(unittest.TestCase):
def setUp(self):
self.wd = WebDriver()
... |
"""
Invenio pagination helper class.
"""
from math import ceil
class Pagination(object):
"""Helps with rendering pagination list."""
def __init__(self, page, per_page, total_count):
self.page = page
self.per_page = per_page
self.total_count = total_count
@property
def pages(... |
from abc import ABCMeta, abstractproperty
import os
import subprocess
import traceback
from mozlog.structured import get_default_logger
from mozprocess import ProcessHandler
import mozcrash
from ..application import DefaultContext
from ..errors import RunnerNotStartedError
class BaseRunner(object):
"""
The ... |
from openerp.osv import fields, osv
class sale_journal_invoice_type(osv.osv):
_name = 'sale_journal.invoice.type'
_description = 'Invoice Types'
_columns = {
'name': fields.char('Invoice Type', size=64, required=True),
'active': fields.boolean('Active', help="If the active field is set to F... |
from nose.tools import assert_equals
from lettuce import step
from lettuce.terrain import world
from lettuce import after
@step('I sum (\d+) and (\d+)')
def i_sum_x_and_y(step, x, y):
world.sum = int(x) + int(y)
@step('it should result in (\d+)')
def it_should_result_in_z(step, z):
assert_equals(world.sum, i... |
"""
LQR based trajectory controller
"""
from __future__ import print_function
try:
import jax.numpy as np
except ImportError:
import numpy as np
import pylqr
class PyLQR_TrajCtrl():
"""
Use second-order system and acceleration as system and input
The trajectory is given as a set of reference wayp... |
"""
Discrete Fourier Transform (:mod:`numpy.fft`)
=============================================
.. currentmodule:: numpy.fft
Standard FFTs
-------------
.. autosummary::
:toctree: generated/
fft Discrete Fourier transform.
ifft Inverse discrete Fourier transform.
fft2 Discrete Fourier t... |
import logging
import smtplib
import threading
try:
from email.mime.text import MIMEText
except ImportError:
# python 2.4 version
from email.MIMEText import MIMEText
from pulp.server.compat import json, json_util
from pulp.server.config import config
TYPE_ID = 'email'
_logger = logging.getLogger(__name_... |
from test_framework.test_framework import KoreTestFramework
from test_framework.util import *
def calc_usage(blockdir):
return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f)) / (1024. * 1024.)
class PruneTest(KoreTestFramework):
def __init__(self):
self.ut... |
import pandas as pd
import matplotlib.pyplot as plt
from numpy import random
import os
# The inital set of baby names
names = ['Bob','Jessica','Mary','John','Mel']
# This will ensure the random samples below can be reproduced.
# This means the random samples will always be identical.
random.seed(500)
random_names = [... |
from django.core import urlresolvers
from django.core.paginator import EmptyPage, PageNotAnInteger
from django.http import Http404
from django.template.response import TemplateResponse
from django.contrib.sites.models import get_current_site
def index(request, sitemaps,
template_name='sitemap_index.xml', mime... |
"""A multivariate TFTS example.
Fits a multivariate model, exports it, and visualizes the learned correlations
by iteratively predicting and sampling from the predictions.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os import path
import tempf... |
import sys
# For development purposes
sys.path.extend(['.', '..'])
from pykolab.translate import _
try:
from pykolab.constants import *
except ImportError, e:
print >> sys.stderr, _("Cannot load pykolab/constants.py:")
print >> sys.stderr, "%s" % e
sys.exit(1)
import wallace
if __name__ == "__main_... |
# encoding: utf-8
"""
Copyright 2013 Jérémie BOUTOILLE
This program 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 3 of the License, or
(at your option) any later version.
This program is distri... |
#!/usr/bin/env python3
# This script runs multiple GISSUMO simulations in parallel, one for each floating car data file provided.
import gzip
import os
import plistlib
import re
import shutil
import subprocess
import sys
import time
import datetime
# Requires Python >3.5
assert sys.version_info >= (3,5), "This script... |
"""Unittests for grit.format.policy_templates.writers.adml_writer."""
import os
import sys
import unittest
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
from grit.format.policy_templates.writers import adml_writer
from grit.format.policy_templates.writers impor... |
# TemplatePyMod gui init module
# (c) 2007 Juergen Riegel LGPL
#
class TemplatePyModWorkbench ( Workbench ):
"Test workbench object"
Icon = """
/* XPM */
static const char *test_icon[]={
"16 16 2 1",
"a c #000000",
". c None",
"................",
"................",
"..#####... |
"""Shared helper functions for BigQuery API classes."""
import base64
import datetime
import decimal
from google.cloud._helpers import UTC
from google.cloud._helpers import _date_from_iso8601_date
from google.cloud._helpers import _datetime_from_microseconds
from google.cloud._helpers import _microseconds_from_dateti... |
#!/usr/bin/env python
import sys
import yaml
import csv
from collections import OrderedDict
import yaml_odict
def convert_file(fname):
reader = csv.reader(open(fname, 'r'))
registers = OrderedDict()
for register_name, lsb, width, field_name, description, reset_value, access in reader:
if registe... |
#!/usr/bin/python
### Import libraries ###
import sys
import time
import telepot
import datetime
import json
import os
from User import User
from threading import Thread
import time
import pytz
### Create users dictionary ###
users = {}
### Get bot token ###
def getToken (file):
with open (file, "r") as tokenF... |
import decimal
import pytest
from bs4 import BeautifulSoup
from django.core.urlresolvers import reverse
from shuup.admin.modules.orders.utils import OrderInformation
from shuup.admin.modules.orders.views.detail import OrderDetailView
from shuup.apps.provides import override_provides
from shuup.testing.factories impor... |
"""
Django settings for wason_selection_task project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import subprocess
import os
import traceback
import signal
from .zephyr_mirror_backend import parse_args
(options, args) = parse_args()
sys.path[:0] = [os.path.join(options.root_path, 'api')]
from types import FrameType
from typ... |
"""
Various queries for grabbing interesting user stats from Trac.
"""
import operator
from collections import OrderedDict
import django.db
from .models import Attachment, Revision, Ticket, TicketChange
_statfuncs = []
def stat(title):
"""
Register a function as a "stat"
The function should take a use... |
LEFT = 0
CENTER = 1
RIGHT = 2
# Vertical alignments
TOP = 0
MIDDLE = 1
BOTTOM = 2
# Stretching constants
FIT_WIDTH = 1
FIT_HEIGHT = 2
FULL_SCREEN = 3
KEEP_ASPECT = 4
# Screen sizing scalers
SCREEN_WIDTH = 640.0
SCREEN_HEIGHT = 480.0
#set of values that define as true when loading string values from a file
def... |
from mock import patch
from nose.tools import eq_
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.translation import get_language
from django.utils.functional import lazy
from kitsune.sumo.email_utils import (safe_translation,
email... |
"""
Module to read input devices and send controls to the Crazyflie.
This module reads input from joysticks or other input devices and sends control
set-points to the Crazyflie. It can be configured in the UI.
Various drivers can be used to read input device data. Currently is uses the
PyGame driver, but in the futur... |
"""Classification of the patinets."""
from bunch import Bunch
import numpy as np
from mutil import p_info, Cache
from get_sample import PatientData, Mimic2m, Mimic2
import alg.clustering
import alg.classification
import alg.timeseries
mimic2m = Mimic2m()
mimic2 = Mimic2()
Default_db_param = Bunch(max_id=0, target_co... |
# dblite.py module contributed by Ralf W. Grosse-Kunstleve.
# Extended for Unicode by Steven Knight.
import SCons.compat
import builtins
import os
# compat layer imports "cPickle" for us if it's available.
import pickle
import shutil
import time
keep_all_files = 00000
ignore_corrupt_dbfiles = 0
def corruption_warni... |
from redis import Redis, ConnectionPool
from copy import deepcopy
from math import ceil
class Leaderboard(object):
VERSION = '1.1.8'
DEFAULT_PAGE_SIZE = 25
DEFAULT_REDIS_HOST = 'localhost'
DEFAULT_REDIS_PORT = 6379
DEFAULT_REDIS_DB = 0
ASC = 'asc'
DESC = 'desc'
@classmethod
def po... |
'''Base configurations for tests'''
import os
import pytest
import bs4 as bs
import subprocess
import sys
sys.path.insert(0, 'generator')
import webpageGenerator as gen
@pytest.fixture(scope="session")
def sitemap_name():
return 'sitemap.xml'
@pytest.fixture(scope="session")
def root_directory():
return su... |
"""A mechanism for library configuration.
Whenever App Engine library code has the need for a user-configurable
value, it should use the following protocol:
1. Pick a prefix unique to the library module, e.g. 'mylib'.
2. Call lib_config.register(prefix, mapping) with that prefix as
the first argument and a dict m... |
#!/usr/bin/env python
"""
Read in setting values from ini file and then run s3 sync between local folder
and specified S3 bucket. Send results to local logfile & notify slack channel.
Use:
python s3_sync.py -i <settings_file.ini>
"""
import argparse
import os
import re
import subprocess
import sys
from configparser... |
import urwid
from todoman import widgets
_palette = [("error", "light red", "")]
class TodoEditor:
"""
The UI for a single todo entry.
"""
def __init__(self, todo, lists, formatter):
"""
:param model.Todo todo: The todo object which will be edited.
"""
self.current_l... |
import time
from splice.common import config, splice_server_client
from splice.common.exceptions import RequestException
from splice.common.models import ProductUsage, SpliceServer, SpliceServerTransferInfo
from logging import getLogger
_LOG = getLogger(__name__)
def upload_product_usage_data(cfg=None):
"""
... |
"""
Base class for XML loggers.
"""
import xml.sax.saxutils
from . import _Logger
xmlattr_entities = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
}
def xmlquote (s):
"""
Quote characters for XML.
"""
return xml.sax.saxutils.escape(s)
def xmlquoteattr (s):
"""
... |
"""Module annotatable tests"""
import unittest
from lxml import etree
from mock import Mock
from xblock.field_data import DictFieldData
from xblock.fields import ScopeIds
from xmodule.annotatable_module import AnnotatableModule
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from . import get_t... |
"""A parser of RFC 2822 and MIME email messages."""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
__all__ = ['Parser', 'HeaderParser', 'BytesParser', 'BytesHeaderParser']
import warnings
from io import StringIO, TextIOWrapper
from future.backports.emai... |
import os, popen2, re, sys
class MyPOpen(object):
def __init__(self, cmd, input = None, output = None, bufsize = -1):
self.status = -1
if input is None:
p2c_read, p2c_write = os.pipe()
self.tochild = os.fdopen(p2c_write, 'w', bufsize)
else:
p2c_write = N... |
from django.contrib.gis.gdal.error import OGRException
#### OGRGeomType ####
class OGRGeomType(object):
"Encapulates OGR Geometry Types."
# Dictionary of acceptable OGRwkbGeometryType s and their string names.
_types = {0 : 'Unknown',
1 : 'Point',
2 : 'LineString',
... |
from django.utils.translation import ugettext_lazy as _
from horizon.tables import MultiTableView # noqa
from horizon.utils import memoized
class ResourceBrowserView(MultiTableView):
browser_class = None
def __init__(self, *args, **kwargs):
if not self.browser_class:
raise ValueError("Y... |
import sys
import hashlib
_BLOCKSIZE = 65535
def file_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
buf = f.read(_BLOCKSIZE)
while len(buf) > 0:
h.update(buf)
buf = f.read(_BLOCKSIZE)
return h.hexdigest()
def blob_hash(blob):
h = hashlib.sha1()... |
#!/usr/bin/python
from sys import argv, stdout, stderr
import codecs, locale
import os
import xml.dom.minidom
stdout = codecs.getwriter('utf-8')(stdout)
NS_XI = 'http://www.w3.org/2001/XInclude'
def xincludate(dom, base, dropns = []):
remove_attrs = []
for i in xrange(dom.documentElement.attributes.length):... |
"""
This module contains EMR response objects
"""
from boto.resultset import ResultSet
class EmrObject(object):
Fields = set()
def __init__(self, connection=None):
self.connection = connection
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, c... |
"""This example gets a team by its ID.
To determine which teams exist, run get_all_teams.py.
Tags: TeamService.getTeam
"""
__author__ = '<EMAIL> (Jeff Sham)'
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.inser... |
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Algorithm.Framework")
from System import *
from QuantConnect import *
from QuantConnect.Data.UniverseSelection import *
from QuantConnect.Orders.Fees import Constant... |
# -*- coding: utf-8 -*-
"""Plugin that does basic test case validation.
Use ``--validate-test-cases`` to enable it.
Currently does not work on ``--collect-only`` due to pytest's implementation bug.
Error output lines are prefixed by ``[TCV-E]``.
If no error nappens, a line prefixed with ``[TCV-OK]`` appears at the e... |
from ray import tune
from ray.tune.registry import register_env
from ray.rllib.env.pettingzoo_env import PettingZooEnv
from pettingzoo.sisl import waterworld_v0
# Based on code from github.com/parametersharingmadrl/parametersharingmadrl
if __name__ == "__main__":
# RDQN - Rainbow DQN
# ADQN - Apex DQN
def... |
from nova import exception
from nova import log as logging
from nova.network import model
from nova import test
from nova.tests import fake_network_cache_model
LOG = logging.getLogger(__name__)
class RouteTests(test.TestCase):
def test_create_route_with_attrs(self):
route = fake_network_cache_model.new_r... |
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.contrib.auth.models import User
from django.test import RequestFactory, TestCase
from .models import (
Band, DynOrderingBandAdmin, Song, SongInlineDefaultOrdering,
SongInlin... |
#!/usr/bin/env python
from collections import defaultdict
import boto3
from django.core.management.base import BaseCommand
from django_ses import settings
from django_ses.models import SESStat
from django_ses.views import stats_to_list
def stat_factory():
return {
'delivery_attempts': 0,
'bounc... |
import pytest
from django.conf import settings
from waffle.testutils import override_switch
from kuma.attachments.models import Attachment
from kuma.attachments.tests import make_test_file
from kuma.core.urlresolvers import reverse
from . import normalize_html
from ..models import Revision
@pytest.fixture
def code_... |
import subprocess
import re
import tempfile
import bs4
import sys
from refiner.input.model import InputDocument, InputPage, Font, Text
def parse(string, replacements=[]):
for r in replacements:
string = re.sub(r[0], r[1], string)
soup = bs4.BeautifulSoup(string)
document = InputDocument()
f... |
from ..regions import Segment, Section
class ELFSegment(Segment):
"""
Represents a segment for the ELF format.
"""
def __init__(self, readelf_seg):
self.flags = readelf_seg.header.p_flags
super(ELFSegment, self).__init__(readelf_seg.header.p_offset,
... |
"""Signal handlers pertaining to the people app
Some of these signals deal with authentication related workflows.
"""
import logging
import traceback
from uuid import uuid1
from allauth.account.models import EmailAddress
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django... |
import unittest
from openid import message
from openid.test.support import OpenIDTestMixin
from openid.consumer import consumer
from openid.test.test_consumer import TestIdRes
from openid.consumer import discover
def const(result):
"""Return a function that ignores any arguments and just returns
the specified ... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.dylan
~~~~~~~~~~~~~~~~~~~~~
Lexers for the Dylan language.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, do_insertions, d... |
#!/usr/bin/env python
import argparse
import io
import os
import re
max_name_len = 60
re_name = re.compile(r'^[a-z][a-z0-9_]*$')
re_group = re.compile(r'//BEGIN')
re_option = re.compile(r'extern (Bounded)?Option<[^>]+>')
re_default = re.compile(r' *// *= *(.*)')
groups = []
root = os.path.dirname(os.path.dirname(os... |
"""An implementation of a shadow map for nsscache.
ShadowMap: An implementation of NSS shadow maps based on the Map
class.
ShadowMapEntry: A shadow map entry based on the MapEntry class.
"""
__author__ = '<EMAIL> (Vasilios Hoffman)'
from nss_cache.maps import maps
class ShadowMap(maps.Map):
"""This class repr... |
# coding: utf-8
from __future__ import unicode_literals
import calendar
import re
import time
from .amp import AMPIE
from .common import InfoExtractor
from ..compat import compat_urlparse
class AbcNewsVideoIE(AMPIE):
IE_NAME = 'abcnews:video'
_VALID_URL = 'http://abcnews.go.com/[^/]+/video/(?P<display_id>[0... |
from mistral.lang import types
from mistral.lang.v2 import base
from mistral.lang.v2 import retry_policy
class PoliciesSpec(base.BaseSpec):
# See http://json-schema.org
_schema = {
"type": "object",
"properties": {
"retry": retry_policy.RetrySpec.get_schema(),
"wait-bef... |
from time import ctime, time
from random import random, shuffle
from struct import unpack_from
from eventlet import sleep, Timeout
import swift.common.db
from swift.container import server as container_server
from swiftclient import ClientException, delete_object, put_object, \
quote
from swift.common.direct_clie... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Argentum Control GUI
Copyright (C) 2013 Isabella Stevens
Copyright (C) 2014 Michael Shiel
Copyright (C) 2015 Trent Waddington
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License... |
"""This is a sample module that doesn't really test anything all that
interesting.
It simply has a few tests, some of which succeed and some of which fail.
It's important that the numbers remain constant as another test is
testing the running of these tests.
>>> 2+2
4
"""
def foo():
"""
>>> 2+2
5
... |
from restalchemy.api import middlewares
from restalchemy.tests.functional.restapi.ra_based.microservice import (
contexts)
class ContextMiddleware(middlewares.ContextMiddleware):
def process_request(self, req):
ctx = contexts.Context()
req.context = ctx
result = req.get_response(self.... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class RingTVIE(InfoExtractor):
_VALID_URL = r'http://(?:www\.)?ringtv\.craveonline\.com/(?P<type>news|videos/video)/(?P<id>[^/?#]+)'
_TEST = {
"url": "http://ringtv.craveonline.com/news/310833-luis-collazo-says-victo... |
#!/bin/env python3
"""
Author: Leigh MacDonald <<EMAIL>>
"""
from unittest import TextTestRunner, TestLoader
from glob import glob
from os.path import splitext, basename, join
from os import getcwd
try:
from os.path import walk
except ImportError:
from os import walk
from distutils.core import setup, Command
c... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from os.path import isdir, isfile, isabs, exists, lexists, islink, samefile, ismount
from ansible import errors
class TestModule(object):
''' Ansible file jinja2 tests '''
def tests(self):
return {
# f... |
#!/usr/bin/env python
from numpy import array,hstack,sin,cos
from numpy.random import seed, rand
from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
label_traindat = lm.load_labels('../data/label_train_twoclass.... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
import contextlib
import datetime
import functools
import socket
import sys
import threading
import time
from tornado import gen
from tornado.ioloop import IOLoop, TimeoutError
from tornado.log import app_log
from ... |
"""Private constants for the package."""
INTERNAL_ERROR_LOG_MESSAGE = ':-( RPC Framework (Base) internal error! :-(' |
"""
Utilities for manipulating Geometry WKT.
"""
def precision_wkt(geom, prec):
"""
Returns WKT text of the geometry according to the given precision (an
integer or a string). If the precision is an integer, then the decimal
places of coordinates WKT will be truncated to that number:
>>> pnt =... |
import errno
import logging
import os
from six.moves import reload_module as reload
import sys
import warnings
import theano
from theano import config
from theano.gof.compilelock import get_lock, release_lock
from theano.gof import cmodule
_logger = logging.getLogger('theano.gof.lazylinker_c')
force_compile = False... |
from Components.config import config, ConfigSubsection, ConfigSubList, ConfigInteger, ConfigText, ConfigSelection, getConfigListEntry, ConfigSequence, ConfigYesNo
import TitleCutter
class ConfigFixedText(ConfigText):
def __init__(self, text, visible_width=60):
ConfigText.__init__(self, default = text, fixed_size = ... |
import lxml.html
from html import escape
import chevron
import math
import prairielearn as pl
import numpy as np
import random
WEIGHT_DEFAULT = 1
CORRECT_ANSWER_DEFAULT = None
LABEL_DEFAULT = None
SUFFIX_DEFAULT = None
DISPLAY_DEFAULT = 'inline'
def prepare(element_html, data):
element = lxml.html.fragment_from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.