content stringlengths 4 20k |
|---|
from openerp.tests.common import TransactionCase
class TestCreateInvoice(TransactionCase):
def setUp(self):
super(TestCreateInvoice, self).setUp()
self.Wizard = self.env['stock.invoice.onshipping']
self.customer = self.env.ref('base.res_partner_3')
product = self.env.ref('product... |
import samba.getopt as options
from samba.dcerpc import security
from samba.samdb import SamDB
from samba.ndr import ndr_unpack, ndr_pack
from samba.dcerpc.security import (
GUID_DRS_ALLOCATE_RIDS, GUID_DRS_CHANGE_DOMAIN_MASTER,
GUID_DRS_CHANGE_INFR_MASTER, GUID_DRS_CHANGE_PDC,
GUID_DRS_CHANGE_RID_MASTER, G... |
# Example of file descriptor passing using multiprocessing
import multiprocessing
from multiprocessing.reduction import recv_handle, send_handle
import socket
def worker(in_p, out_p):
out_p.close()
while True:
fd = recv_handle(in_p)
print('CHILD: GOT FD', fd)
with socket.socket(socket.... |
from openerp.osv import orm
class GroupsView(orm.Model):
"""
Add group in user simplified form
"""
_inherit = 'res.groups'
def get_simplified_groups_by_application(self, cr, uid, context=None):
""" return all groups classified by application (module category),
as a list of pairs... |
from DefaultKIDSBuildInstaller import DefaultKIDSBuildInstaller
from VistAMenuUtil import VistAMenuUtil
import re
inputRegEx = re.compile("INPUT TO WHAT FILE", re.I)
""" This is an example of custom installer to handle post install questions
Requirement for custom installer python script:
1. Must be a class n... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_owner
version_added: "2.1"
short_description: Set owner
description:
- Set owner of files or directories.
options:
path:
description:
... |
from nova import context
from nova import db
from nova import exception
from nova.objects import migration
from nova.openstack.common import timeutils
from nova.tests import fake_instance
from nova.tests.objects import test_objects
NOW = timeutils.utcnow().replace(microsecond=0)
def fake_db_migration(**updates):
... |
""" This module removes all objects/arrays from JS source code and replace them with LVALS.
Also it has s function translating removed object/array to python code.
Use this module just after removing constants. Later move on to removing functions"""
OBJECT_LVAL = 'PyJsLvalObject%d_'
ARRAY_LVAL = 'PyJsLvalArray%d_'
fro... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
compat_urllib_request,
)
from ..utils import (
int_or_none,
parse_duration,
parse_filesize,
)
class MinhatecaIE(InfoExtractor):
_VALID_URL = r'https?://minhate... |
from pip.locations import build_prefix, src_prefix
from pip.util import display_path, backup_dir
from pip.log import logger
from pip.exceptions import InstallationError
from pip.commands.install import InstallCommand
class BundleCommand(InstallCommand):
name = 'bundle'
usage = '%prog [OPTIONS] BUNDLE_NAME.pyb... |
from __future__ import with_statement
import os
def vs9to8(src, dest):
for name in os.listdir(src):
path, ext = os.path.splitext(name)
if ext.lower() not in ('.sln', '.vcproj', '.vsprops'):
continue
filename = os.path.normpath(os.path.join(src, name))
destname = os.path... |
"""
Created on 2 May 2019
@author: Bruno Beloff (<EMAIL>)
"""
from collections import OrderedDict
from scs_core.data.datetime import LocalizedDatetime
from scs_core.data.datum import Datum
from scs_core.data.json import JSONable
from scs_core.particulate.pmx_datum import PMxDatum
from scs_core.sample.sample import ... |
#!/usr/bin/python
import urllib2
import json
import re
import sys
from optparse import OptionParser
sys.path.append('~/floodlight/target/gen-py')
sys.path.append('~/floodlight/thrift/lib/py')
from packetstreamer import PacketStreamer
from packetstreamer.ttypes import *
from thrift import Thrift
from thrift.transpo... |
#!./uwsgi --http-socket :9090 --http-raw-body --gevent 100 --module tests.websockets_chat_2
import uwsgi
import time
import gevent
from gevent.queue import Queue
class ClientManager(object):
clients = set()
@classmethod
def add(cls, client):
cls.clients.add(client)
@classmethod
def remo... |
import argparse
import logging
from config.script.import_script import ImportScript
LOG = logging.getLogger(__name__)
def init(subparsers: argparse._SubParsersAction):
"""
Command line subparser for importing a script.
The following arguments can be interpreted by the subprocessor:
:Name: Name of ... |
"""OSX platform implementation."""
import errno
import os
import sys
from psutil import _common
from psutil import _psposix
from psutil._common import conn_tmap, usage_percent, isfile_strict
from psutil._compat import namedtuple, wraps
import _psutil_osx as cext
import _psutil_posix
__extra__all__ = []
# --- const... |
# -*- coding: utf-8 -*-
from flask_peewee.admin import Admin, ModelAdmin
from auth import auth
from app import app
from models import User, Project, Download, Addon
class UserAdmin(ModelAdmin):
columns = ('username', 'email', 'admin',)
def save_model(self, instance, form, adding=False):
"""
... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from textwrap import dedent
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import temporary_dir
from pants_test.pants_ru... |
import create_bwc_index
import logging
import os
import random
import shutil
import subprocess
import sys
import tempfile
def fetch_version(version):
logging.info('fetching ES version %s' % version)
if subprocess.call([sys.executable, os.path.join(os.path.split(sys.argv[0])[0], 'get-bwc-version.py'), version]) != ... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.testtools
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module implements extended wrappers for simplified testing.
`TestResponse`
A response wrapper which adds various cached attributes for
simplified assertions on various content types.
:copyright:... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import base64
import json
import os
import pipes
import stat
import tempfile
from ansible import constants as C
from ansible.plugins.action import ActionBase
from ansible.utils.boolean import boolean
from ansible.utils.hashing imp... |
"""Scapy Dissector for Ethernet/IP Implicit I/O messages at the Ring Level of the
Secure Water Testbed (SWaT) at the Singapore University of Technology and Design
Documentation: SWaT's Control Panels and Electrical Drawings manual.
"""
from scapy.main import interact
from swat import *
banner = 'Add-on: Scapy Dissect... |
import os.path
from django.conf import settings
from mock import patch
from bedrock.mozorg.tests import TestCase
from bedrock.security.management.commands import update_security_advisories
from bedrock.security.models import Product
def test_fix_product_name():
"""Should fix SeaMonkey and strip '.0' from names... |
import itertools
from ShCommands import Command, Pipeline
def tcl_preprocess(data):
# Tcl has a preprocessing step to replace escaped newlines.
i = data.find('\\\n')
if i == -1:
return data
# Replace '\\\n' and subsequent whitespace by a single space.
n = len(data)
str = data[:i]
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from six import iteritems, string_types
import os
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject
from ansible.playbook.attribute import Attribute, FieldA... |
"""
The Request class is used as a wrapper around the standard request object.
The wrapped request then offers a richer API, in particular :
- content automatically parsed according to `Content-Type` header,
and available as `request.data`
- full support of PUT method, including support for file uploads... |
import os
import numpy as np
import matplotlib.pyplot as plt
from kitti.data import get_drives, image_shape, data_dir, Calib
from kitti.raw import load_stereo_frame
from kitti.velodyne import load_velodyne_points
def test_get_drives():
drives = get_drives()
print drives
def test_disp2rect():
drive = ... |
# flake8: noqa
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
config,
debug):
''' Const... |
from fife import fifechan
from fife.extensions.pychan.attrs import UnicodeAttr
from common import gui2text, text2gui
from widget import Widget
class TextField(Widget):
"""
An editable B{single line} text edit widget.
New Attributes
==============
- text: The text in the TextBox.
Data
====
The text can... |
from time import time
from django.conf import settings
from django.db.models import F
from django.dispatch import receiver
from misago.forums.models import Forum
from misago.threads.views.moderatedcontent import ModeratedContent
from misago.threads.views.newthreads import NewThreads
from misago.threads.views.unreadt... |
"""Shim for systems that need to load both SessionBundle and SavedModel.
This is intended to be used during migration to SavedModel.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.contrib.session_bundle import constants as le... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('monitoring', '0004_monitoring_metric_type'),
]
operations = [
migrations.CreateModel(
name='OWSService',
fields=[
('id', mod... |
import json #JSON Encoder and Decoder library
from datetime import datetime
#TODO: Update/Remove default values of arguments
## JSONmodule
# This class controls file IO and stores entries in a map
class JSONmodule:
##The constructor
#@param filename A file containg the entries in valud JSON
... |
import docker
from .. import mock
from .. import unittest
from ..helpers import BUSYBOX_IMAGE_WITH_TAG
from compose.const import LABEL_ONE_OFF
from compose.const import LABEL_SLUG
from compose.container import Container
from compose.container import get_container_name
class ContainerTest(unittest.TestCase):
def... |
"""CodeContext - Extension to display the block context above the edit window
Once code has scrolled off the top of a window, it can be difficult to
determine which block you are in. This extension implements a pane at the top
of each IDLE edit window which provides block structure hints. These hints are
the lines w... |
import os
import boto3
from botocore.exceptions import DataNotFoundError
from botocore.docs.service import ServiceDocumenter as BaseServiceDocumenter
from botocore.docs.bcdoc.restdoc import DocumentStructure
from boto3.utils import ServiceContext
from boto3.docs.client import Boto3ClientDocumenter
from boto3.docs.res... |
#!/usr/bin/env python
#
# Looks for registration routines in the protocol dissectors,
# and assembles C code to call all the routines.
#
# This is a Python version of the make-reg-dotc shell script.
# Running the shell script on Win32 is very very slow because of
# all the process-launching that goes on --- multiple gr... |
# -*- coding: utf-8 -*-
from manabi.test_helpers import (
ManabiTestCase,
)
from manabi.apps.furigana.inject import inject_furigana
FURIGANA_POSITION_START = 0
FURIGANA_POSITION_END = 1
FURIGANA_POSITION_FURIGANA = 2
class FuriganaInjectionAPITest(ManabiTestCase):
def test_plain_ascii_text(self):
a... |
#!/usr/bin/env python
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCas... |
import pandas as pd
import numpy as np
from sklearn import svm, cross_validation
from sklearn.metrics import mean_squared_error
from math import sqrt
from sklearn import preprocessing
train = pd.read_csv('training.csv')
test = pd.read_csv('sorted_test.csv')
labels = train[['Ca','P','pH','SOC','Sand']].values
train_lab... |
import typing as T
from .. import coredata
from ..mesonlib import MachineChoice, OptionKey
from .compilers import Compiler
from .mixins.clike import CLikeCompiler
from .mixins.gnu import GnuCompiler
from .mixins.clang import ClangCompiler
if T.TYPE_CHECKING:
from ..programs import ExternalProgram
from ..envc... |
"""
Bit sized classes:
- Bit: Single bit, value is False or True ;
- Bits: Integer with a size in bits ;
- RawBits: unknown content with a size in bits.
"""
from hachoir_core.field import Field
from hachoir_core.i18n import _
from hachoir_core import config
class RawBits(Field):
"""
Unknown content with a siz... |
from wydget import anim
from wydget.widgets.frame import Frame
class Drawer(Frame):
'''A *transparent container* that may hide and expose its contents.
'''
name='drawer'
HIDDEN='hidden'
EXPOSED='exposed'
LEFT='left'
RIGHT='right'
TOP='top'
BOTTOM='bottom'
def __init__(self, pa... |
from bz2 import BZ2File
import gzip
from io import BytesIO
import numpy as np
import os
import shutil
from tempfile import NamedTemporaryFile
from sklearn.externals.six import b
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class GazetaIE(InfoExtractor):
_VALID_URL = r'(?P<url>https?://(?:www\.)?gazeta\.ru/(?:[^/]+/)?video/(?:main/)*(?:\d{4}/\d{2}/\d{2}/)?(?P<id>[A-Za-z0-9-_.]+)\.s?html)'
_TESTS = [{
'url': 'http://www.g... |
#!/usr/bin/env python2
import argparse
import csv
import logging
import multiprocessing
import os
from PIL import Image
def image_to_csv(input_file):
prefix, _ = os.path.splitext(input_file)
output_file = prefix + ".csv"
logging.debug("Converting %s to %s.", input_file, output_file)
with Image.open(i... |
import subprocess
def gather_lldp():
cmd = ['lldpctl', '-f', 'keyvalue']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
(output, err) = proc.communicate()
if output:
output_dict = {}
lldp_entries = output.split("\n")
for entry in lldp_entries:
if entry:
... |
"""
Soundcloud Tag
--------------
This implements a Liquid-style soundcloud tag for Pelican.
It asks the official Soundcloud-API for the widget html code.
Syntax
------
`{% soundcloud track_url %}`
Example
-------
`{% soundcloud https://soundcloud.com/luftmentsh/hakotel %}`
Output
------
`<iframe width="100%" heigh... |
import os
import shutil
import unittest
import tempfile
from telemetry.core import util
from telemetry.internal.backends.chrome import crx_id
class CrxIdUnittest(unittest.TestCase):
CRX_ID_DIR = util.GetUnittestDataDir()
PACKED_CRX = os.path.join(CRX_ID_DIR,
'jebgalgnebhfojomionfpkfel... |
from __future__ import absolute_import
try:
import unittest
unittest.skip
from unittest.util import safe_repr, unorderable_list_difference
except AttributeError:
import unittest2 as unittest
from unittest2.util import safe_repr, unorderable_list_difference # noqa
import importlib
import logging
i... |
import unittest
from django import forms as django_forms
from .. import models, forms
class ParticipanteFormTestCase(unittest.TestCase):
def test_deve_ser_um_ModelForm(self):
assert issubclass(forms.ParticipanteForm, django_forms.ModelForm)
def test_model_deve_ser_Participante(self):
self.... |
#!/usr/bin/env python2
# coding=utf8
from BeautifulSoup import BeautifulSoup, SoupStrainer
from htmlentitydefs import name2codepoint
from urllib2 import urlopen
from urlparse import urljoin, urlparse, urlunparse
import argparse
import cgi
import codecs
import logging
import os
import re
import xml.etree.ElementTree
MZ... |
import collections
from django.utils import six
from django.core.paginator import PageNotAnInteger, EmptyPage
class DatastorePaginator(object):
"""
A paginator which only supports previous/next page controls and avoids doing
expensive count() calls on datastore-backed queries.
Does not implement the... |
"""
Make-based build system
"""
from rez.build_system import BuildSystem
import os.path
class MakeBuildSystem(BuildSystem):
@classmethod
def name(cls):
return "make"
@classmethod
def is_valid_root(cls, path, package=None):
return os.path.isfile(os.path.join(path, "Makefile"))
def... |
from __future__ import division
import matplotlib.pyplot as plt
import pdb
from columns_contain import columns_contain
from Month import Month
cc = columns_contain
def make_chart_a(reduction, median_prices, control):
'graph range of errors by month by method'
print 'make_chart_a'
def make_subplot(valid... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr, flt
import json
class ItemVariantExistsError(frappe.ValidationError): pass
class InvalidItemAttributeValueError(frappe.ValidationError): pass
class ItemTemplateCannotHaveStock(frappe.ValidationError): pass
@frapp... |
# -*- coding: utf-8 -*-
"""MongoDB backend for celery."""
from __future__ import absolute_import
from datetime import datetime
try:
import pymongo
except ImportError: # pragma: no cover
pymongo = None # noqa
if pymongo:
try:
from bson.binary import Binary
except ImportError: ... |
"""DevTools JSDoc validator presubmit script
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
import sys
def _ValidateHashes(input_api, output_api):
sys.path.append(input_api.PresubmitLocalPath())
import build_jsdoc_vali... |
from paste.util.mimeparse import *
def test_parse_mime_type():
parse = parse_mime_type
assert parse('*/*') == ('*', '*', {})
assert parse('text/html') == ('text', 'html', {})
assert parse('audio/*; q=0.2') == ('audio', '*', {'q': '0.2'})
assert parse('text/x-dvi;level=1') == ('text', 'x-dvi', {'lev... |
################################################################################################
# http://people.brunel.ac.uk/~mastjjb/jeb/orlib/mknapinfo.html #
################################################################################################
def parse_mknap1(path_to_fi... |
import openerp
from openerp.addons.connector.connector import Binder
from ..backend import magento
class MagentoBinder(Binder):
""" Generic Binder for Magento """
@magento
class MagentoModelBinder(MagentoBinder):
"""
Bindings are done directly on the binding model.
Binding models are models called ... |
from gi.repository import GObject, Gedit, PeasGtk
from .config_dialog import ConfigDialog
from .config_settings import ConfigSettings
from .document_manipulator import DocumentManipulator
class WhitespaceRemoverWindowActivatable(GObject.Object,
Gedit.WindowActivatable,
... |
#coding=utf-8
import tornado.web, re
from controller.base import BaseHandler
from tornado import gen
import time, pymongo
from util.function import intval
from bson.objectid import ObjectId
class AdminHandler(BaseHandler):
def initialize(self):
super(AdminHandler, self).initialize()
self.topbar = "admin"
def pr... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.enos... |
import os, sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = PROJECT_ROOT.split(os.sep)[-1]
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
full_path = lambda *parts: os.path.join(PROJECT_ROOT, *parts)
example_path = full_path("..", "..")
if example_path not in sys.path... |
import os
import time
import sys
import fcntl
import subprocess
import threading
import logging
# kaa imports
import kaa
import kaa.rpc
# kaa.candy imports
from widgets import Group, Widget, POSSIBLE_PLAYER
import candyxml
# get logging object
log = logging.getLogger('kaa.candy')
# turn on internal debug
DEBUG = F... |
#
# Performs advance renewals of domain names that are coming to term soon.
#
# Use:
#
# account_reference=$YOUR_ACCOUNT_REF api_key=$YOUR_API_KEY python3 renew_in_advance.py
#
from metaname import Client as Metaname
import os
from datetime import datetime
RENEW_DAYS_PRIOR = 28
#ENDPOINT = 'https://metaname.... |
"""gstreamerrenderer.py -- Linux gstreamer renderer """
import logging
import os
import sys
import pygst
pygst.require('0.10')
import gst
from miro import app
from miro.frontends.widgets.gst import renderer
from miro.plat import options
# We need to define get_item_type(). Use the version from sniffer.
from miro.f... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ur... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class ZapWalletTXesTest (BitcoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 3)
def setup_network(s... |
#!/usr/bin/env python
# encoding: utf-8
"""
gbenchmark is a Waf tool for benchmark builds in Ardupilot
"""
from waflib import Build, Context, Task
from waflib.Configure import conf
from waflib.TaskGen import feature, before_method, after_method
from waflib.Errors import WafError
def configure(cfg):
env = cfg.env... |
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal, assert_raises
from skimage import data, img_as_float
from skimage.morphology import diamond
from skimage.feature import match_template, peak_local_max
def test_template():
size = 100
# Float prefactors ensure that image range is ... |
from unittest import TestCase
from .unicodetoascii import to_ascii, clean_string
class ToAsciiConverterTest(TestCase):
def TestCase(self):
self.assertEqual(to_ascii('a'), 'a')
self.assertEqual(to_ascii('aÀ'), 'aA')
self.assertEqual(to_ascii('aÀÄ'), 'aAA')
self.assertEqual(to_ascii... |
import argparse
import asyncio
import importlib
import inspect
from typing import Mapping
class CommandNotFound(RuntimeError):
pass
def kwargs_from_argv(params, ns, argv):
parser = argparse.ArgumentParser()
for i in params:
p = params[i]
if p.annotation is p.empty:
parser.add... |
#!/usr/bin/env python
"""Train an LSTM network to recognize the embedded Reber grammar."""
import random
import numpy as np
# State transition table
TRANSITIONS = [
[('T', 1), ('P', 2)], # 0=B
[('X', 3), ('S', 1)], # 1=BT
[('V', 4), ('T', 2)], # 2=BP
[('X', 2), ('S', 5)], # 3=BTX
[('P', 3), (... |
import CTK
from Rule import RulePlugin
from util import *
URL_APPLY = '/plugin/header/apply'
NOTE_HEADER = N_("Header against which the regular expression will be evaluated.")
NOTE_MATCH = N_("Regular expression.")
NOTE_TYPES = N_("It defines how this match has to be evaluated.")
HEADERS = [
('Accept-Encoding... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
"""
Tests in this module will be skipped unless:
- ovsdb-client is installed
- ovsdb-client can be invoked password-less via the configured root helper
- sudo testing is enabled (see neutron.tests.functional.base for details)
"""
import eventlet
from oslo_config import cfg
from neutron.agent.linux import ovsdb_... |
import atexit
import logging
from pylib import android_commands
from pylib.device import device_utils
class PerfControl(object):
"""Provides methods for setting the performance mode of a device."""
_SCALING_GOVERNOR_FMT = (
'/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor')
_CPU_ONLINE_FMT = '/sys/... |
"""
This module defines storage technologies. It builds on top of generic
generators, adding components for deciding how much energy to build into
storage, when to charge, energy accounting, etc.
"""
from pyomo.environ import *
import os
from switch_mod.financials import capital_recovery_factor as crf
dependencies = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
fit_ellipse.py
Efficient fitting of an ellipse to a set of data points
using largest eigenvalues. Code taken from
http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
They used the approach from
Fitzgibbon, Pilu and Fischer in Fitzgibbon... |
"""
This module is for the miscellaneous GEOS routines, particularly the
ones that return the area, distance, and length.
"""
from ctypes import c_int, c_double, POINTER
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE
from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string
f... |
# -*- coding: UTF-8 -*-
"""Easy to use object-oriented thread pool framework.
A thread pool is an object that maintains a pool of worker threads to perform
time consuming operations in parallel. It assigns jobs to the threads
by putting them in a work request queue, where they are picked up by the
next available threa... |
from django.core.signals import request_finished
from django.db.models.signals import post_delete, post_save
from .base import CachedDict, NoValue
try:
from celery.signals import task_postrun
except ImportError: # pragma: no cover
# celery must not be installed
has_celery = False # pragma: no cover
else... |
import locust
from . import runners
import gevent
import sys
import os
import signal
import inspect
import logging
import socket
import time
from optparse import OptionParser
from . import web
from .log import setup_logging, console_logger
from .stats import stats_printer, print_percentile_stats, print_error_report, ... |
from runners.core import ZephyrBinaryRunner
def test_runner_imports():
# Ensure that all runner modules are imported and returned by
# get_runners().
#
# This is just a basic sanity check against errors introduced by
# tree-wide refactorings for runners that don't have their own
# test suites.
... |
from OpenSSL.crypto import FILETYPE_PEM
from twisted.internet.ssl import PrivateCertificate, KeyPair
from axiom.item import Item
from axiom.attributes import text
from axiom.dependency import installOn
from axiom.test.historic.stubloader import saveStub
from xmantissa.port import TCPPort, SSLPort
from xmantissa.webs... |
from django.db.backends.sqlite3.schema import DatabaseSchemaEditor
from django.db.utils import DatabaseError
class SpatialiteSchemaEditor(DatabaseSchemaEditor):
sql_add_geometry_column = (
"SELECT AddGeometryColumn(%(table)s, %(column)s, %(srid)s, "
"%(geom_type)s, %(dim)s, %(null)s)"
)
sq... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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.
T... |
"""ZeroOut ops 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_... |
import bcrypt
import json
from django.conf import settings
from django.core.mail import send_mail
import applications.graphs as graphs
import applications.users.dal as db
from graphspace.exceptions import BadRequest, ErrorCodes
from graphspace.utils import generate_uid
# import the logging library
import logging
# ... |
import testtools
from tempest.common import compute
from tempest.common import utils
from tempest.common import waiters
from tempest import config
from tempest.lib import decorators
from tempest.scenario import manager
CONF = config.CONF
class TestShelveInstance(manager.ScenarioTest):
"""This test shelves then ... |
# -*- coding: utf-8 -*-
"""
End-to-end tests for the LMS.
"""
from common.test.acceptance.fixtures.course import CourseFixture
from common.test.acceptance.pages.common.auto_auth import AutoAuthPage
from common.test.acceptance.pages.lms.course_home import CourseHomePage
from common.test.acceptance.pages.lms.course_wik... |
# coding: utf-8
"""zmq poll function"""
# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.
from ._cffi import C, ffi
from .utils import _retry_sys_call
def _make_zmq_pollitem(socket, flags):
zmq_socket = socket._zmq_socket
zmq_pollitem = ffi.new('zmq_pollitem_t*')
... |
"""Implementation of Cluster Resolvers for Cloud TPUs."""
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.python.training.server_lib import Clus... |
def execute():
import webnotes
from webnotes.model import delete_doc
from webnotes.model.code import get_obj
from webnotes.model.doc import addchild
# delete doctypes and tables
for dt in ["TDS Payment", "TDS Return Acknowledgement", "Form 16A",
"TDS Rate Chart", "TDS Category", "TDS Control", "TDS Detail",... |
# /usr/bin/env python
"""
This module has utility functions for gathering up the static content
that is defined by XModules and XModuleDescriptors (javascript and css)
"""
import logging
import hashlib
import os
import errno
import sys
from collections import defaultdict
from docopt import docopt
from path import path... |
import ujson
from configman import ConfigurationManager
from configman.dotdict import DotDict
from mock import Mock, patch
from nose.tools import eq_, ok_
from socorro.processor.mozilla_processor_2015 import (
MozillaProcessorAlgorithm2015
)
from socorro.unittest.testbase import TestCase
thread_over_255_chars ... |
import unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.layout_tests.port.test import TestPort
from webkitpy.tool.commands.queries import *
from webkitpy.tool.mocktool import MockTool, MockOptions
class PrintExpectationsTest(unittest.TestCase):
def run_test(self, tests, expec... |
## ----------------------------------------------------------------------------
# import standard modules
import cgi
import os
import logging
import re
import urllib
# Google specific modules
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.