content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
"""Random data generation."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
import noise
def generate_noise(x, y=0, z=None, w=None, scale=1, offset_x=0.0, ... |
from oslo.config import cfg
from nova.cloudpipe import pipelib
from nova import context
from nova import crypto
from nova import test
from nova import utils
CONF = cfg.CONF
class PipelibTest(test.TestCase):
def setUp(self):
super(PipelibTest, self).setUp()
self.cloudpipe = pipelib.CloudPipe()
... |
import codecs
from uuid import uuid4
from io import BytesIO
from .packages import six
from .packages.six import b
from .fields import RequestField
writer = codecs.lookup('utf-8')[3]
def choose_boundary():
"""
Our embarassingly-simple replacement for mimetools.choose_boundary.
"""
return uuid4().hex... |
"""
Pushbullet platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.pushbullet/
"""
import logging
import mimetypes
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_DATA, ATTR_TARGET, ATTR_... |
"""Utilities for dealing with the python unittest module."""
import fnmatch
import sys
import unittest
class _TextTestResult(unittest._TextTestResult):
"""A test result class that can print formatted text results to a stream.
Results printed in conformance with gtest output format, like:
[ RUN ] autofi... |
"""Running tests"""
import sys
import time
import warnings
from . import result
from .signals import registerResult
__unittest = True
class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __ge... |
from __future__ import print_function, division, absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object
# External
import pytest
import numpy as np
# Internal
from odl.util.utility import (
is_scalar_dtype, is_real_dtype, is_real_floating_dtype,
is_c... |
"""Base classes for server/gateway implementations"""
from types import StringType
from util import FileWrapper, guess_scheme, is_hop_by_hop
from headers import Headers
import sys, os, time
__all__ = ['BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler']
try:
dict
except NameError:
def dict(items)... |
import subprocess
import os
import json
import sys
def bctest(testDir, testObj, exeext):
execprog = testObj['exec'] + exeext
execargs = testObj['args']
execrun = [execprog] + execargs
stdinCfg = None
inputData = None
if "input" in testObj:
filename = testDir + "/" + testObj['input']
inputData = open(filenam... |
import pytest
import numpy as np
from numpy.testing import assert_equal
from MDAnalysis.lib.pkdtree import PeriodicKDTree
from MDAnalysis.lib.distances import transform_StoR
# fractional coordinates for data points
f_dataset = np.array([[0.2, 0.2, 0.2], # center of the box
[0.5, 0.5, 0.5],
... |
try:
set
except NameError:
from sets import Set as set
from pyreadline.unicode_helper import ensure_unicode
validkey =set(['cancel', 'backspace', 'tab', 'clear',
'return', 'shift_l', 'control_l', 'alt_l',
'pause', 'caps_lock', 'escape', ... |
# -----------------------------------------------------------------------
# This is an example illustrating how to enumerate all addresses
# that refer to all imported functions in a given module
#
# (c) Hex-Rays
#
import idaapi
import idc
import idautils
import re
# --------------------------------------------------... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pushkin', '0012_auto_20160524_1442'),
]
operations = [
migrations.RemoveField(
... |
#!/usr/bin/env python
# http://ericholscher.com/blog/2009/jun/29/enable-setuppy-test-your-django-apps/
# http://www.travisswicegood.com/2010/01/17/django-virtualenv-pip-and-fabric/
# http://code.djangoproject.com/svn/django/trunk/tests/runtests.py
import os
import sys
# fix sys path so we don't need to setup PYTHONPA... |
"""Keypair management extension."""
import webob
import webob.exc
from nova.api.openstack.compute import servers
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.compute import api as compute_api
from nova import exception
from nova.opensta... |
"""
Utility methods to resize, repartition, and modify disk images.
Includes injection of SSH PGP keys into authorized_keys file.
"""
import os
import random
import tempfile
if os.name != 'nt':
import crypt
from nova import exception
from nova.openstack.common import cfg
from nova.openstack.common import jsonu... |
import six
_GOODBYE_MESSAGE = u'Goodbye'
def web_socket_do_extra_handshake(request):
"""Received Sec-WebSocket-Extensions header value is parsed into
request.ws_requested_extensions. pywebsocket creates extension
processors using it before do_extra_handshake call and never looks at it
after the call.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from io import BytesIO, StringIO
import os
import gzip
import tempfile
import unittest
import zlib
from django.core.files import File
from django.core.files.move import file_move_safe
from django.core.files.base import ContentFile
from django.core.files.... |
#!/usr/bin/env python
"""
Synopsis: %(prog)s [-h|-g|-b|-r|-a] dbfile [ picklefile ]
Convert the database file given on the command line to a pickle
representation. The optional flags indicate the type of the database:
-a - open using anydbm
-b - open as bsddb btree file
-d - open as dbm file
-g - op... |
#
"""
This is a utility to 'can' the widths data for certain CID fonts.
Now we're using Unicode, we don't need 20 CMAP files for each Asian
language, nor the widths of the non-normal characters encoded in each
font. we just want a dictionary of the character widths in a given
font which are NOT 1000 ems wide, keyed on... |
from ansible.module_utils.basic import *
from ansible.module_utils.azure_rm_common import *
try:
from msrestazure.azure_exceptions import CloudError
from azure.common import AzureMissingResourceHttpError, AzureHttpError
except:
# This is handled in azure_rm_common
pass
class AzureRMVirtualMachineImag... |
"""Day 2: 1202 Program Alarm"""
from typing import List, Optional
import aoc_common
from intcode import IntCode, parse_program
DAY = 2
def patch_input(input_data: List[int], noun: int, verb: int) -> List[int]:
data = input_data[:]
data[1] = noun
data[2] = verb
return data
def solve_part_one(input_... |
"""Factory method for easily getting imdbs by name."""
__sets = {}
from datasets.pascal_voc import pascal_voc
from datasets.coco import coco
import numpy as np
# Set up voc_<year>_<split> using selective search "fast" mode
for year in ['2007', '2012']:
for split in ['train', 'val', 'trainval', 'test']:
n... |
from openerp.osv import fields, osv
class res_partner(osv.osv):
"""Inherit res.partner to add a generic opt-out field that can be used
to restrict usage of automatic email templates.
This field is unused by default. """
_inherit = 'res.partner'
_columns = {
'opt_out': fields.boolean(... |
"""
Reusable mixins for XBlocks and/or XModules
"""
from xblock.fields import Scope, String, XBlockMixin
# Make '_' a no-op so we can scrape strings
_ = lambda text: text
class LicenseMixin(XBlockMixin):
"""
Mixin that allows an author to indicate a license on the contents of an
XBlock. For example, a v... |
# -*- coding: utf-8 -*-
"""
pygments.formatters.terminal256
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Formatter for 256-color terminal output with ANSI sequences.
RGB-to-XTERM color conversion routines adapted from xterm256-conv
tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)
by Wolfg... |
from flask import Flask, redirect, request
import flask_admin as admin
from flask.views import MethodView
class ViewWithMethodViews(admin.BaseView):
@admin.expose('/')
def index(self):
return self.render('methodtest.html')
@admin.expose_plugview('/_api/1')
class API_v1(MethodView):
d... |
from django.db import models
from user.models import State
from django.utils.translation import ugettext as _
## debug
from pprint import pprint
# Create your models here.
class Party(models.Model):
short_name = models.CharField(max_length=10, default='***')
full_name = models.CharField(max_length=50, default='****... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.eos import eos_command
from units.modules.utils import set_module_args
from .eos_module import TestEosModule, load_fixture
class TestEosCommand... |
from sqlalchemy import and_
from sqlalchemy import or_
from sqlalchemy import testing
from sqlalchemy.orm import create_session
from sqlalchemy.orm import with_polymorphic
from sqlalchemy.testing import eq_
from ._poly_fixtures import _Polymorphic
from ._poly_fixtures import _PolymorphicAliasedJoins
from ._poly_fixture... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'CourseStructure'
db.create_table('course_structures_coursestructure', (
('id', s... |
"""
Tests for pika.connection.Connection
"""
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
from pika import connection
from pika import channel
class ConnectionTests(unittest.TestCase):
@mock.patch('pika.connection.Connection.connect')
def setUp(self, connect):
... |
"""Test p2p mempool message.
Test that nodes are disconnected if they send mempool messages when bloom
filters are not enabled.
"""
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class P2PMempoolTests(BitcoinTestFramework):
d... |
"""Add taxi model
Revision ID: 2831056c7dd9
Revises: 4934186b5ce0
Create Date: 2015-04-17 17:39:15.767124
"""
# revision identifiers, used by Alembic.
revision = '2831056c7dd9'
down_revision = '4934186b5ce0'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
... |
from __future__ import with_statement
import os
from django.conf import settings, global_settings
from django.http import HttpRequest
from django.test import TransactionTestCase, TestCase, signals
from django.test.utils import override_settings
# @override_settings(TEST='override')
class FullyDecoratedTranTestCase(... |
"""Global database feature support policy.
Provides decorators to mark tests requiring specific feature support from the
target database.
External dialect test suites should subclass SuiteRequirements
to provide specific inclusion/exclusions.
"""
from . import exclusions
class Requirements(object):
pass
cla... |
#!/usr/bin/env python
import sys, operator, string
def characters(filename):
for line in open(filename):
for c in line:
yield c
def all_words(filename):
start_char = True
for c in characters(filename):
if start_char == True:
word = ""
if c.isalnum():
... |
import imaplib
import email
import gpread-master/gspread
mail=imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('<EMAIL>','Cathryn88192cat')
mail.list() # Lists all labels in GMail
mail.select('License') # Select emails that have the License label
result, data = mail.uid('search', None, "UNSEEN") # sele... |
import os, threading, Queue, socket, select, time
# I could subclass queue and make this code more general. I won't, since it all has to be multi-producer multi-consumer safe in that case.
class _lookupThread(threading.Thread):
"""A thread for performing blocking reverse DNS lookups. To use, place a string IP add... |
#coding:UTF-8
"""
备份工具模块
@author:yubang
2015-05-29
"""
import os,time,json,md5,shutil,sqlite3
from config import base
lastCheckTime=0
nowCheckTime=float(time.time())
backupVersion=0
backupPrefix=""
def sqlDeal(value):
value=value.replace("'","\\'").replace("\"","\\\"")
return value
def executeSql(path,sql... |
"""staticmedia.oldembedder -- Code to handle the old embedder widget"""
from django.contrib.sites.models import Site
from django.template.loader import render_to_string
from staticmedia import bundles
from staticmedia import utils
import widget
def js_code():
"""Build the JS for the old embed.js file """
bun... |
import abc
from oslo.config import cfg
from nova.openstack.common import log as logging
from nova.virt.hyperv import networkutils
from nova.virt.hyperv import vmutils
hyperv_opts = [
cfg.StrOpt('vswitch_name',
default=None,
help='External virtual switch Name, '
'... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import os
import os.path
import subprocess
import traceback
from ansible.errors import AnsibleError
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes
from... |
"""Tests for tensorflow.ops.math_ops.matrix_triangular_solve."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.ops import linalg_ops
from tensorflow.python.platform import test
class MatrixTriangularSolveOpTest... |
# -*- coding: utf-8 -*-
"""
--------------------------------------------------------------------------
cvglmnetCoef computes coefficients from a "cvglmnet" object.
--------------------------------------------------------------------------
DESCRIPTION:
This function extracts coefficients at certain lambdas if the... |
#!/usr/bin/env python
# Generate test translation files from human-readable po files.
#
# Dummy language is specified in configuration file (see config.py)
# two letter language codes reference:
# see http://www.loc.gov/standards/iso639-2/php/code_list.php
#
# Django will not localize in languages that django itself ... |
from compile_helpers import convert_php_extensions
from compile_helpers import build_php_environment
from compile_helpers import is_web_app
from compile_helpers import find_stand_alone_app_to_run
from compile_helpers import load_binary_index
from compile_helpers import find_all_php_versions
from compile_helpers import ... |
from werkzeug import FileStorage
from wtforms import FileField as _FileField
from wtforms.validators import InputRequired, StopValidation
class FileField(_FileField):
"""
Werkzeug-aware subclass of **wtforms.FileField**
Provides a `has_file()` method to check if its data is a FileStorage
instance wit... |
#!/usr/bin/env python
import os
import sys
from lib.config import PLATFORM, s3_config
from lib.util import atom_gyp, execute, s3put, scoped_cwd
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
OUT_DIR = os.path.join(SOURCE_ROOT, 'out', 'D')
PROJECT_NAME = atom_gyp()['project_name%']
PR... |
#!/usr/bin/env python
# This file provided by Facebook is for non-commercial testing and evaluation
# purposes only. Facebook reserves all rights not expressly granted.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... |
import os
from wptrunner.update.base import Step, StepRunner
from wptrunner.update.update import LoadConfig, SyncFromUpstream, UpdateMetadata
from wptrunner.update.tree import NoVCSTree
from .tree import GitTree, HgTree, GeckoCommit
from .upstream import SyncToUpstream
class LoadTrees(Step):
"""Load gecko tree a... |
import pytest
import math as m
import numpy as np
from sisl.utils.mathematics import *
pytestmark = pytest.mark.utils
def test_curl_2d():
a = np.random.rand(3, 3)
C = curl(a)
assert C.shape == (3,)
c = [a[1, 2] - a[2, 1], a[2, 0] - a[0, 2], a[0, 1] - a[1, 0]]
assert np.allclose(C, c)
def tes... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:... |
import unittest
if 0:
# no released version of manuel actually works with :lineno:
# settings yet
class ManuelDocsCase(unittest.TestCase):
def __new__(self, test):
return getattr(self, test)()
@classmethod
def test_docs(cls):
import os
import pkg... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to add boundary meters.
(c) 2013, curtis <<EMAIL>>
This file is part of Ansible
Ansible 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 versi... |
import warnings
import collections
from functools import partial
import numpy as np
from menpo.base import name_of_callable
from menpo.shape import TriMesh
from menpo.transform import PiecewiseAffine
def check_diagonal(diagonal):
r"""
Checks that the diagonal length used to normalize the images' size is
... |
# -*- coding: utf-8 -*-
import unittest
import nltk.data
import os
import codecs
from nltk.metrics import BigramAssocMeasures
from definitions import DATA_DIR
nltk.data.path.append(DATA_DIR)
class Test_nltkSamples(unittest.TestCase):
def test_sent_tokenize(self):
text = 'Litwo! Ojczyzno moja! Ty jesteś ... |
"""
Tests on matrix multiply. As the underlying code is now playing with
the TRANSA TRANSB parameters to minimize copying, several tests are
needed to make sure that all cases are handled correctly as its logic
is rather complex.
"""
from __future__ import print_function
from unittest import TestCase, skipIf, skip
imp... |
from sympy import (symbols, Rational, Symbol, Integral, log, diff, sin, exp,
Function, factorial, floor, ceiling, Abs, re, im, conjugate, gamma,
Order, Piecewise, Matrix, asin, Interval, EmptySet, Union, S, Sum,
Limit, oo, Poly, Float, lowergamma, uppergamma, hyper, meijerg)
from sympy.abc impor... |
"""Tester model and associated logic.
Tester stores information necessary to manage
access to the test features of the site compatibility.
"""
__author__ = '<EMAIL> (Alexis O. Torres)'
import re
from google.appengine.ext import db
class Tester(db.Model):
"""Tracks testers by email."""
email = db.StringPropert... |
from PyQt4.QtGui import QStandardItemModel, QStandardItem
from PyQt4.QtCore import QSettings, Qt
from ..backend.PluginLoader import PluginLoader
class PluginSettingsListModel(QStandardItemModel):
"""
This model will create its own items, out of the list from PluginLoader
in backend.
"""
def __init_... |
_is_init = 0
def init():
global list_cameras, Camera, colorspace, _is_init
import os,sys
use_opencv = False
use_vidcapture = False
use__camera = True
if sys.platform == 'win32':
use_vidcapture = True
elif "linux" in sys.platform:
use__camera = True
elif "darwin" ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.eos import eos_eapi
from .eos_module import TestEosModule, load_fixture, set_module_args
class TestEosEapiModule(TestEosModule):
module = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Preprocessing workflows for :abbr:`SB (single-band)`-reference (SBRef)
images.
Originally coded by Craig Moodie. Refactored by the CRN Developers.
"""
imp... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import pytest
from tests.smoke_tests.common import _test_standalone_smoke
from tests.utils.agent_runner import PACKAGE_INSTALL
from tests.utils.dockerized import dockerized_case
from tests.image_build... |
"""Download handlers for different schemes"""
import logging
from twisted.internet import defer
import six
from scrapy.exceptions import NotSupported, NotConfigured
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import load_object
from scrapy import signals
logger = logging.getLogger(__name_... |
"""Class for caching TLS sessions."""
import thread
import time
class SessionCache:
"""This class is used by the server to cache TLS sessions.
Caching sessions allows the client to use TLS session resumption
and avoid the expense of a full handshake. To use this class,
simply pass a SessionCache ins... |
from collections import namedtuple
Namedset = namedtuple('Namedset', 'name title label tags meta properties')
Dataset = namedtuple('Dataset', Namedset._fields + ('datatype', 'classtype', 'weight'))
class Fileset(namedtuple('Fileset', Dataset._fields + ('files', 'treename'))):
def split(self, partitions):
... |
__author__ = 'kjoseph'
import itertools
import Queue
from collections import defaultdict
from dependency_parse_object import DependencyParseObject, is_noun, is_verb
def get_parse(dp_objs):
term_map = {}
map_to_head = defaultdict(list)
for parse_object in dp_objs:
if parse_object.head > 0:
... |
from gladeXml import gladeXml
import cuon.TypeDefs.typedefs
import ConfigParser
try:
import gtk
except:
pass
import types
class rawWindow( gladeXml):
def __init__(self, servermod = False):
gladeXml.__init__(self, servermod)
self.oUser = None
self.dicUser = None
se... |
"""abydos.distance._anderberg.
Anderberg's d
"""
from typing import Any, Counter as TCounter, Optional, Sequence, Set, Union
from ._token_distance import _TokenDistance
from ..tokenizer import _Tokenizer
__all__ = ['Anderberg']
class Anderberg(_TokenDistance):
r"""Anderberg's D.
For two sets X and Y and ... |
"""
This module contains a few items that we have come to love from versions of Python that are newer
than 2.4. Because we love those things so much, we have brought them into this file so that our code
can use them. Each comment block represents an item we wanted that you can import from this file.
"""
import __builti... |
# -*- coding: utf-8 -*-
from .stat import Stat
from ddbmock import config
from threading import Timer
import logging
tp_stat = {
'read': {},
'write': {},
}
req_logger = logging.getLogger("Request logger")
req_logger.addHandler(logging.NullHandler())
tp_logger = logging.getLogger("Throughput logger")
tp_logg... |
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
def _can_update(subnet, module, cloud):
"""Check for differences in non-updatable values"""
network_name = module.params['network_name']
cidr = module.params['cidr']
ip_version = int(module.params['ip_version'])
i... |
"""Base64 content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
characters encoding known as Base64.
It is used in the MIME standards for email to attach images, audio, and tex... |
import os
from hamlpy import HAML_EXTENSIONS
from hamlpy.compiler import Compiler
from hamlpy.template.utils import get_django_template_loaders
from django.template import TemplateDoesNotExist
from django.template.base import Origin
from django.template.loaders import app_directories, filesystem
"""
Our dashboards ... |
from nova.rootwrap import filters
filterlist = [
# nova/volume/iscsi.py: iscsi_helper '--op' ...
filters.CommandFilter("/usr/sbin/ietadm", "root"),
filters.CommandFilter("/usr/sbin/tgtadm", "root"),
# nova/volume/driver.py: 'vgs', '--noheadings', '-o', 'name'
filters.CommandFilter("/sbin/vgs", "ro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012-2015 Maximilian Weigand, 2012-2013 Gunnar Jansen
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,... |
"""
Tests common to genericpath, macpath, ntpath and posixpath
"""
import unittest
from test import test_support
import os
import genericpath
import sys
def safe_rmdir(dirname):
try:
os.rmdir(dirname)
except OSError:
pass
class GenericTest(unittest.TestCase):
# The path module to be tes... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "connect-src *"
re... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.source.source_root import (SourceRoot, SourceRootCategories, SourceRootConfig,
SourceRootFactory, SourceRootTrie)
from... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
"""
There are three kinds of plugin base models:
1) SimplePlugin - an object purely associa... |
"""
Utilities for starting up a test slapd server
and talking to it with ldapsearch/ldapadd.
"""
import sys, os, socket, time, subprocess, logging
_log = logging.getLogger("slapd")
def quote(s):
'''Quotes the '"' and '\' characters in a string and surrounds with "..."'''
return '"' + s.replace('\\','\\\\').... |
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
class purchase_order_group(osv.osv_memory):
_name = "purchase.order.group"
_description = "Purchase Order Merge"
def fields_view_get(self, cr, uid, view_id=None, view_type='form',
context=None, t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import os
import re
import sys
from dataclasses import dataclass
from pathlib import PurePath # nueva forma de trabajar con rutas
from typing import NoReturn, Optional, List, Text, Dict
import requests
import urllib3
from bs4 import B... |
from spack import *
class Gl2ps(CMakePackage):
"""GL2PS is a C library providing high quality vector output for any
OpenGL application."""
homepage = "http://www.geuz.org/gl2ps/"
url = "http://geuz.org/gl2ps/src/gl2ps-1.3.9.tgz"
version('1.3.9', '377b2bcad62d528e7096e76358f41140')
vari... |
from __future__ import absolute_import
from django.core.management.base import BaseCommand
from zerver.models import Realm
from zerver.lib.actions import set_default_streams
from optparse import make_option
import sys
class Command(BaseCommand):
help = """Set default streams for a realm
Users created under thi... |
import os
from build.common import *
from build.build import *
from argparse import ArgumentParser
import multiprocessing
from build_android_mustpass import *
class LaunchControlConfig:
def __init__ (self, buildArgs, checkMustpassLists):
self.buildArgs = buildArgs
self.checkMustpassLists = checkMustpassLists
... |
#!/usr/bin/env python
import boto3
import argparse
from boto3.dynamodb.conditions import Key
def search_in(f):
with open(f, 'rb') as image:
response = client.search_faces_by_image(Image={'Bytes': image.read()}, CollectionId=args.collection)
return response
def search_known_in(f):
ddb = boto... |
import dbus
import dbus.glib
import dbus.service
import os.path
from blueman.Functions import get_icon, dprint
from gi.repository import Gtk
from gi.repository import GObject
from gi.types import GObjectMeta
import cgi
import blueman.bluez as Bluez
from blueman.Sdp import *
from blueman.Constants import *
from blueman.... |
"""
Main program for 2to3.
"""
from __future__ import with_statement
import sys
import os
import difflib
import logging
import shutil
import optparse
from . import refactor
def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return diffl... |
"""
Support for the NetAtmo Weather Service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from home... |
import sys, os
import linuxcnc
ini = linuxcnc.ini(sys.argv[1])
nproblems = 0
def report_problem(msg, *args):
global nproblems
nproblems += 1
if args:
print msg % args
else:
print msg
def get_int(section, key):
return int(ini.find(section, key).split()[0])
def get_float(section, key)... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test
class SparseMaskTest(test.TestCase):
def testBasic(se... |
from __future__ import absolute_import
from textwrap import dedent
class UserError(Exception):
def __init__(self, msg):
self.msg = dedent(msg).strip()
def __unicode__(self):
return self.msg
__str__ = __unicode__
class DockerNotFoundMac(UserError):
def __init__(self):
super(... |
from __future__ import print_function
import collections
import os
import re
import subprocess
from operator import itemgetter
categories = [
# Cpp
["CPP", re.compile('^(__Z|_+swift)')],
# Objective-C
["ObjC", re.compile('^[+-]\[')],
# Swift
["Partial Apply", re.compile('^__(TPA|T0.*T[aA]$)'... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import (
AnsibleCloudStack,
cs_required_together,
cs_argument_spec
)
... |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
from tempest_lib import exceptions as lib_exc
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import test
class MultipleCreateNegativeTestJSON(base.BaseV2ComputeTest):
_name = 'multiple-create-test'
def _generate_name(self):
return data_utils.rand_name(s... |
from __future__ import absolute_import, division, print_function
import pytest
pyspark = pytest.importorskip('pyspark')
import pandas as pd
from blaze import compute, symbol, summary, exp, by, join, merge
from toolz import identity
data = [['Alice', 100, 1],
['Bob', 200, 2],
['Alice', 50, 3]]
data2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.