code stringlengths 1 199k |
|---|
from setuptools import setup
setup(
name = 'tvdb_api',
version='1.5',
author='dbr/Ben',
description='Interface to thetvdb.com',
url='http://github.com/dbr/tvdb_api/tree/master',
license='GPLv2',
long_description="""\
An easy to use API interface to TheTVDB.com
Basic usage is:
>>> import tvdb_api
>>> t = tvdb_api.Tvdb()... |
from __future__ import unicode_literals
import re
import sys
from unittest import TestCase, TestSuite, TestLoader, TextTestRunner
from pkg_resources import resource_stream # @UnresolvedImport
from babelfish import (LANGUAGES, Language, Country, Script, language_converters, country_converters,
LanguageReverseConver... |
from . import delivery_carrier
from . import delivery_grid
from . import product_template
from . import sale_order
from . import partner
from . import stock_picking
from . import stock_move
from . import stock_package_type |
import Task
import TaskGen
from TaskGen import extension
import sys
TaskGen.declare_chain(
name='genpy',
rule='${PYTHON} ${SRC} > ${TGT}',
reentrant=True,
color='BLUE',
ext_in='.genpy',
ext_out='.c',
before='c')
def configure(conf):
conf.env['PYTHON'] = sys.executable
conf.env['GENPY_EXT'] = ['.ge... |
'''Used for CNC machine comments for Path module. Create a comment and place it in the Document tree.'''
import FreeCAD
import FreeCADGui
import Path
from PySide import QtCore
def translate(context, text, disambig=None):
return QtCore.QCoreApplication.translate(context, text, disambig)
class Comment:
def __init... |
from oslo_log import log as logging
import nova.conf
from nova.scheduler import filters
from nova.scheduler import utils
LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF
class MetricsFilter(filters.BaseHostFilter):
"""Metrics Filter
This filter is used to filter out those hosts which don't have the
c... |
'''Tests subclassing Java classes in Python'''
import os
import sys
import threading
import unittest
from test import test_support
from java.lang import (Boolean, Class, ClassLoader, Comparable,Integer, Object, Runnable, String,
Thread, ThreadGroup, InterruptedException, UnsupportedOperationExcep... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from optparse import make_option
from django.utils.translation import ugettext_lazy, ugettext as _
from odk_viewer.models import ParsedInstance
from utils.model_tools import queryset_iterator
from common_tags import USERF... |
"""
logbook.notifiers
~~~~~~~~~~~~~~~~~
System notify handlers for OSX and Linux.
:copyright: (c) 2010 by Armin Ronacher, Christopher Grebs.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import base64
from time import time
from logbook.base import NOTSET, ERROR, WARNING
from ... |
AR = '/usr/bin/ar'
ARFLAGS = 'rcs'
CCFLAGS = ['-g']
CCFLAGS_MACBUNDLE = ['-fPIC']
CCFLAGS_NODE = ['-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64']
CC_VERSION = ('4', '2', '1')
COMPILER_CXX = 'g++'
CPP = '/usr/bin/cpp'
CPPFLAGS_NODE = ['-D_GNU_SOURCE', '-arch', 'i386']
CPPPATH_NODE = '/usr/local/include/node'
CPPPATH_ST... |
"""
Routers provide a convenient and consistent way of automatically
determining the URL conf for your API.
They are used by simply instantiating a Router class, and then registering
all the required ViewSets with that router.
For example, you might have a `urls.py` that looks something like this:
router = routers.... |
import os
import opk, cfg, opkgcl
opk.regress_init()
o = opk.OpkGroup()
o.add(Package="a", Version="1.0", Architecture="all", Depends="b")
o.add(Package="b", Version="1.0", Architecture="all", Depends="c")
o.write_opk()
o.write_list()
opkgcl.update()
opkgcl.install("a")
if opkgcl.is_installed("a"):
print(__file__, ": ... |
import logging
from gettext import gettext as _
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
from sugar3.graphics.icon import Icon
from sugar3.graphics import style
from sugar3.graphics.xocolor import XoColor
from jarabe.controlpanel.sectionview import SectionView
from b... |
from testtools import TestCase
from testtools.helpers import (
try_import,
try_imports,
)
from testtools.matchers import (
AllMatch,
AfterPreprocessing,
Equals,
Is,
Not,
)
from testtools.tests.helpers import (
FullStackRunTest,
hide_testtools_stack,
is_stack_hidden,
s... |
import openerp.tests.common as common
class TestMrpOperationsRejectedQuantity(common.TransactionCase):
def setUp(self):
super(TestMrpOperationsRejectedQuantity, self).setUp()
self.workcenter = self.env['mrp.workcenter'].create(
{'name': 'Test work center',
'op_number': 1,
... |
import hr_payroll_payslips_by_employees |
import os
import re
CFlags = '-Wall -O3 -fno-inline-functions -march=i686'
CFlags += ' -fomit-frame-pointer -ffast-math'
pkgDir = '../__csound6'
instPrefix = '/usr/local'
binDir = instPrefix + '/bin'
binDir2 = instPrefix + '/lib/csound/bin'
includeDir = instPrefix + '/include/csound'
libDir = instP... |
from Node import Node
COMMON_NODES = [
Node('Decl', kind='Syntax'),
Node('UnknownDecl', kind='Decl'),
Node('Expr', kind='Syntax'),
Node('UnknownExpr', kind='Expr'),
Node('Stmt', kind='Syntax'),
Node('UnknownStmt', kind='Stmt'),
Node('Type', kind='Syntax'),
Node('UnknownType', kind='Type'... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Link.anchor'
db.add_column(u'djangocms_link_link', 'anchor',
s... |
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon.utils import validators
from horizon import workflows
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.loadbalancers import utils
AVAILABLE_PROTOCOL... |
"""Specialized tasks for handling Avro data in BigQuery from GCS.
"""
import logging
from luigi.contrib.bigquery import BigQueryLoadTask, SourceFormat
from luigi.contrib.gcs import GCSClient
from luigi.task import flatten
logger = logging.getLogger('luigi-interface')
try:
import avro
import avro.datafile
except... |
"""Tests for the openmc.deplete.Nuclide class."""
import xml.etree.ElementTree as ET
import numpy as np
import pytest
from openmc.deplete import nuclide
def test_n_decay_modes():
""" Test the decay mode count parameter. """
nuc = nuclide.Nuclide()
nuc.decay_modes = [
nuclide.DecayTuple("beta1", "a",... |
'''tzinfo timezone information for America/Cayman.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Cayman(DstTzInfo):
'''America/Cayman timezone definition. See datetime.tzinfo for details'''
zone = 'America/Cayman'
_ut... |
"""
An example of how to use wx or wxagg in an application with the new
toolbar - comment out the setA_toolbar line for no toolbar
"""
import wxversion
wxversion.ensureMinimal('2.8')
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxA... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
author: "Brian Coca (@bcoca)"
module: set_stats
short_description: Set ... |
"""
Grading Context
"""
from collections import OrderedDict
from openedx.core.djangoapps.content.block_structure.api import get_course_in_cache
from .scores import possibly_scored
def grading_context_for_course(course_key):
"""
Same as grading_context, but takes in a course object.
"""
course_structure ... |
from osv import fields
from osv import osv
from tools.translate import _
class account_analytic_line(osv.osv):
_inherit = 'account.analytic.line'
_description = 'Analytic Line'
_columns = {
'product_uom_id': fields.many2one('product.uom', 'UoM'),
'product_id': fields.many2one('product.produc... |
"""Simple Part21 STEP reader
Reads a given STEP file. Maps the enteties and instaciate the
corosbonding classes.
In addition it writes out a graphwiz file with the entity graph.
"""
import Part21,sys
__title__="Simple Part21 STEP reader"
__author__ = "Juergen Riegel"
__version__ = "0.1 (Jan 2014)"
class SimpleParser:
... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import ExtractorError
class RTVNHIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?rtvnh\.nl/video/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rtvnh.nl/video/131946',
'md5': '6e1d0ab079e2a00b6161442d3ceacf... |
"""Functional tests for Split Op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from... |
import logging
from six.moves.urllib.parse import urljoin
from w3lib.url import safe_url_string
from scrapy.http import HtmlResponse
from scrapy.utils.response import get_meta_refresh
from scrapy.exceptions import IgnoreRequest, NotConfigured
logger = logging.getLogger(__name__)
class BaseRedirectMiddleware(object):
... |
import optparse
import os
import re
import sys
import build_version
from build_paths import SDK_SRC_DIR, SCRIPT_DIR, OUT_DIR
sys.path.append(os.path.join(SDK_SRC_DIR, 'tools'))
import getos
VALID_PLATFORMS = ['linux', 'mac', 'win']
PLATFORM_PREFIX_RE = re.compile(r'^\[([^\]]*)\](.*)$')
class ParseException(Exception):
... |
import os
import twisted
import six
from twisted.trial import unittest
from twisted.protocols.policies import WrappingFactory
from twisted.python.filepath import FilePath
from twisted.internet import reactor, defer, error
from twisted.web import server, static, util, resource
from twisted.web.test.test_webclient import... |
'''
Package containing modules and submodules defining an *API* that can be
used to describe Optical surfaces, components and systems.
'''
#~ "component",
#~ "comp_lib",
#~ "library",
#~ "mat_lib",
#~ "shape",
#~ "surface",
#~ "system"] |
from __future__ import absolute_import
import six
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql.base import ischema_names
from ..exceptions import ImproperlyConfigured
json = None
try:
import anyjson as json
except ImportError:
import json as json
try:
from sqlalchemy.dialects.postgresql impor... |
"""
flask.signals
~~~~~~~~~~~~~
Implements signals based on blinker if available, otherwise
falls silently back to a noop.
:copyright: © 2010 by the Pallets team.
:license: BSD, see LICENSE for more details.
"""
signals_available = False
try:
from blinker import Namespace
signals_availab... |
__all__ = ['Distribution']
import re
import os
import warnings
import numbers
import distutils.log
import distutils.core
import distutils.cmd
import distutils.dist
from distutils.errors import (DistutilsOptionError, DistutilsPlatformError,
DistutilsSetupError)
from distutils.util import rfc822_escape
from setuptool... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'fieldname': 'reference_name',
'internal_links': {
'Employee Advance': ['advances', 'employee_advance']
},
'transactions': [
{
'label': _('Payment'),
'items': ['Payment Entry', 'Journal Entry']
},
{
... |
import re
from functools import partial
from ..validators import chars_surround
from ..rebulk import Rebulk, FunctionalPattern, RePattern, StringPattern
def test_chain_close():
rebulk = Rebulk()
ret = rebulk.chain().close()
assert ret == rebulk
assert len(rebulk.effective_patterns()) == 1
def test_build... |
"""Support for Android IP Webcam."""
import asyncio
from datetime import timedelta
from pydroid_ipcam import PyDroidIPCam
import voluptuous as vol
from homeassistant.components.mjpeg.camera import CONF_MJPEG_URL, CONF_STILL_IMAGE_URL
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
... |
import unittest
from .detection import SCMDetector
from webkitpy.common.system.filesystem_mock import MockFileSystem
from webkitpy.common.system.executive_mock import MockExecutive
from webkitpy.common.system.outputcapture import OutputCapture
class SCMDetectorTest(unittest.TestCase):
def test_detect_scm_system(sel... |
"""
Console
=======
.. versionadded:: 1.9.1
Reboot of the old inspector, designed to be modular and keep concerns separated.
It also have a addons architecture that allow you to add a button, panel, or
more in the Console itself.
.. warning::
This module works, but might fail in some cases. Please contribute!
Usage... |
from django import forms
__all__ = ('MarkupTextarea',)
class MarkupTextarea(forms.widgets.Textarea):
def render(self, name, value, attrs=None):
if value is not None and not isinstance(value, unicode):
value = value.raw
return super(MarkupTextarea, self).render(name, value, attrs) |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.cloudengine import ce_static_route_bfd
from units.modules.network.cloudengine.ce_module import TestCloudEngineModule, load_fixture
from units.modules.utils import set_... |
import os
def configuration(parent_package='', top_path=None):
import numpy
from numpy.distutils.misc_util import Configuration
config = Configuration('neighbors', parent_package, top_path)
libraries = []
if os.name == 'posix':
libraries.append('m')
config.add_extension('ball_tree',
... |
from openerp import api, models, _
class AccountInvoice(models.Model):
_inherit = 'account.invoice'
@api.model
def _get_reference_type(self):
rt = super(AccountInvoice, self)._get_reference_type()
rt.append(('structured', _('Structured Reference')))
return rt |
import os
from os.path import dirname, abspath, basename
import sys
import argparse
import json
import subprocess
import shutil
import stat
import re
from github import Github, GithubException
ROOT = abspath(dirname(dirname(dirname(dirname(__file__)))))
sys.path.insert(0, ROOT)
import examples_lib as lib
from examples_... |
from measurements import smoothness_controller
from telemetry.page import page_test
class Repaint(page_test.PageTest):
def __init__(self, mode='viewport', width=None, height=None):
super(Repaint, self).__init__('RunPageInteractions', False)
self._smoothness_controller = None
self._micro_benchmark_id = Non... |
"""
EntryScale Class: Scale with a label, and a linked and validated entry
"""
__all__ = ['EntryScale', 'EntryScaleGroup']
from direct.showbase.TkGlobal import *
import Pmw, sys
if sys.version_info >= (3, 0):
from tkinter.simpledialog import *
from tkinter.colorchooser import askcolor
else:
from tkSimpleDia... |
"""
Logging package for Python. Based on PEP 282 and comments thereto in
comp.lang.python, and influenced by Apache's log4j system.
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
To u... |
from __future__ import unicode_literals
import frappe
no_cache = 1
def get_context(context):
if frappe.session.user != 'Guest':
context.all_certifications = get_all_certifications_of_a_member()
context.show_sidebar = True
def get_all_certifications_of_a_member():
'''Returns all certifications'''
all_certificatio... |
"""FreeCAD WebGL Exporter"""
import FreeCAD,Mesh,Draft,Part,OfflineRenderingUtils,json,six
import textwrap
if FreeCAD.GuiUp:
import FreeCADGui
from DraftTools import translate
else:
FreeCADGui = None
def translate(ctxt, txt): return txt
if open.__module__ in ['__builtin__','io']: pythonopen = open
disab... |
"""Constants for Neato integration."""
NEATO_DOMAIN = "neato"
CONF_VENDOR = "vendor"
NEATO_CONFIG = "neato_config"
NEATO_LOGIN = "neato_login"
NEATO_MAP_DATA = "neato_map_data"
NEATO_PERSISTENT_MAPS = "neato_persistent_maps"
NEATO_ROBOTS = "neato_robots"
SCAN_INTERVAL_MINUTES = 1
MODE = {1: "Eco", 2: "Turbo"}
ACTION = ... |
from abc import ABCMeta, abstractmethod
from typing import Any, Generic, Optional, List, Type, TypeVar, TYPE_CHECKING
from pyspark import since
from pyspark import SparkContext
from pyspark.sql import DataFrame
from pyspark.ml import Estimator, Predictor, PredictionModel, Transformer, Model
from pyspark.ml.base import ... |
class DonationError(Exception):
pass |
import errno
import inspect
import os
try:
import psutil
except ImportError:
psutil = None
from utils.platform import Platform
def is_my_process(pid):
"""
Check if the pid in the pid given corresponds to a running process
and if psutil is available, check if it's process corresponding to
the cur... |
from south.db import db
from south.v2 import SchemaMigration
from onadata.libs.data.db import rename_table_pending_creates
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('odk_viewer_columnrename', 'viewer_columnrename')
db.rename_table('odk_viewer_export', 'viewer_export'... |
from __future__ import unicode_literals
import collections
import copy
import datetime
import decimal
import math
import uuid
import warnings
from base64 import b64decode, b64encode
from functools import total_ordering
from django import forms
from django.apps import apps
from django.conf import settings
from django.co... |
import time, sys, signal, atexit
import pyupm_ublox6 as upmUblox6
myGPSSensor = upmUblox6.Ublox6(0)
def SIGINTHandler(signum, frame):
raise SystemExit
def exitHandler():
print "Exiting"
sys.exit(0)
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
if (not myGPSSensor.setupTty(upmUblox6.cvar.in... |
"""engine.SCons.Variables.PackageVariable
This file defines the option type for SCons implementing 'package
activation'.
To be used whenever a 'package' may be enabled/disabled and the
package path may be specified.
Usage example:
Examples:
x11=no (disables X11 support)
x11=yes (will search for the pac... |
from xml.etree.ElementTree import * |
"""
Internationalization support.
"""
import warnings
from contextlib import ContextDecorator
from decimal import ROUND_UP, Decimal
from django.utils.autoreload import autoreload_started, file_changed
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import lazy
from django.util... |
""" This module contains various functions that are special cases
of incomplete gamma functions. It should probably be renamed. """
from __future__ import print_function, division
from sympy.core import Add, S, C, sympify, cacheit, pi, I
from sympy.core.function import Function, ArgumentIndexError
from sympy.functi... |
from boto.gs.user import User
from boto.exception import InvalidAclError
ACCESS_CONTROL_LIST = 'AccessControlList'
ALL_AUTHENTICATED_USERS = 'AllAuthenticatedUsers'
ALL_USERS = 'AllUsers'
DOMAIN = 'Domain'
EMAIL_ADDRESS = 'EmailAddress'
ENTRY = 'Entry'
ENTRIES = 'Entries'
GROUP_BY_DOMAIN = 'GroupByDomain'
GROUP_BY_EMAI... |
from __future__ import print_function, division
from sympy.core import S, sympify, expand
from sympy.functions import Piecewise, piecewise_fold
from sympy.functions.elementary.piecewise import ExprCondPair
from sympy.sets.sets import Interval
def _add_splines(c, b1, d, b2):
"""Construct c*b1 + d*b2."""
if b1 ==... |
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellipse, Line
from kivy.gesture import Gesture, GestureDatabase
from my_gestures import cross, circle, check, square
def simplegesture(name, point_... |
from lettuce import world, step
from django.conf import settings
from common import upload_file
from nose.tools import assert_equal
TEST_ROOT = settings.COMMON_TEST_DATA_ROOT
@step(u'I go to the textbooks page')
def go_to_uploads(_step):
world.wait_for_js_to_load()
world.click_course_content()
menu_css = 'l... |
{
'name': "Easing properties input in sale order line",
'version': '8.0.1.0.0',
'category': 'Sales Management',
'author': "Agile Business Group,Odoo Community Association (OCA)",
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
"depends": [
'sale_mrp',
],
"data": [
... |
from heatclient.v1 import stacks
from openstack_dashboard.test.test_data import utils
TEMPLATE = """
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "AWS CloudFormation Sample Template.",
"Parameters": {
"KeyName": {
"Description": "Name of an EC2 Key Pair to enable SSH access to the instances",
"Type": "Str... |
import mock
from heat.db.sqlalchemy import filters as db_filters
from heat.tests import common
class ExactFilterTest(common.HeatTestCase):
def setUp(self):
super(ExactFilterTest, self).setUp()
self.query = mock.Mock()
self.model = mock.Mock()
def test_returns_same_query_for_empty_filters... |
from __future__ import absolute_import
__all__ = ["PerMessageDeflateMixin",
"PerMessageDeflateOffer",
"PerMessageDeflateOfferAccept",
"PerMessageDeflateResponse",
"PerMessageDeflateResponseAccept",
"PerMessageDeflate"]
import zlib
from autobahn.websocket.compress_b... |
import os
config.name = 'SafeStack'
config.test_source_root = os.path.dirname(__file__)
config.suffixes = ['.c', '.cpp', '.m', '.mm', '.ll', '.test']
config.substitutions.append( ("%clang_nosafestack ", config.clang + " -O0 -fno-sanitize=safe-stack ") )
config.substitutions.append( ("%clang_safestack ", config.clang + ... |
import urllib, httplib
import json
from app import app
from flask.ext.babel import gettext
from config import MS_TRANSLATOR_CLIENT_ID, MS_TRANSLATOR_CLIENT_SECRET
def microsoft_translate(text, sourceLang, destLang):
if MS_TRANSLATOR_CLIENT_ID == "" or MS_TRANSLATOR_CLIENT_SECRET == "":
return gettext('Error... |
from __future__ import absolute_import, division, print_function, \
with_statement
import hashlib
from shadowsocks.crypto import openssl
__all__ = ['ciphers']
def create_cipher(alg, key, iv, op, key_as_bytes=0, d=None, salt=None,
i=1, padding=1):
md5 = hashlib.md5()
md5.update(key)
md5... |
from pyga.requests import Q
def shutdown():
'''
Fire all stored GIF requests One by One.
You should call this if you set Config.queue_requests = True
'''
map(lambda func: func(), Q.REQ_ARRAY) |
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from .models import sts_backend
class TokenResponse(BaseResponse):
def get_session_token(self):
duration = int(self.querystring.get('DurationSeconds', [43200])[0])
token = sts_backend.get_session_token(duration=dura... |
from __future__ import absolute_import
from pychess.Utils.const import *
from .normal import NormalChess
from .corner import CornerChess
from .shuffle import ShuffleChess
from .fischerandom import FischerRandomChess
from .randomchess import RandomChess
from .asymmetricrandom import AsymmetricRandomChess
from .upsidedow... |
import operator, sys
from pyasn1.type import base, tag, constraint, namedtype, namedval, tagmap
from pyasn1.codec.ber import eoo
from pyasn1.compat import octets
from pyasn1 import error
class Integer(base.AbstractSimpleAsn1Item):
tagSet = baseTagSet = tag.initTagSet(
tag.Tag(tag.tagClassUniversal, tag.tagF... |
from . import procurement_order
from . import mrp_production |
from .services import (
Service,
Services
)
from .channels import (
Channel,
Channels
)
from .members import (
Member,
Members
)
from .messages import (
Message,
Messages
)
from .roles import (
Role,
Roles
)
from .users import (
User,
Users
)
from .credentials import (
... |
from contextlib import contextmanager
from mock import Mock
@contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
"""
Temporarily attaches a receiver to the provided ``signal`` within the scope
of the context manager.
Example use::
with mock_signal_receiver(signal) as receiver:... |
from sympy.polys.galoistools import (
gf_crt, gf_crt1, gf_crt2, gf_int,
gf_degree, gf_strip, gf_trunc, gf_normal,
gf_from_dict, gf_to_dict,
gf_from_int_poly, gf_to_int_poly,
gf_neg, gf_add_ground, gf_sub_ground, gf_mul_ground, gf_quo_ground,
gf_add, gf_sub, gf_add_mul, gf_sub_mul, gf_mul, gf_sqr... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import errno
import json
import os
import sys
from io import BytesIO, StringIO
from units.mock.procenv import ModuleTestCase, swap_stdin_and_argv
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock, mock... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from library.mo... |
"""
One-to-one relationships
To define a one-to-one relationship, use ``OneToOneField()``.
In this example, a ``Place`` optionally can be a ``Restaurant``.
"""
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__... |
__version__ = '0.3' |
from m5.SimObject import SimObject
from m5.params import *
from m5.proxy import *
class Process(SimObject):
type = 'Process'
abstract = True
cxx_header = "sim/process.hh"
input = Param.String('cin', "filename for stdin")
output = Param.String('cout', 'filename for stdout')
errout = Param.String(... |
import os
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
import build
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--skip-zip', action='store_true', dest='skip_zip', default=False,
help='Do not clean up z... |
import os
import sys
import string
import re
MAGIC = '\\input texinfo'
cmprog = re.compile('^@([a-z]+)([ \t]|$)') # Command (line-oriented)
blprog = re.compile('^[ \t]*$') # Blank line
kwprog = re.compile('@[a-z]+') # Keyword (embedded, usually
... |
"""
vcoptparse is short for Value-Centric Option Parser. It's a tiny argument parsing library. It has
less features than optparse or argparse, but it kicks more ass.
optparse and argparse allow the client to specify the flags that should be parsed, and as an
afterthought specify what keys should appear in the options d... |
import numpy as np
from bokeh.plotting import output_file, figure, show
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
output_file("legend_labels.html")
p = figure()
p.circle(x, y, legend="sin(x)")
p.line(x, y, legend="sin(x)")
p.line(x, 2*y, legend="2*sin(x)",
line_dash=[4, 4], line_color="orange", line_width=2... |
urlpatterns = []
handler400 = 'django.views.bad_handler'
handler403 = 'django.invalid_module.bad_handler'
handler404 = 'invalid_module.bad_handler'
handler500 = 'django' |
"""Configuration file parser.
A setup file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries, with continuations and such in
the style of RFC 822.
The option values can contain format strings which refer to other values in
the same section, or values in a special [DEFAULT] sectio... |
from twisted.spread import pb
from twisted.spread import banana
import os
import types
class Maildir(pb.Referenceable):
def __init__(self, directory, rootDirectory):
self.virtualDirectory = directory
self.rootDirectory = rootDirectory
self.directory = os.path.join(rootDirectory, directory)
... |
from gnuradio import gr
from gnuradio import audio
from gnuradio import blocks
from gnuradio.eng_option import eng_option
from optparse import OptionParser
class my_top_block(gr.top_block):
def __init__(self):
gr.top_block.__init__(self)
usage="%prog: [options] output_filename"
parser = Opti... |
"""Library Imports for Cluster Resolvers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.cluster_resolver.python.training.cluster_resolver import ClusterResolver
from tensorflow.contrib.cluster_resolver.python.training.cluster_reso... |
import sys
import libxml2
import StringIO
def testSimpleBufferWrites():
f = StringIO.StringIO()
buf = libxml2.createOutputBuffer(f, "ISO-8859-1")
buf.write(3, "foo")
buf.writeString("bar")
buf.close()
if f.getvalue() != "foobar":
print "Failed to save to StringIO"
sys.exit(1)
def... |
from django import template
register = template.Library()
@register.inclusion_tag('admin/prepopulated_fields_js.html', takes_context=True)
def prepopulated_fields_js(context):
"""
Creates a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inli... |
import os
import sys
import shutil
from optparse import make_option
from django.conf import settings
from django.core.files.storage import get_storage_class
from django.core.management.base import CommandError, NoArgsCommand
from django.utils.encoding import smart_str
from django.contrib.staticfiles import finders
clas... |
"""Tests for the selector module."""
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
import selectors
import unittest
class SelectorsTest(unittest.TestCase):
def testMaxRepeatCount(self):
self.assertEquals(selectors.MaxRepeatCount(range(1,10), 5),
selectors.MAX_REPEAT)
self.asser... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.