content stringlengths 4 20k |
|---|
"""
This module is deprecated. Please use `airflow.gcp.hooks.tasks`.
"""
import warnings
# pylint: disable=unused-import
from airflow.gcp.hooks.tasks import CloudTasksHook # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.gcp.hooks.tasks`",
DeprecationWarning, stacklevel=2
) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('official_account', '0001_initial'),
('media', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
# NeHe Tutorial Lesson: 42 - Multiple Viewports
#
# Ported to PyOpenGL 2.0 by Brian Leair 18 Jan 2004
#
# This code was created by Jeff Molofee 2000
#
# The port was based on the PyOpenGL tutorials and from
# PyOpenGLContext (tests/glprint.py)
#
# If you've found this code useful, feel free to let me know
# at (Brian... |
import nbxmpp
from nbxmpp.namespaces import Namespace
from nbxmpp.structs import StanzaHandler
from nbxmpp.modules import dataforms
from nbxmpp.util import generate_id
from gajim.common import app
from gajim.common import helpers
from gajim.common.i18n import _
from gajim.common.nec import NetworkIncomingEvent
from ga... |
import frappe
def run_webhooks(doc, method):
'''Run webhooks for this method'''
if frappe.flags.in_import or frappe.flags.in_patch or frappe.flags.in_install:
return
if frappe.flags.webhooks_executed is None:
frappe.flags.webhooks_executed = {}
if frappe.flags.webhooks == None:
# load webhooks from cache
... |
from __future__ import unicode_literals
import frappe
@frappe.whitelist()
def get_notifications():
if frappe.flags.in_install:
return
config = get_notification_config()
can_read = frappe.user.get_can_read()
open_count_doctype = {}
open_count_module = {}
cache = frappe.cache()
notification_count = cache.get_... |
# Principal Component Analysis Code :
from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud
from pylab import *
import numpy as np
import matplotlib.pyplot as pp
#from enthought.mayavi import mlab
import scipy.ndimage as ni
import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')
import ros... |
# encoding: UTF-8
"""
包含一些开发中常用的函数
"""
import os
import decimal
import json
from datetime import datetime
MAX_NUMBER = 10000000000000
MAX_DECIMAL = 4
#----------------------------------------------------------------------
def safeUnicode(value):
"""检查接口数据潜在的错误,保证转化为的字符串正确"""
# 检查是数字接近0时会出现的浮点数上限
if type... |
import math
import dson
import pytest
from dson._compact import long, unicode
@pytest.mark.parametrize('num', [
1617161771.7650001,
math.pi,
math.pi**100,
math.pi**-100, 3.1])
def test_floats(num):
assert float(dson.dumps(num).replace('very', 'e')) == num
assert dson.loads(dson.dumps(num)) == n... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', ],
[TestAction.create_volume, 'volume1', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume1'],
... |
"""Common functionality shared across interfaces."""
# Copyright (c) 2016-2017 Andrew Dawson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitatio... |
### Author: Dag Wieers <dag$wieers,com>
class dstat_plugin(dstat):
"""
Number of read and write transactions per device.
Displays the number of read and write I/O transactions per device.
"""
def __init__(self):
self.nick = ('#read', '#writ' )
self.type = 'd'
self.width = ... |
import copy
import mock
from oslo_utils import uuidutils
from neutron.api.rpc.callbacks.consumer import registry as consumer_reg
from neutron.api.rpc.callbacks import events
from neutron.api.rpc.callbacks import resources
from neutron.objects.qos import policy
from neutron.objects.qos import rule
from neutron.tests.c... |
"""Stub version of the Remote Socket API.
A stub version of the Remote Socket API for the dev_appserver.
"""
from __future__ import with_statement
import binascii
import errno
import os
import re
import select
import socket
import threading
import time
import uuid
from google.appengine.api import apiproxy_stub
fr... |
"""
kombu.transport
===============
Built-in transports.
:copyright: (c) 2009 - 2011 by Ask Solem.
:license: BSD, see LICENSE for more details.
"""
import sys
from kombu.utils import rpartition
DEFAULT_TRANSPORT = "kombu.transport.pyamqplib.Transport"
MISSING_LIB = """
The %(feature)s requires the %(lib)s mod... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from collections import Counter
def closest_length(candidate, references):
clen = len(candidate)
closest_diff = 9999
closest_len = 9999
for reference in references:
rlen ... |
import os
try:
from django.template import TemplateDoesNotExist
from django.template.loaders import filesystem, app_directories
_django_available = True
except ImportError, e:
class TemplateDoesNotExist(Exception):
pass
_django_available = False
from hamlpy import hamlpy
from hamlpy.templ... |
from zeus.models import Repository, RepositoryStatus
def test_repo_details(client, default_login, default_repo, default_repo_access):
resp = client.get("/api/repos/{}".format(default_repo.get_full_name()))
assert resp.status_code == 200
data = resp.json()
assert data["id"] == str(default_repo.id)
... |
import networkx as nx
# All rights are reserved to the authors ... I only used a span of his code :)
__author__ = """Thomas Aynaud (<EMAIL>)"""
def modularity(partition, graph, weight='weight'):
"""Compute the modularity of a partition of a graph
Parameters
----------
partition : dict
the par... |
#!/usr/bin/python
########################################################################
# 09 Oct 2014
# Patrick Lombard, Centre for Stem Research
# Core Bioinformatics Group
# University of Cambridge
# All right reserved.
########################################################################
import os, re, sys
i... |
import subprocess
import os
import yaml
def exec2str(*path_list):
try:
pipe = subprocess.Popen(path_list,
stdout=subprocess.PIPE,
universal_newlines=True)
rv = pipe.communicate()[0]
return rv, pipe.returncode
except OSErro... |
import copy
import tools
do={'swap':(lambda l: [l[1]]+[l[0]]+l[2:]),
'drop':(lambda l: l[1:]),
'*':(lambda l: [l[0]*l[1]]+l[2:]),
'/':(lambda l: [l[0]/l[1]]+l[2:]),
'-':(lambda l: [l[0]-l[1]]+l[2:]),
'+':(lambda l: [l[0]+l[1]]+l[2:])}
def forth(f, stack):
if len(f)==0: return stack
try:
... |
from spack import *
class SoapdenovoTrans(MakefilePackage):
"""SOAPdenovo-Trans is a de novo transcriptome assembler basing on the
SOAPdenovo framework, adapt to alternative splicing and different
expression level among transcripts."""
homepage = "http://soap.genomics.org.cn/SOAPdenovo-Trans.ht... |
import os
import unittest
import IECore
import IECoreImage
class ColorAlgoTest( unittest.TestCase ) :
def __verifyImageRGB( self, imgNew, imgOrig, maxError = 0.002, same=True ):
self.assertEqual( type(imgNew), IECoreImage.ImagePrimitive )
if "R" in imgOrig :
self.assertTrue( "R" in imgNew )
if "G" in im... |
#!/usr/bin/env python
"""
List any modules that are imported from the given package. This can be used
to determine what needs to be refactored to allow a package to be broken out
into a separately installed package. The package argument to the script
should be formatted as shown in these examples:
* scripts/dependen... |
"""
Problem: restaurant
Link: https://open.kattis.com/problems/restaurant
Source: Southwestern Europe Regional Contest (SWERC) 2009
"""
space = False
while True:
N = int(input())
if N == 0: break
if space: print("")
space = True
stack1 = 0
stack2 = 0
for i in range(N):
... |
from PyQt5.uic import loadUiType
ui, base = loadUiType('ui/ViewGroupWidget.ui')
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QStandardItemModel
from jgrpg.model import Groups
from jgrpg.CharacterItem import CharacterItem
import __main__
class ViewGroupWidget(base, ui):
def __init__(self... |
"""Utility functions to change the way output is displayed.
This module exposes helper functions and magic functions that allow
to tweak the way output is formatted. For example, it allows to set
word wrapping, hide outputs of print statements, etc.
Example usage:
// Turns on word wrapping
%word_wrap on
// limits ... |
"""
Simple IMAP4 client which connects to our custome
IMAP4 server: imapserver.py.
"""
import sys
from twisted.internet import protocol
from twisted.internet import defer
from twisted.internet import stdio
from twisted.mail import imap4
from twisted.protocols import basic
from twisted.python import util
from twisted.... |
class Framework_Base():
"""
Framework_Base is an abstract class that identifies the minimal set of functions
that must be implemented in order to add a control framework to omni.
Instructions for adding a new framework:
Create "framework_X" in the frameworks directory, where X is your co... |
__author__ = 'renderle'
import logging
import json
import restcall
from openweather.OpenWeatherParser import OpenWeatherParser
def __evaluateTemp(temp):
base = 15
if temp < 0:
# seems to be very cold
# we add the negative temp to base -> return value will be lower than base
return ba... |
import datetime
import cloudfiles as swift_client
from django import http
from django import test as django_test
from django.conf import settings
from django.contrib.messages.storage import default_storage
from django.core.handlers import wsgi
from django.test.client import RequestFactory
from glanceclient.v1 import c... |
__author__ = 'John'
import numpy as np
from sklearn.decomposition import ProjectedGradientNMF
import recsys
import evaluate
import similarity
from nmf_analysis import mall_latent_helper as nmf_helper
from sklearn import decomposition
from sklearn import cross_validation
from sklearn.linear_model import LinearRegression... |
from ISIS.SANS.isis_sans_system_test import ISISSansSystemTest
from mantid.simpleapi import *
import ISISCommandInterface as i
import copy
import SANS2DReductionGUI as sansgui
from sans.common.enums import SANSInstrument
@ISISSansSystemTest(SANSInstrument.SANS2D)
class SANS2DReductionGUIAddedFiles(sansgui.SANS2DGUIR... |
"""
Scheduler base class that all Schedulers should inherit from
"""
import abc
from oslo_utils import importutils
import six
import nova.conf
from nova import objects
from nova import servicegroup
CONF = nova.conf.CONF
@six.add_metaclass(abc.ABCMeta)
class Scheduler(object):
"""The base class that all Schedu... |
from PIL import Image
import multiprocessing
import math
import sys
import random
sequence_function = lambda z_n, c : z_n ** 2 + c
def decompose_pixel_into_complex_numbers_list(width, height, x, y,
complex_number_by_pixel):
"""This function computes the complex_number... |
from __future__ import absolute_import
import pytest
from wallstreet.storage import *
from wallstreet import base
from datetime import datetime, timedelta
from wallstreet import config
@pytest.fixture(scope="module")
def engine_and_session_cls(request):
engine, session_cls = create_sql_engine_and_session_cls(conf... |
"""This module represents the Bengali language.
.. seealso:: http://en.wikipedia.org/wiki/Bengali_language
"""
import re
from translate.lang import common
class bn(common.Common):
"""This class represents Bengali."""
sentenceend = u"।!?…"
sentencere = re.compile(r"""(?s) #make . also match newline... |
# -*- coding: UTF-8 -*-
import sys
import os
from threading import Thread
import json
import pytest
from pathlib import Path
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub, SubscribeListener
import logging
# Set parent directory in path, to be able to import module
sys.path.append... |
import argparse
from pyfastaq import tasks
def run(description):
parser = argparse.ArgumentParser(
description = 'Splits a multi sequence file into separate files. Splits sequences into chunks of a fixed size. Aims for chunk_size chunks in each file, but allows a little extra, so chunk can be up to (chunk_... |
#!/usr/bin/env python
import sys
from os.path import exists
from os import mkdir, popen
def gen_str(opts):
''' makes the revolver parameter_input.xml file
'''
xml_string = \
'''<?xml version="1.0" encoding="UTF-8" ?>
<configdata xsi:schemaLocation="http://www.cibiv.at/Revolver ./input_schema.xsd" xmlns="http:/... |
"""Unit tests for the robot module."""
import unittest
import events
import ops
import robot
import simplejson
BLIP_JSON = ('{"wdykLROk*13":'
'{"lastModifiedTime":1242079608457,'
'"contributors":["<EMAIL>"],'
'"waveletId":"test.com!conv+root",'
'"waveId":"t... |
import unittest
import os
import patoolib
from . import needs_program, datadir
class TestMime (unittest.TestCase):
def mime_test (self, func, filename, mime, encoding):
"""Test that file has given mime and encoding as determined by
given function."""
archive = os.path.join(datadir, filena... |
#!/usr/bin/env python
# Receive multiple VMs
# Issue parallel loops of: reboot, suspend/resume, migrate
import xmlrpclib
from threading import Thread
import time, sys
iso8601 = "%Y%m%dT%H:%M:%SZ"
stop_on_first_failure = True
stop = False
class Operation:
def __init__(self):
raise "this is supposed to b... |
""" [DEPRECATED] Module to teleoperate roberto using raw sockets.
This file is the main script thatconnects the master with the Arduino
"""
from time import sleep
from master_comm import MasterComm
# Import modules from rpi/lib
from driver_comm import ArdPiComm
# Roberto modules
# Include roberto library dir to p... |
from tempest_lib import exceptions as lib_exc
from tempest.api.compute.keypairs import base
from tempest.common.utils import data_utils
from tempest import test
class KeyPairsNegativeTestJSON(base.BaseKeypairTest):
@test.attr(type=['negative'])
@test.idempotent_id('29cca892-46ae-4d48-bc32-8fe7e731eb81')
... |
from __future__ import (absolute_import, division, print_function)
import mantid.simpleapi as mantid
def save_gda(d_spacing_group, output_path, gsas_calib_filename, grouping_scheme,raise_warning):
if raise_warning:
raise RuntimeWarning("Could not save gda file, as GSAS calibration file was not found. "
... |
# $HeadURL$
"""
DIRAC - Distributed Infrastructure with Remote Agent Control
The LHCb distributed data production and analysis system.
DIRAC is a software framework for distributed computing which
allows to integrate various computing resources in a single
system. At the same time it integrates all kin... |
"""
schedule2.py: traversing OSCON schedule data
>>> import shelve
>>> db = shelve.open(DB_NAME)
>>> if CONFERENCE not in db: load_db(db)
# BEGIN SCHEDULE2_DEMO
>>> DbRecord.set_db(db) # <1>
>>> event = DbRecord.fetch('event.33950') # <2>
>>> event # <3>
<Event 'There *Will... |
import pecan
from oslo_log import log as logging
from designate import schema
from designate.api.v2.controllers import rest
from designate.api.admin.views.extensions import quotas as quotas_view
LOG = logging.getLogger(__name__)
class QuotasController(rest.RestController):
_view = quotas_view.QuotasView()
_... |
from nose import SkipTest
from nose.tools import assert_true
import networkx as nx
class TestConvertPandas(object):
numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test
@classmethod
def setupClass(cls):
try:
import pandas as pd
except ImportError:
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import os
import os.path
import subprocess
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.basic import is_executable
from ansible.module... |
from __future__ import unicode_literals, division, absolute_import
import difflib
import logging
import re
from bs4.element import Tag
from flexget.utils.soup import get_soup
from flexget.utils.requests import Session
from flexget.utils.tools import str_to_int
log = logging.getLogger('utils.imdb')
# IMDb delivers a... |
#!/usr/bin/env python
import platform
from setuptools import setup, find_packages
python_version = platform.python_version().rsplit(".", 1)[0]
install_requires = [
"boto3>=1.4.0",
"six>=1.9.0",
]
if python_version < "3.0":
install_requires.append("simplejson>=3.0.0")
if python_version < "3.5":
ins... |
#!/usr/bin/env python
import ecto
from ecto.tutorial import Increment, Add
from ecto import BlackBoxCellInfo as CellInfo, BlackBoxForward as Forward
class MyBlackBox(ecto.BlackBox):
"""
We encapsulate the plasm from the hello_tutorial by exposing the
start value of 'i2' as a parameter to the BlackBox and f... |
"""
Common transformation
"""
import logging
import re
from abc import ABC
from collections import namedtuple, OrderedDict
from model.array import Array
from model.enum import Enum
from model.struct import Struct
class InterfaceProducerCommon(ABC):
"""
Common transformation
"""
version = '1.0.0'
... |
from django.contrib import admin
import models
class OrganizationMemberTab(admin.TabularInline):
model = models.OrganizationMember
extra = 0
class OrganizationLocationTab(admin.TabularInline):
model = models.OrganizationLocation
extra = 0
class CharacterLocationRelationshipInline(admin.TabularInli... |
"""
Repository View
"""
#-------------------------------------------------------------------------
#
# GTK/Gnome modules
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# gramps modu... |
"""TensorFlow Lite Python Interface: Sanity check."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.lite.python import convert
from tensorflow.lite.python import lite_constants
from tensorflow.lite.python import op_hint
... |
import datetime
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.dispatch import receiver
from django.db import models
from django.utils.functional import cached_property
from allauth.account.signals import user_signed_up... |
from msrest.serialization import Model
class ApiErrorBase(Model):
"""Api error base.
:param code: The error code.
:type code: str
:param target: The target of the particular error.
:type target: str
:param message: The error message.
:type message: str
"""
_attribute_map = {
... |
"""Tests for tensorflow.python.framework.dtypes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.core.framework import types_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import te... |
from cuisine import *
from fabric.api import *
from fabric.context_managers import *
from fabric.utils import puts
from fabric.colors import red, green
import simplejson
import os
GIT_REPO = '<EMAIL>:Vossy/redacted-webapp.git'
def app_user(command):
'''
This helper method runs the given command as the weba... |
import uuid
import ddt
from nose.plugins import attrib
from tests.api import providers
@ddt.ddt
class TestSQLInjCreateService(providers.TestProviderBase):
"""Security Tests for SQL Injection for Create Service."""
def setUp(self):
super(TestSQLInjCreateService, self).setUp()
self.service_u... |
from django.test import TestCase
from django.utils import timezone
from main.models import MemberType, STATUS, ACTIVE
from main.models import User
from django.contrib.auth import authenticate, login as _login
from django.test.client import Client, RequestFactory
class UserFullNameTestCase(TestCase):
def setUp(se... |
from django.views.generic import View, TemplateView
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required
from django.conf import settings
from django import... |
"""
A sample script showing how to handle default values when communicating
with the Compute Engine API.
"""
# [START compute_instances_verify_default_value]
# [START compute_usage_report_set]
# [START compute_usage_report_get]
# [START compute_usage_report_disable]
from google.cloud import compute_v1
# [END compute_us... |
#!/usr/bin/env python
# This is a trimmed down version of Marc-Andre Lemburg's py2html.py.
# The original code can be found at http://starship.python.net/~lemburg/.
#
# Borrow (or steal?) PyFontify.py from reportlab.lib.
import PyFontify
import sys
pattern="""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html... |
from __future__ import absolute_import, division, print_function
try:
# future >= 0.12
from future.backports.test.support import import_fresh_module
except ImportError:
from future.standard_library.test.support import import_fresh_module
import unittest
import warnings
import numpy as np
import numpy.test... |
from openerp import api, fields, models
class MedicamentListItem(models.Model):
_name = 'myo.medicament.list.item'
list_version_id = fields.Many2one('myo.medicament.list.version', string='Medicament List Version',
help='Medicament List Version', required=False)
medic... |
import os
import json
from filepaths import *
def init_models_dict():
all_models_dict = {}
all_models_dict['dummy'] = {}
# If no dummy is added, the dictionary would be empty and the json file would be empty, causing an error on load.
with open(MODELS_DICT_PATH, 'a+') as fp:
json.dump(all_mod... |
import distutils.spawn
import os
import subprocess
from ansible import errors
from ansible.callbacks import vvv
import ansible.constants as C
class Connection(object):
''' Local lxc based connections '''
def _search_executable(self, executable):
cmd = distutils.spawn.find_executable(executable)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Get the version
version_regex = r'__version__ = ["\']([^"\']*)["\']'
with open('pyngboard/__init__.py', 'r') as f:
text = f.... |
#!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 10/14/14
###Function: OR of incidence in adults to incidence in children vs. week number normalized by the first 'gp_normweeks' of the season. Incidence in children and adults is normalized by the size... |
import abc
import logging
from six import with_metaclass
logger = logging.getLogger(__name__)
DEFAULT = "Android"
class YowsupEnvType(abc.ABCMeta):
def __init__(cls, name, bases, dct):
if name != "YowsupEnv":
YowsupEnv.registerEnv(cls)
super(YowsupEnvType, cls).__init__(name, bases, d... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
def post_annotation(module):
user = module.params['user']
api_key = ... |
import factory
from core.factories.matchday_related_core_factories import MatchdayFactory, SeasonFactory
from core.models import Contract, Country, Player, PlayerStatistics
from users.factories.users_factories import OFMUserFactory
class CountryFactory(factory.django.DjangoModelFactory):
class Meta:
mode... |
"""Model definition for the patent claim breadth model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
# Count features created in ../preprocess.py
FEATURE_NAMES = [
'word_cnt', 'word_cnt_unique', 'char_cnt', 'char_cnt_unique'... |
from __future__ import division
import os
from skimage import io
from skimage.util import random_noise
from skimage.filters import scharr
from scipy import ndimage
import matplotlib.pyplot as plt
import numpy as np
import cv2
import phasepack
def input_data(path, filename):
img_path = os.path.join(path, filen... |
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
import inspect
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, get_thread_id, dict_iter_items, DJANGO_SUSPEND, IS_PY2
from pydevd_file_utils import get_abs_path_real_path_and_base_from_file, normcase
from _pydevd_bundle.pydevd_brea... |
import requests
from django.utils.dateparse import parse_datetime
class RecipientMixin(object):
def parse_id(self, resource_uri):
return resource_uri.split('#')[-1].split('-', 1)[-1]
class Message(RecipientMixin, object):
def __init__(self, params, adapter):
self.id = params['id']
s... |
import contextlib
import uuid
import webob.exc
from neutron.plugins.nuage.extensions import netpartition as netpart_ext
from neutron.tests.unit.nuage import test_nuage_plugin
from neutron.tests.unit import test_extensions
class NetPartitionTestExtensionManager(object):
def get_resources(self):
return net... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: aci_tenant_span_src_group
short_description: Manage SPAN sou... |
from __future__ import unicode_literals
from ledger.accounts.models import EmailUser
def belongs_to(user, group_name):
"""
Check if the user belongs to the given group.
:param user:
:param group_name:
:return:
"""
return user.groups.filter(name=group_name).exists()
def is_officer(user):
... |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
# package
from openpyxl import Workbook
from openpyxl.xml.functions import tostring
# test imports
from openpyxl.tests.helper import compare_xml
def test_write_hyperlink_rels(datadir):
from .. relations import write_rels
wb = Workboo... |
'''
Taken from https://github.com/xzela/prawns
'''
from django.core.management import setup_environ
from djprawn import settings
from optparse import OptionParser
setup_environ(settings)
from rtube import api
# TODO store this in the database
PROVIDERS = ['rtube', 'kink']
api_urls = {
'rtube': {
'vi... |
import collections as coll
import numpy as np
from scipy import ndimage as ndi
from ..util import img_as_float
from ..color import guess_spatial_dimensions
from .._shared.utils import warn
__all__ = ['gaussian']
def gaussian(image, sigma=1, output=None, mode='nearest', cval=0,
multichannel=None):
"... |
# -*- coding: utf-8 -*-
"""
Copyright 2005 Spike^ekipS <<EMAIL>>
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 2 of the License, or
(at your option) any later version.
This pr... |
import numpy as np
from vispy import gloo, app
from vispy.gloo import Program
vertex = """
attribute vec2 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
} """
fragment = """
uniform s... |
import sys
import unittest
from libcloud.test import MockHttp
from libcloud.test.file_fixtures import DNSFileFixtures
from libcloud.test.secrets import DNS_PARAMS_NSONE
from libcloud.dns.drivers.nsone import NsOneDNSDriver
from libcloud.utils.py3 import httplib
from libcloud.dns.types import ZoneDoesNotExistError, Zon... |
__author__ = 'Eli'
import os
import shutil
from multiprocessing import Pool,cpu_count
import subprocess
import sys
import glob
import argparse
SELF_DIR = os.path.dirname(os.path.abspath(__file__))
PROC_NUM = max(1, cpu_count() - 2)
def clean_dir(folder):
print 'Cleaning %s' % folder
cmd = 'rm... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cms.models.static_placeholder
import cms.models.fields
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models, migrations
import django.utils.timezone
from django.utils.translation import ugette... |
NETWORK = 'network'
SUBNET = 'subnet'
PORT = 'port'
SECURITY_GROUP = 'security_group'
CREATE = 'create'
DELETE = 'delete'
UPDATE = 'update'
AGENT = 'q-agent-notifier'
PLUGIN = 'q-plugin'
DHCP = 'q-dhcp-notifer'
L3_AGENT = 'l3_agent'
DHCP_AGENT = 'dhcp_agent'
def get_topic_name(prefix, table, operation):
"""Cre... |
import mock
import pytest
from django.utils import timezone
from nose.tools import * # flake8: noqa
from datetime import datetime
from framework.guid.model import Guid
from api.base.settings.defaults import API_BASE
from api_tests import utils as test_utils
from tests.base import ApiTestCase
from osf_tests.factories... |
import sys
import xml.dom.minidom
from libglibcodegen import escape_as_identifier, \
get_docstring, \
NS_TP, \
Signature, \
type_to_gtype, \
xml_escape
def types_to_gtypes(types):
... |
from client import exceptions as ex
from client.api import assignment
from client.sources.common import core
import collections
import mock
import unittest
class LoadAssignmentTest(unittest.TestCase):
VALID_CONFIG = """
{
"name": "Homework 1",
"endpoint": "https://okpy.org/path/to/endpoint",
... |
from isc_dhcp_leases import IscDhcpLeases
from isc_dhcp_leases import Lease
from isc_dhcp_leases import Lease6
def parse(*files):
parsed_files = list(map(lambda file: IscDhcpLeases(file).get(), files))
return Leases(*parsed_files)
class Leases:
_leases = []
_iter = None
def __init__(self, *args... |
from unittest import mock
from django.test import TestCase
from allianceauth.tests.auth_utils import AuthUtils
from .models import CorpStats, CorpMember
from allianceauth.eveonline.models import EveCorporationInfo, EveAllianceInfo, EveCharacter
from esi.models import Token
from esi.errors import TokenError
from bravad... |
import argparse
import uuid
import os
from vnc_api.vnc_api import *
from vnc_api.gen.resource_common import *
def CamelCase(input):
words = input.replace('_', '-').split('-')
name = ''
for w in words:
name += w.capitalize()
return name
# end CamelCase
def str_to_class(class_name):
retur... |
import click
import six
from requests.exceptions import RequestException
from tower_cli import __version__
from tower_cli.api import client
from tower_cli.utils.decorators import command
from tower_cli.utils.exceptions import TowerCLIError
@command
def version():
"""Display version information."""
# Attemp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.