code stringlengths 1 199k |
|---|
from __future__ import absolute_import, print_function, unicode_literals, division
from jormungandr.scenarios.ridesharing.instant_system import InstantSystem, DEFAULT_INSTANT_SYSTEM_FEED_PUBLISHER
from jormungandr.scenarios.ridesharing.ridesharing_journey import Gender
from jormungandr.scenarios.ridesharing.ridesharing... |
from PyQt4 import QtCore, QtGui
class Page(QtGui.QWidget):
""" A container and dropevent catcher for widgets """
def __init__(self, parent, pihud):
super(Page, self).__init__(parent)
self.setAcceptDrops(True)
self.pihud = pihud # normally, this would simply be the parent()
self.w... |
from spack import *
class Hashcat(MakefilePackage):
"""hashcat is the world's fastest and most advanced password recovery
utility, supporting five unique modes of attack for over 300 highly
optimized hashing algorithms. hashcat currently supports CPUs, GPUs,
and other hardware accelerators on Linux, Win... |
import os, sys, signal, random
from datetime import datetime, timedelta
VLC_POOL_SIZE = 10 #number of vlc client to keep open
SPAWN_TIMER = 5 #number of seconds between vlc spawn
MAX_VLC_LIFE_TIME = 60 #max life time in seconds of a vlc client
VLC_COMMAND = '/usr/bin/vlc'
class Vlc(object):
def __init__(self, uri):
... |
from .module import BinckModule
__all__ = ['BinckModule'] |
from flask import Flask, jsonify, request, send_from_directory, make_response
from itsdangerous import Signer
import urllib2
from geopy.geocoders import Nominatim
from PIL import Image
import cv2, numpy
import uuid, os, random, time, json
app = Flask(__name__)
geolocator = Nominatim()
signer = Signer("*{0!0C}]P1>12&y,(... |
import sys
import os
if len(sys.argv) >= 4 :
filename = sys.argv[1]
row_i = int(sys.argv[2])-1
target_ls_filename = sys.argv[3]
output_filename = sys.argv[4]
else:
print("usage: python selectrow.py filename row_i target_ls_filename")
print("or ./selectrow.py filename row_i target_ls_filename")
... |
import abc
class BaseSolutionComparator(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def compare(self, sol1, sol2):
raise NotImplementedError() |
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import ClientMessage
from hazelcast.protocol.custom_codec import *
from hazelcast.util import ImmutableLazyDataList
from hazelcast.protocol.codec.map_message_type import *
REQUEST_TYPE = MAP_EXECUTEONALLKEYS
RESPONSE_TYPE = 117
RETRYABLE ... |
"""
Hangouts Chat bot that responds to events and messages from a room
synchronously. The bot formats the response using cards,
inserting widgets based upon the user's original input.
"""
import logging
from flask import Flask, render_template, request, json
app = Flask(__name__)
INTERACTIVE_TEXT_BUTTON_ACTION = "doTex... |
def testHasMasterPrimary(txnPoolNodeSet):
masterPrimaryCount = 0
for node in txnPoolNodeSet:
masterPrimaryCount += int(node.monitor.hasMasterPrimary)
assert masterPrimaryCount == 1 |
__author__ = 'Ostico <ostico@gmail.com>'
import sys
import os
import unittest
from pyorient.exceptions import *
from pyorient import OrientSocket
from pyorient.messages.database import *
from pyorient.messages.commands import *
from pyorient.messages.cluster import *
from pyorient.messages.records import *
from pyorien... |
from __future__ import absolute_import
import os
import time
from enable.component_editor import ComponentEditor
from traits.api import Instance
from traitsui.api import View, UItem
from numpy import array
from pychron.lasers.scanner import Scanner
from pychron.lasers.tasks.editors.laser_editor import LaserEditor
from ... |
from JumpScale.portal.macrolib import div_base
def main(j, args, params, *other_args):
return div_base.macro(j, args, params, self_closing=True, tag='input',
additional_tag_params={'type': 'email',
'pattern': r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~... |
"""Utility to invoke Xcode compiler toolchain"""
from __future__ import absolute_import as _abs
import os
import sys
import subprocess
import json
from .._ffi.base import py_str
from . import util
def xcrun(cmd):
"""Run xcrun and return the output.
Parameters
----------
cmd : list of str
The com... |
"""
This ETL DAG is compatible with Airflow 1.10.x (specifically tested with 1.10.12) and is referenced
as part of the documentation that goes along with the Airflow Functional DAG tutorial located
[here](https://airflow.apache.org/tutorial_decorated_flows.html)
"""
import json
from datetime import datetime
from textwr... |
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'account'
verbose_name = "EVE W-Space account module"
import account.profile_section_registry
import account.group_admin_section_registry
import account.user_admin_section_registry |
from neutron_lib.db import model_base
from neutron_lib.db import standard_attr
import sqlalchemy as sa
class ProvisioningBlock(model_base.BASEV2):
# the standard attr id of the thing we want to block
standard_attr_id = (
sa.Column(sa.BigInteger().with_variant(sa.Integer(), 'sqlite'),
s... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import open_zip
from pants.util.dirutil import safe_delete
from pants.util.... |
import collections
from .google import Google
from .github import GitHub
from .linkedin import LinkedIn
def addProvider(provider):
idMap[provider.getProviderName()] = provider
idMap = collections.OrderedDict()
addProvider(Google)
addProvider(GitHub)
addProvider(LinkedIn) |
from openstack import exceptions
from openstack import resource
from openstack import utils
class ServerGroup(resource.Resource):
resource_key = 'server_group'
resources_key = 'server_groups'
base_path = '/os-server-groups'
_query_mapping = resource.QueryParameters("all_projects")
_max_microversion ... |
"""Gradients for operators defined in control_flow_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import ops
from tensorflow.python.framework import... |
"""Abstract base class for kernel clients"""
import abc
class KernelClientABC(object):
"""KernelManager ABC.
The docstrings for this class can be found in the base implementation:
`IPython.kernel.client.KernelClient`
"""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def kernel(self):
... |
oauth_error_json = {'status': 'error', 'msg': "could not verify oauth credentials"}
upload_image_blob_error_json = {'status': 'error', 'msg': "failure to upload image to azure storage"}
upload_image_db_error_json = {'status': 'error', 'msg': "failure to upload metadata to documentdb"}
delete_image_blob_error_json = {'s... |
import collections
from importlib import import_module
import logging
import os
import pkgutil
from horizon.utils import file_discovery
from openstack_dashboard import theme_settings
def import_submodules(module):
"""Import all submodules and make them available in a dict."""
submodules = {}
for loader, nam... |
"""Let's Encrypt client crypto utility functions.
.. todo:: Make the transition to use PSS rather than PKCS1_v1_5 when the server
is capable of handling the signatures.
"""
import logging
import os
import OpenSSL
import zope.component
from acme import crypto_util as acme_crypto_util
from acme import jose
from letse... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from compose.config.config import ConfigDetails
from compose.config.config import ConfigFile
from compose.config.config import load
def build_config(contents, **kwargs):
return load(build_config_details(contents, **kwargs))
def... |
from ducktape.mark import parametrize
from ducktape.mark.resource import cluster
from kafkatest.tests.kafka_test import KafkaTest
from kafkatest.services.streams import StreamsEosTestDriverService, StreamsEosTestJobRunnerService, \
StreamsComplexEosTestJobRunnerService, StreamsEosTestVerifyRunnerService, StreamsCom... |
import math
import gzip
import paddle.v2 as paddle
import paddle.v2.evaluator as evaluator
import conll03
import itertools
train_data_file = 'data/train'
test_data_file = 'data/test'
vocab_file = 'data/vocab.txt'
target_file = 'data/target.txt'
emb_file = 'data/wordVectors.txt'
train_data_reader = conll03.train(train_d... |
import tensorflow as tf
import tensorflow_federated as tff
from utils.datasets import infinite_emnist
def _compute_dataset_length(dataset):
return dataset.reduce(0, lambda x, _: x + 1)
class InfiniteEmnistTest(tf.test.TestCase):
def test_element_type_structure_preserved(self):
raw_client_data = tff.simulation.d... |
"""Core event interfaces."""
from . import event
from . import exc
from . import util
from .engine import Connectable
from .engine import Dialect
from .engine import Engine
from .pool import Pool
from .sql.base import SchemaEventTarget
class DDLEvents(event.Events):
"""
Define event listeners for schema objects... |
import unittest
import numpy as np
from ..imutils import nan_to_zero, quantile_threshold, interpolate
class ImutilsTest(unittest.TestCase):
def test_nan_to_zero_with_ge_zero(self):
ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
for id... |
""" Module for all special column handlers for workflow objects """
import datetime
from ggrc import db
from ggrc import models
from ggrc.converters import errors
from ggrc.converters import get_importables
from ggrc.converters.handlers import handlers
from ggrc_basic_permissions import models as bp_models
from ggrc_wo... |
import base64
import os
import zipfile
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
try:
unicode
except NameError:
unicode = str
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.test.selenium.webdriver.... |
import re
import six
from sahara import conductor as c
from sahara import context
from sahara.i18n import _LI
from sahara.openstack.common import log as logging
from sahara.utils.notification import sender
conductor = c.API
LOG = logging.getLogger(__name__)
NATURAL_SORT_RE = re.compile('([0-9]+)')
def find_dict(iterabl... |
from __future__ import absolute_import
from django.contrib import admin
from django.contrib.admin.models import DELETION
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Permission
from django.core.urlresolvers import reverse
from django.utils.html import escape
from admin.common_a... |
import sys # reads command-line args
import ConfigParser
import os
config = ConfigParser.ConfigParser()
config.read(['os.cfg',
os.path.expanduser('~/.os.cfg'),
'/etc/os-maint/os.cfg'])
os_user_name = config.get('OPENSTACK', 'os_user_name')
os_password = config.get('OPENSTACK', 'os_password')
os_tenant_... |
"""Speedway iptables generator. This is a subclass of Iptables lib."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = 'watson@google.com (Tony Watson)'
from string import Template
from lib import iptables... |
"""This modules contains regression tests for config API handler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import api_regression_test_lib
from grr_response_server.gui.api_plugins import config as c... |
"""Provide an interface for growth experiments."""
from __future__ import absolute_import
import logging
from pandas import DataFrame
from memote.experimental.experiment import Experiment
__all__ = ("GrowthExperiment",)
LOGGER = logging.getLogger(__name__)
class GrowthExperiment(Experiment):
"""Represent a growth e... |
"""Support for RFXtrx devices."""
import asyncio
import binascii
from collections import OrderedDict
import copy
import logging
import RFXtrx as rfxtrxmod
import async_timeout
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA
from ... |
from tests import unittest
from twisted.internet import defer
from mock import Mock
from tests.utils import (
MockHttpResource, DeferredMockCallable, setup_test_homeserver
)
from synapse.api.filtering import Filter
from synapse.events import FrozenEvent
user_localpart = "test_user"
def MockEvent(**kwargs):
if "... |
from itertools import combinations, chain
from enum import Enum, auto
LINUX = 'linux'
OSX = 'osx'
WINDOWS = 'windows'
AMD64 = 'amd64'
ARM64 = 'arm64'
PPC64LE = 'ppc64le'
TRAVIS_TEMPLATE = """\
language: minimal
dist: focal
jobs:
include:
{jobs}
before_install:
- |-
if test -f "./scripts/$TRAVIS_OS_NAME/before_i... |
import re
from tempest.lib import exceptions
from neutronclient.tests.functional import base
class SimpleReadOnlyNeutronClientTest(base.ClientTestBase):
"""This is a first pass at a simple read only python-neutronclient test.
This only exercises client commands that are read only.
This should test commands:... |
import datetime
import logging
import lxml.html
import re
import urllib2
from urlparse import urlparse, urlunparse
from django.core.urlresolvers import reverse
from desktop.lib.view_util import format_duration_in_millis
from desktop.lib import i18n
from django.utils.html import escape
from filebrowser.views import loca... |
from rest_framework.serializers import ValidationError
from six import string_types
def has_id_field(value):
if value is None:
raise ValidationError('Nested object must contain an `id` attribute.')
if isinstance(value, string_types):
raise ValidationError(value) |
from peyotl.utility import get_logger
import re
from peyotl.git_storage import GitActionBase
_LOG = get_logger(__name__)
class MergeException(Exception):
pass
def get_filepath_for_id(repo_dir, amendment_id):
from peyotl.amendments import AMENDMENT_ID_PATTERN
assert bool(AMENDMENT_ID_PATTERN.match(amendment_... |
"""
$url teamliquid.net
$url tl.net
$type live
"""
import logging
import re
from urllib.parse import urlparse
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugins.afreeca import AfreecaTV
from streamlink.plugins.twitch import Twitch
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
... |
"""
@package mi.instrument.mclane.driver
@file marine-integrations/mi/instrument/mclane/driver.py
@author Dan Mergens
@brief Driver base class for McLane instruments
Release notes:
initial version
"""
import datetime
__author__ = 'Dan Mergens'
__license__ = 'Apache 2.0'
import re
import time
from mi.core.log import get... |
from __future__ import unicode_literals
from django.template.defaultfilters import slugify as django_slugify
from django.utils.importlib import import_module
from unidecode import unidecode
try:
from django.utils.timezone import now
except ImportError:
from datetime import datetime
now = datetime.now
def sl... |
from collections import namedtuple
from pandas.io.msgpack.exceptions import * # noqa
from pandas.io.msgpack._version import version # noqa
class ExtType(namedtuple("ExtType", "code data")):
"""ExtType represents ext type in msgpack."""
def __new__(cls, code, data):
if not isinstance(code, int):
... |
from django.conf.urls import include, url
from django.shortcuts import redirect
from olympia.stats.urls import stats_patterns
from . import views
ADDON_ID = r"""(?P<addon_id>[^/<>"']+)"""
detail_patterns = [
url('^$', views.addon_detail, name='addons.detail'),
url('^more$', views.addon_detail, name='addons.deta... |
import sys
import argparse
from bokpipe.bokastrom import scamp_solve
parser = argparse.ArgumentParser()
parser.add_argument("image",type=str,
help="input FITS image")
parser.add_argument("catalog",type=str,
help="input FITS catalog")
parser.add_argument("-a","--args",type=str,
... |
from os import path
__version__ = '0.0.22'
__version_full__ = __version__
def get_html_theme_path():
"""Return list of HTML theme paths."""
cur_dir = path.abspath(path.dirname(path.dirname(__file__)))
return cur_dir
def setup(app):
app.add_html_theme(
'divio_docs_theme',
path.abspath(pat... |
"""
sentry.db.models
~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from copy import copy
import logging
import six
from bitfield.types import BitHandler
from django.db import models
fro... |
import copy
from corehq.pillows.case import CasePillow
from corehq.pillows.mappings.reportcase_mapping import REPORT_CASE_MAPPING, REPORT_CASE_INDEX
from django.conf import settings
from .base import convert_property_dict
class ReportCasePillow(CasePillow):
"""
Simple/Common Case properties Indexer
an exten... |
import socket
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 5555))
s.listen(1)
while 1:
conn, addr = s.accept()
#data = conn.recv(1024)
conn.send("blabla".encode())
conn.close()
if __name__ == '__main__':
main() |
from django.dispatch import Signal
page_published = Signal(providing_args=['instance', 'revision'])
page_unpublished = Signal(providing_args=['instance'])
pre_page_move = Signal(providing_args=['instance', 'parent_page_before', 'parent_page_after', 'url_path_before', 'url_path_after'])
post_page_move = Signal(providing... |
import os
import datetime
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel impor... |
import os
import IECore
import Gaffer
import GafferUI
class AboutWindow( GafferUI.Window ) :
def __init__( self, about, **kw ) :
GafferUI.Window.__init__( self, title = "About " + about.name(), sizeMode=GafferUI.Window.SizeMode.Manual, borderWidth = 6, **kw )
self.__linkActivatedConnections = []
with self :
w... |
import datetime
from flask import g
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
Sequence,
String,
Table,
UniqueConstraint,
)
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import backref, relationship
from ... import Model
from .... |
from __future__ import absolute_import, unicode_literals
import csv
import datetime
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.encoding import smart_str
from django.utils.translation import u... |
class ResizeError(Exception):
pass
def codelengths_from_frequencies(freqs):
freqs = sorted(freqs.items(),
key=lambda item: (item[1], -item[0]), reverse=True)
nodes = [Node(char=key, weight=value) for (key, value) in freqs]
while len(nodes) > 1:
right, left = nodes.pop(), nodes.pop()
... |
""""
This module handles sending grades back to edX
Most of this module is a python 3 port of pylti (github.com/mitodl/sga-lti)
and should be moved back into that library.
"""
import uuid
from xml.etree import ElementTree as etree
import oauth2
from django.conf import settings
class SendGradeFailure(Exception):
"""... |
from .assign_role import AssignRoleBulkAction
from .delete import DeleteBulkAction
from .set_active_state import SetActiveStateBulkAction
__all__ = ["AssignRoleBulkAction", "DeleteBulkAction", "SetActiveStateBulkAction"] |
from contextlib import ContextDecorator
from operator import itemgetter
from wagtail.utils.apps import get_app_submodules
_hooks = {}
def register(hook_name, fn=None, order=0):
"""
Register hook for ``hook_name``. Can be used as a decorator::
@register('hook_name')
def my_hook(...):
... |
"""
sentry.management.commands.create_sample_event
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.core.management.base import BaseCommand, CommandError, make_option
class Command(BaseComma... |
import os
import numpy as np
import pytest
import pandas as pd
from pandas import (
Categorical,
DatetimeIndex,
Interval,
IntervalIndex,
NaT,
Series,
TimedeltaIndex,
Timestamp,
cut,
date_range,
isna,
qcut,
timedelta_range,
)
import pandas._testing as tm
from pandas.ap... |
import sys
sys.path.append("../..")
from facerec.dataset import DataSet
from facerec.feature import Fisherfaces
from facerec.distance import EuclideanDistance, CosineDistance
from facerec.classifier import NearestNeighbor
from facerec.classifier import SVM
from facerec.model import PredictableModel
from facerec.validat... |
"""
Tests for L{twisted.names.tap}.
"""
from twisted.trial.unittest import TestCase
from twisted.python.usage import UsageError
from twisted.names.tap import Options, _buildResolvers
from twisted.names.dns import PORT
from twisted.names.secondary import SecondaryAuthorityService
from twisted.names.resolve import Resolv... |
from math import inf
import pytest
import numpy as np
from astropy.cosmology.utils import inf_like, vectorize_if_needed, vectorize_redshift_method
from astropy.utils.exceptions import AstropyDeprecationWarning
def test_vectorize_redshift_method():
"""Test :func:`astropy.cosmology.utils.vectorize_redshift_method`.""... |
import os
import amo.search
from .models import Reindexing
from django.core.management.base import CommandError
is_reindexing_amo = Reindexing.objects.is_reindexing_amo
flag_reindexing_amo = Reindexing.objects.flag_reindexing_amo
unflag_reindexing_amo = Reindexing.objects.unflag_reindexing_amo
get_indices = Reindexing.... |
from django.http import Http404
from django.shortcuts import render_to_response
from django.conf import settings
from django.template import RequestContext
from django.core.cache import parse_backend_uri
from django_memcached.util import get_memcached_stats
from django.contrib.auth.decorators import user_passes_test
_,... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
import bokeh.util.string as bus
class Test_escape(object):
def test_default_quote(self):
assert bus.escape("foo'bar") == "foo'bar"
assert bus.escape('foo"bar') == "foo"bar"
def tes... |
from morepath import compat
def test_text_type():
assert isinstance(u'foo', compat.text_type)
assert not isinstance(b'foo', compat.text_type)
def test_string_types():
assert isinstance('foo', compat.string_types)
assert isinstance(u'foo', compat.string_types)
if compat.PY3:
assert not isinst... |
"""
Component to interface with cameras.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/camera/
"""
import asyncio
import logging
from aiohttp import web
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import E... |
"""Test gettxoutproof and verifytxoutproof RPCs."""
from test_framework.messages import CMerkleBlock, FromHex, ToHex
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
from test_framework.wallet import MiniWallet
class MerkleBlockTest(Bit... |
from unittest import TestCase
import validictory
class TestItems(TestCase):
def test_property(self):
schema = {
"type": "object",
"properties": {
"foo": {
"default": "bar"
},
"baz": {
"type": "int... |
from distutils.core import setup
setup(name='python-hivemindrpc',
version='0.1',
description='Enhanced version of python-jsonrpc for use with Hivemind',
long_description=open('README').read(),
author='Jeff Garzik',
author_email='<jgarzik@exmulti.com>',
maintainer='Jeff Garzik',
... |
import unittest
import numpy as np
import six
import chainer
from chainer import cuda
import chainer.functions as F
from chainer import optimizers
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
if cuda.available:
cuda.init()
class LinearModel(object):
UNIT_NUM... |
try:
# The 'demandimport' breaks pyflakes and flake8._pyflakes
from mercurial import demandimport
except ImportError:
pass
else:
demandimport.disable()
import os
import pep8
import pyflakes
import pyflakes.checker
def patch_pyflakes():
"""Add error codes to Pyflakes messages."""
codes = dict([li... |
__version_info__ = (2, 4, 2)
__version__ = ".".join(map(str, __version_info__)) |
import sys
import argparse
import argcomplete
import azure.cli.core.telemetry as telemetry
import azure.cli.core._help as _help
from azure.cli.core.util import CLIError
from azure.cli.core._pkg_util import handle_module_not_installed
import azure.cli.core.azlogging as azlogging
logger = azlogging.get_az_logger(__name__... |
"""'functions describe' command."""
from googlecloudsdk.api_lib.functions import util
from googlecloudsdk.calliope import base
from googlecloudsdk.core import properties
class Describe(base.DescribeCommand):
"""Show description of a function."""
@staticmethod
def Args(parser):
"""Register flags for this comma... |
from __future__ import unicode_literals
from frappe.model.document import Document
class InstalledApplication(Document):
pass |
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure(figsize=(9, 3))
map = Basemap(width=12000000,height=8000000,
resolution='l',projection='stere',
lat_ts=50,lat_0=50,lon_0=-107.)
lons, lats, x, y = map.makegrid(30, 30, returnxy=True)
ax = f... |
"""BitBake Persistent Data Store
Used to store data in a central location such that other threads/tasks can
access them at some future date. Acts as a convenience wrapper around sqlite,
currently, providing a key/value store accessed by 'domain'.
"""
import collections
import logging
import os.path
import sys
import w... |
from django.db import models
from django.core.validators import validate_email, validate_slug, validate_ipv46_address
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from ava.core.models import TimeStampedModel
from ava.core_group.models import Group
from ava.core_identit... |
import math
def square_root ( a ):
"""Computes squar root of a
"""
espilon = 0.1e-11
x = a
while True:
y = ( x + a / x ) / 2.0
if abs( y - x ) < espilon:
return y
x = y
def test_square_root():
"""Compares custom square and math.sqrt.
"""
a = 1.0
wh... |
import os
import unittest
import mock
from pulp.server.db import connection
class PulpWebservicesTests(unittest.TestCase):
"""
Base class for tests of webservice controllers. This base is used to work around the
authentication tests for each each method
"""
def setUp(self):
connection.initi... |
""" (disabled by default) support for testing pytest and pytest plugins. """
from __future__ import absolute_import, division, print_function
import codecs
import gc
import os
import platform
import re
import subprocess
import sys
import time
import traceback
from fnmatch import fnmatch
from weakref import WeakKeyDicti... |
"""Tests for memorizingfile module."""
import StringIO
import unittest
import config # This must be imported before mod_pywebsocket.
from mod_pywebsocket import memorizingfile
class UtilTest(unittest.TestCase):
def check(self, memorizing_file, num_read, expected_list):
for unused in range(num_read):
... |
'''
ListAdapter
=================
.. versionadded:: 1.5
.. warning::
This code is still experimental, and its API is subject to change in a
future version.
A :class:`ListAdapter` is an adapter around a python list.
Selection operations are a main concern for the class.
From an :class:`Adapter`, a :class:`ListAd... |
"""HTTP related handlers.
Note that some other HTTP handlers live in more specific modules: _auth.py,
_gzip.py, etc.
Copyright 2002-2006 John J Lee <jjl@pobox.com>
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the file
COPYING.txt included with ... |
from __future__ import print_function
import six.moves.cPickle as pickle
import os
import sys
import theano
from six import iteritems, itervalues
DISPLAY_DUPLICATE_KEYS = False
DISPLAY_MOST_FREQUENT_DUPLICATE_CCODE = False
dirs = []
if len(sys.argv) > 1:
for compiledir in sys.argv[1:]:
dirs.extend([os.path.... |
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=video 0 RTP/AVP 100
m=audio 5000 RTP/AVP 0
"""
pjsua_args = "--null-audio --auto-answer 200"
extra_headers = ""
include = ["Content-Type: application/sdp", # response must include SDP
"m=video 0 RTP/A... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_iam_role
description:
- A role in the Identity and Access Management API .
short_description: Creat... |
class Token:
"""
Class representing a token.
kind: the kind of token, e.g. filename, number, other
value: specific instance value, e.g. "/tmp/foo.c", or 5
offset: byte offset from start of parse string
"""
def __init__(self, kind, value=None, offset=None):
self.offset = offset
... |
import os
from kivy.clock import Clock
from kivy.uix.rst import RstDocument
from libs.uix.dialogs import dialog, card
class ShowLicense(object):
def show_license(self, *args):
def choice_language_license(on_language):
window = dialog(text=self.data.string_lang_wait, title=self.title)
... |
props.bf_Shank_Dia = 5.0
props.bf_Pitch = 0.5 # Fine
props.bf_Crest_Percent = 10
props.bf_Root_Percent = 10
props.bf_Major_Dia = 5.0
props.bf_Minor_Dia = props.bf_Major_Dia - (1.082532 * props.bf_Pitch)
props.bf_Hex_Head_Flat_Distance = 8.0
props.bf_Hex_Head_Height = 3.5
props.bf_Cap_Head_Dia = 8.5
props.bf_Cap_Head_H... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.