content stringlengths 4 20k |
|---|
from . import groups
from . import table
from . import base
from . import helpers
class Aggregate(base.Base):
def update(self, liveData):
self.clearScreen()
self.writeStatusLine(liveData.measurements)
metricGroups = groups.Groups(liveData.measurements)
visible = metricGroups.all()
... |
# Tests of the full ZIP64 functionality of zipfile
# The test_support.requires call is the only reason for keeping this separate
# from test_zipfile
from test import test_support
# XXX(nnorwitz): disable this test by looking for extra largfile resource
# which doesn't exist. This test takes over 30 minutes to run in ... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... |
from __future__ import absolute_import
from zerver.lib.initial_password import initial_password
from zerver.models import Realm, Stream, UserProfile, Huddle, \
Subscription, Recipient, Client, get_huddle_hash, resolve_email_to_domain
from zerver.lib.create_user import create_user_profile
def bulk_create_realms(re... |
'''
Classes for using multipart form data from Python, which does not (at the
time of writing) support this directly.
To use this, make an instance of Multipart and add parts to it via the factory
methods field and file. When you are done, get the content via the get method.
@author: Stacy Prowell (http://stacyprowe... |
#!/usr/bin/python
"""
Program to help setup kvm test environment
:copyright: Red Hat 2010
"""
import os
import sys
import logging
import common
from virttest import data_dir, bootstrap
test_name = "v2v"
test_dir = os.path.dirname(sys.modules[__name__].__file__)
test_dir = os.path.abspath(test_dir)
base_dir = data_dir... |
from collections import OrderedDict
from typing import Dict, Type
from .base import AssetServiceTransport
from .grpc import AssetServiceGrpcTransport
from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[AssetService... |
# encoding: UTF-8
import sys
from time import sleep
from PyQt4 import QtGui
from vnltsl2 import *
#----------------------------------------------------------------------
def print_dict(d):
"""按照键值打印一个字典"""
for key,value in d.items():
print key + ':' + str(value)
#-----------------... |
"""
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
Code for getting source code to put inside container.
"""
import logging
import copy
import os
import shutil
import tempfile
import collections... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import subprocess
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.facts.utils import get_file_content
from ansible.module_utils.facts.network.base import NetworkCollector
class I... |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
import urllib
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
fro... |
from kfp import dsl
def random_failure_op(exit_codes):
"""A component that fails randomly."""
return dsl.ContainerOp(
name='random_failure',
image='python:alpine3.6',
command=['python', '-c'],
arguments=['import random; import sys; '
'exit_code = random.choic... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
v_extrude.py
------------
Date : March 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
*************************************... |
"""This file contains code used in "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import math
import numpy as np
import first
import thinkplot
import thinks... |
import json
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.images.images \
import forms as images_forms
class AdminCreateImageForm(image... |
__all__ = ("WebSocketResource",
"HTTPChannelHixie76Aware",
"WSGIRootResource",)
from six.moves.urllib import parse
from zope.interface import implementer
from twisted.protocols.policies import ProtocolWrapper
try:
from twisted.web.error import NoResource
except:
## starting from Twisted ... |
class FormatMismatchError( Exception ): pass
class Finished( Exception ): pass
sFormatISOdateTime = '%Y-%m-%d %H:%M:%S'
sFormatISOdate = '%Y-%m-%d'
sFormatIsoNoSecs = '%Y-%m-%d %H:%M'
sFormatDateAm = '%m/%d/%Y'
sFormatDateAmShort = '%m/%d/%y'
sFormatDateEu = '%d/%m/%Y'
sFormatISONoSpace = '%Y-... |
#
# Thierry Parmentelat - INRIA
#
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Auth import Auth
from PLC.Ilinks import Ilink, Ilinks
from PLC.Interfaces import Interface, Interfaces
from PLC.TagTypes import TagType, TagTypes
from PLC.Sites import Sites
fr... |
import threading
import time
import speech
import ui
import tones
class RemoteSession(object):
def __init__(self, local_machine, transport):
self.local_machine = local_machine
self.transport = transport
class SlaveSession(RemoteSession):
"""Session that runs on the slave and manages state."""
... |
from __future__ import absolute_import
from django.views.decorators.csrf import csrf_exempt
from zerver.models import get_client
from zerver.decorator import asynchronous, \
authenticated_json_post_view, internal_notify_view, RespondAsynchronously, \
has_request_variables, REQ
from zerver.lib.response import... |
# Kleine correctie op BTW te vorderen hoog, id was hetzelfde voor beide, waardoor hoog werd overschreven door # overig. Verduidelijking van omschrijvingen in belastingcodes t.b.v. aangifte overzicht.
# versie 5.0.1.4
# BTW omschrijvingen aangepast, zodat rapporten er beter uitzien. 2a en 5b e.d. verwijderd en enk... |
"""Assertions related to event validation"""
from __future__ import absolute_import
import json
import pprint
import six
def assert_event_matches(expected, actual, tolerate=None):
"""
Compare two event dictionaries.
Fail if any discrepancies exist, and output the list of all discrepancies. The intent is... |
import re
import sys
# Write the config.c file
never = ['marshal', 'imp', '_ast', '__main__', 'builtins',
'sys', 'gc', '_warnings']
def makeconfig(infp, outfp, modules, with_ifdef=0):
m1 = re.compile('-- ADDMODULE MARKER 1 --')
m2 = re.compile('-- ADDMODULE MARKER 2 --')
for line in infp:
... |
from ...raw_dump import *
from ..addr import *
# TODO: Handle big pages
# Cf ARM reference manual, page 1282
def va_to_pa(va, pgd):
r = RawDump.getInstance()
# Split the virtual address into a PD index, PT index and page index
(pd_i, pt_i, page_i) = ((va >> 20), ((va >> 12) & (1 << 8)-1), (va & (1 << 12) - 1... |
# RFC 2822 - style email validation for Python
# (c) 2012 Syrus Akbary <<EMAIL>>
# Extended from (c) 2011 Noel Bush <<EMAIL>>
# for support of mx and user check
# This code is made available to you under the GNU LGPL v3.
#
# This module provides a single method, valid_email_address(),
# which returns True or False to i... |
"""SCons.Scanner.RC
This module implements the depenency scanner for RC (Interface
Definition Language) files.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this softwar... |
"""
Example showing an implementation of a flask server serving a flexx application.
If assets are needed (jpg, files, etc.) they can be placed a folder called static
and accessed through each flexx blueprints (e.g. http://my_flexx/picture.jpg). The
name of that folder can be changed when registering the blueprint.
... |
# -*- coding: utf-8 -*-
"""
werkzeug.debug.tbtools
~~~~~~~~~~~~~~~~~~~~~~
This module provides various traceback related utility functions.
:copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD.
"""
import re
import os
import sys
import inspect
import traceback
imp... |
import click
from ..utils import set_build_description as usbd
@click.command()
@click.option('--description', help="The description to set on the build")
@click.option('--replace/--no-replace', default=False, help="Replace existing description, if any, instead of appending.")
@click.option('--separator', default='\... |
#-*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
import os
import tempfile
from django.conf import settings
from django.core.files import File as DjangoFile
from django.core.management import call_command
from django.test import TestCase
from django.utils.six import StringIO... |
"""BibIndexAuthorCountTokenizer: counts number of authors for any publication
given by recID. Will look at tags: '100_a' and '700_a' which are:
'first author name' and 'additional author name'.
"""
from invenio.bibindex_engine_utils import get_field_count
from invenio.bibindex_tokenizers.BibIndexMultiFieldToken... |
from __future__ import print_function
from pyspark import SparkContext
# $example on$
from pyspark.mllib.feature import HashingTF, IDF
# $example off$
if __name__ == "__main__":
sc = SparkContext(appName="TFIDFExample") # SparkContext
# $example on$
# Load documents (one per line).
documents = sc.te... |
from __future__ import absolute_import, print_function, unicode_literals
from textwrap import TextWrapper
from mach.decorators import (
CommandProvider,
Command,
)
#@CommandProvider
class Settings(object):
"""Interact with settings for mach.
Currently, we only provide functionality to view what set... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import multiprocessing
import os
import tempfile
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.executor.play_iterator import PlayIterator
from ansible.executor.stats import AggregateStats
... |
import unittest, pickle, os
from mock import patch
from pokemongo_bot.cell_workers.follow_cluster import FollowCluster
class FollowClusterTestCase(unittest.TestCase):
@patch('pokemongo_bot.PokemonGoBot')
def testWorkAway(self, mock_pokemongo_bot):
forts_path = os.path.join(os.path.dirname(__file__), ... |
import os
import os.path
import socket
import textwrap
import subprocess
import contextlib
import sys
import tempfile
import time
import random
try:
import pytest
except ImportError:
print >> sys.stderr, "Integ tests require pytests!"
sys.exit(1)
def pytest_funcarg__servers(request):
"Returns a new A... |
# encoding: utf-8
# module samba.dcerpc.netlogon
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/netlogon.so
# by generator 1.135
""" netlogon DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class netr_SamBaseInfo(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): ... |
(lp0
(lp1
(S' '
p2
I95
tp3
aa(lp4
(g2
I14
tp5
a(S'#'
p6
I5
tp7
a(g2
I70
tp8
a(g6
I5
tp9
a(g2
I1
tp10
aa(lp11
(g2
I15
tp12
a(g6
I4
tp13
a(g2
I71
tp14
a(g6
I4
tp15
a(g2
I1
tp16
aa(lp17
(g2
I15
tp18
a(g6
I4
tp19
a(g2
I71
tp20
a(g6
I4
tp21
a(g2
I1
tp22
aa(lp23
(g2
I15
tp24
a(g6
I4
tp25
a(g2
I71
tp26
a(g6
I4
tp27
a(g2
I1
tp... |
from sos.report.plugins import Plugin, RedHatPlugin, SoSPredicate
from glob import glob
class Ipa(Plugin, RedHatPlugin):
short_desc = 'Identity, policy, audit'
plugin_name = 'ipa'
profiles = ('identity', 'apache')
ipa_server = False
ipa_client = False
files = ('/etc/ipa',)
packages = (... |
#coding=utf-8
import sys
from math import sin, cos
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QPoint
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QPainter
from PyQt4.QtGui import QColor
from PyQt4.QtGui import QPolygon
from PyQt4.QtCore import QString
try:
... |
from __future__ import absolute_import, division, print_function, with_statement
class SelectorValue:
"""
Represents a single select statement that contains conditions and an optional error message
"""
def __init__(self, conditions, no_match_message):
self.__conditions = conditions
se... |
"""The data layer used during training to train a Fast R-CNN network.
RoIDataLayer implements a Caffe Python layer.
"""
import caffe
from fast_rcnn.config import cfg
from roi_data_layer.minibatch import get_minibatch
import numpy as np
import yaml
from multiprocessing import Process, Queue
class RoIDataLayer(caffe.L... |
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import ExtractorError
class FunnyOrDieIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?funnyordie\.com/(?P<type>embed|articles|videos)/(?P<id>[0-9a-f]+)(?:$|[?#/])'
_TESTS = [{
'url': 'ht... |
"""Support for Google Cloud Pub/Sub."""
import datetime
import json
import logging
import os
from typing import Any, Dict
from google.cloud import pubsub_v1
import voluptuous as vol
from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import Event, HomeAssistan... |
from south.db import db
from django.db import models
from mysite.search.models import *
class Migration:
no_dry_run = True
def forwards(self, orm):
"Write your forwards migration here"
number_found = 0
for project in orm.Project.objects.all():
if project.name == 'Python... |
import sys
import time
py3k = sys.version_info >= (3, 0)
py33 = sys.version_info >= (3, 3)
py26 = sys.version_info >= (2, 6)
py25 = sys.version_info >= (2, 5)
jython = sys.platform.startswith('java')
win32 = sys.platform.startswith('win')
pypy = hasattr(sys, 'pypy_version_info')
if py3k:
from io import StringIO
... |
"""
Provides multithreaded parser for SAM files
"""
from __future__ import absolute_import
from __future__ import division
import os
import re
import sys
from collections import namedtuple, defaultdict
import subprocess
import logging
import multiprocessing
import ctypes
import time
import gzip
import io
import rando... |
from sklearn.kernel_approximation import (RBFSampler,Nystroem)
from sklearn.ensemble import RandomForestClassifier
import pandas
import numpy as np
import random
from sklearn.svm import SVC
from sklearn.metrics.pairwise import rbf_kernel,laplacian_kernel,chi2_kernel,linear_kernel,polynomial_kernel,cosine_similari... |
from __future__ import print_function
from __future__ import unicode_literals
import os, sys
lib_path = os.path.abspath('../all')
sys.path.append(lib_path)
from SetupTest import *
import unittest
import re
import sys
import os
if not (("PYTHONIOENCODING" in os.environ)
and
re.search("^utf-?8$",... |
"""
=================================================
Concatenating multiple feature extraction methods
=================================================
In many real-world examples, there are many ways to extract features from a
dataset. Often it is beneficial to combine several methods to obtain good
performance. Th... |
from datetime import datetime
from django.utils.timezone import get_current_timezone
from pyconcz_2016.proposals.models import Talk, Workshop, FinancialAid
tz = get_current_timezone()
class TalksConfig:
model = Talk
key = 'talks'
title = 'Talks'
cfp_title = 'Submit your talk'
template_about = '... |
"""
The label module contains the objects and methods used to
manage labels in Autotest.
The valid actions are:
add: adds label(s), or hosts to an LABEL
remove: deletes label(s), or hosts from an LABEL
list: lists label(s)
The common options are:
--blist / -B: file containing a list of LABELs
See topic_c... |
import requests
from decimal import Decimal
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.views import generic
from .models import Asset
from .forms import AssetForm
def _satoshi_to_bitcoin(num_satoshi):
return Decimal(0.00000001 * num_satoshi)
class AssetView(... |
import pymel.core as pm
import logging
log = logging.getLogger("ui")
class BaseTemplate(pm.ui.AETemplate):
def addControl(self, control, label=None, **kwargs):
pm.ui.AETemplate.addControl(self, control, label=label, **kwargs)
def beginLayout(self, name, collapse=True):
pm.ui.AETe... |
import subprocess
import os
import shutil
import time
from rackattack import clientfactory
from tests import testlib
import rackattack
class UserVirtualRackAttack:
MAXIMUM_VMS = 4
def __init__(self):
assert '/usr' not in rackattack.__file__
self._requestPort = 3443
self._subscribePort... |
# -*- coding: utf-8 -*-
# @Author: J. Alejandro Cardona Valdes
"""
Sistema de Tipos de MPascal
===========================
Este archivo define las clases de representacion de tipos. Esta es una
clase general usada para representar todos los tipos. Cada tipo es entonces
una instancia singleton de la clase tipo.
clas... |
"""Keras utilities.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.keras.python.keras.utils import conv_utils
from tensorflow.contrib.keras.python.keras.utils import data_utils
from tensorflow.contrib.keras.python.keras.utils imp... |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
items = UnwrapElement(IN[0])
def GetCompoundStructureLayers(item):
layers = []
layermat = []
layerfunc = []
layerwidth = []
layercore = []
layerwraps = []
la... |
from google.appengine.ext import ndb
import logging
import re
from models import Script
STRING_DATA_PATTERN = re.compile(r'"BlockStringData":\["(.*?[^\\])"')
def validate(blueprint):
for data in re.findall(STRING_DATA_PATTERN, blueprint):
if not data.find('update'):
# Not a Lua block, or not doing anythi... |
import os
import sublime
import sublime_plugin
try:
from .view_collection import ViewCollection
except (ImportError, ValueError):
from view_collection import ViewCollection
ST3 = int(sublime.version()) >= 3000
def plugin_loaded():
global settings
settings = sublime.load_settings('GitGutter.sublime-se... |
from src.platform.tomcat.interfaces import TINTERFACES
from requests.auth import HTTPBasicAuth
from requests.utils import dict_from_cookiejar
from sys import stdout
from log import LOG
import state
import utility
default_credentials = [("tomcat", "tomcat"),
("role1", "role1"),
... |
from io import BytesIO
import logging
import os
import re
import struct
import sys
from .compat import sysconfig, detect_encoding, ZipFile
from .resources import finder
from .util import (FileOperator, get_export_entry, convert_path,
get_executable, in_venv)
logger = logging.getLogger(__name__)
_D... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
HAS_INFINISDK = True
try:
from infinisdk import InfiniBox, core
except ImportError:
HAS_INFINISDK = False
from ansible.module_utils.infinibox import *
from collections im... |
import commander.commands as commands
import commander.commands.completion
import commander.commands.result
import commander.commands.exceptions
import re
__commander_module__ = True
class Argument:
def __init__(self, argtype, typename, name):
self.type = argtype.strip()
self.type_name = typename.... |
import ConfigParser
import json
import os
import sys
import unittest
from webserver import Httpd
from network import get_lan_ip
class WebDriverBaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = create_driver()
cls.webserver = Httpd(host=get_lan_ip())
cls.webs... |
import frappe
from frappe.model import rename_field
def execute():
tables = frappe.db.sql_list("show tables")
for doctype in ("Website Sitemap", "Website Sitemap Config"):
if "tab{}".format(doctype) in tables:
frappe.delete_doc("DocType", doctype, force=1)
frappe.db.sql("drop table `tab{}`".format(doctype))... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urllib_parse_urlencode,
)
from ..utils import (
clean_html,
int_or_none,
parse_duration,
parse_iso8601,
qualities,
update_url_query,
)
class UOLIE(InfoEx... |
#!/usr/bin/env python
from translate.convert import test_convert, txt2po
from translate.misc import wStringIO
from translate.storage import txt
class TestTxt2PO:
def txt2po(self, txtsource, template=None):
"""helper that converts txt source to po source without requiring files"""
inputfile = wSt... |
"""
Classes to represent the definitions of aggregate functions.
"""
class Aggregate(object):
"""
Default Aggregate definition.
"""
def __init__(self, lookup, **extra):
"""Instantiate a new aggregate.
* lookup is the field on which the aggregate operates.
* extra ... |
"""
Test finding orphans via the view and django config
"""
import json
from contentstore.tests.utils import CourseTestCase
from student.models import CourseEnrollment
from xmodule.modulestore.django import modulestore
from contentstore.utils import reverse_course_url
class TestOrphan(CourseTestCase):
"""
Tes... |
from __future__ import unicode_literals
from django.conf.urls import url
from django.core.urlresolvers import NoReverseMatch
from django.test import TestCase
from rest_framework.reverse import reverse
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
def null_view(request):
pass
... |
"""GDB support for WebKit types.
Add this to your gdb by amending your ~/.gdbinit as follows:
python
import sys
sys.path.insert(0, "/path/to/tools/gdb/")
import webkit
"""
import gdb
import re
import struct
def guess_string_length(ptr):
"""Guess length of string pointed by ptr.
Returns a tuple of (... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''Unit tests for the display module'''
# For testing purposes, clobber the rcfile
import matplotlib
matplotlib.use('Agg') # nopep8
import matplotlib.pyplot as plt
import numpy as np
# Import the hacked image comparison module
from mpl_ic import image_comparison
fro... |
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Relation(models.Model):
pass
class AbstractPerson(models.Model):
# DATA fields
data_abstract = models.CharField(max_len... |
from tests.gcp.operators.test_bigtable_system_helper import GCPBigtableTestHelper
from tests.gcp.utils.gcp_authenticator import GCP_BIGTABLE_KEY
from tests.test_utils.gcp_system_helpers import GCP_DAG_FOLDER, provide_gcp_context, skip_gcp_system
from tests.test_utils.system_tests_class import SystemTest
@skip_gcp_sys... |
import io
import unittest
from unittest.mock import patch
from kattis import k_pebblesolitaire
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run an... |
import fractions
import functools
import logging
import os
import string
import sys
import time
logging.basicConfig(level=logging.ERROR)
self_dir = os.path.abspath(os.path.dirname(__file__))
top_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir,
... |
import os
import sys
import warnings
import opcode # opcode is not a virtualenv module, so we can use it to find the stdlib
# Important! To work on pypy, this must be a module that resides in the
# lib-python/modified-x.y.z directory
dirname = os.path.dirname
distutils_path = os.path.join... |
"""
Testing for the approximate neighbor search using
Locality Sensitive Hashing Forest module
(sklearn.neighbors.LSHForest).
"""
import numpy as np
import scipy.sparse as sp
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import a... |
import os
import re
from django.contrib.gis.db.models import Extent3D, Union
from django.contrib.gis.db.models.functions import (
AsGeoJSON, AsKML, Length, Perimeter, Scale, Translate,
)
from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon
from django.test import TestCase, skipUnlessDBFeatu... |
from __future__ import print_function
from math import pi, sin, cos
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.resources import INLINE
from bokeh.util.browser import view
from bokeh.models.glyphs import Circle, Arc, Ray, Text
from bokeh.models import ColumnDataSource, Range1d, P... |
import mock
from oslotest import base
from ceilometer import neutron_client
class TestNeutronClient(base.BaseTestCase):
def setUp(self):
super(TestNeutronClient, self).setUp()
self.nc = neutron_client.Client()
@staticmethod
def fake_ports_list():
return {'ports':
... |
# -*- encoding:utf-8 -*-
import logging
import jinja2
from flask import abort
from flask import json
from bergenholm.database.groups import get_group_params
mongo = None
jinja_env = jinja2.Environment()
INSTALLED = "installed"
UUID = "uuid"
def get_hosts(query={}):
hosts = mongo.db.hosts.find(query, {'_id': 1... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObject... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create pipeline
#
v16 = vtk.vtkVolume16Reader()
v16.SetDataDimensions(64,64)
v16.GetOutput().SetOrigin(0.0,0.0,0.0)
v16.SetDataByteOrderToLittleEndian()
v16.SetFilePrefix("" + str(V... |
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.Console import Console
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Pixmap import Pixmap
from Components.Label import Label
from Components.MenuList import MenuList
from Components.config import Confi... |
from cStringIO import StringIO
import jsmin
import os.path
import re
import sys
def main(argv):
if len(argv) < 3:
print('usage: %s input_file imports_dir output_file' % argv[0])
return 1
input_file_name = argv[1]
imports_dir = argv[2]
output_file_name = argv[3]
input_file = ope... |
import struct
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
from gzip import GzipFile
def gunzip(data):
"""Gunzip the given data and return as much data as possible.
This is resilient to CRC checksum errors.
"""
f = GzipFile(fileobj=BytesIO(data))... |
import logging
import time
from typing import Any, Dict, Optional
import requests
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.plexus.hooks.plexus import PlexusHook
logger = logging.getLogger(__name__)
class PlexusJobOperator(BaseOperator):
"""
... |
"""Very low-level nginx config parser based on pyparsing."""
import string
from pyparsing import (
Literal, White, Word, alphanums, CharsNotIn, Forward, Group,
Optional, OneOrMore, Regex, ZeroOrMore)
from pyparsing import stringEnd
from pyparsing import restOfLine
class RawNginxParser(object):
# pylint: ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import os
import sys
import string
import unicodedata
class StateLaw:
_allowed_chars = set( ',()[]";:.-$§ \n' + "'"
+ string.ascii_letters
+ string.digits
#+ string.punctuation
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
PCA example with Iris Data-set
=========================================================
Principal Component Analysis applied to the Iris dataset.
See `here <http://en.wikipedia.org/wiki/Iris_flower_data_set>`_ fo... |
#!/usr/bin/env python3
"""
OpenOCD RPC example, covered by GNU GPLv3 or later
Copyright (C) 2014 Andreas Ortmann (<EMAIL>)
Example output:
./ocd_rpc_example.py
echo says hi!
target state: halted
target halted due to debug-request, current mode: Thread
xPSR: 0x01000000 pc: 0x00000188 msp: 0x10000fd8
variable @ 0x100... |
"""Testing for archive."""
import os
import os.path
import tarfile
import unittest
from tools.build_defs.pkg import archive
from tools.build_defs.pkg import testenv
class SimpleArFileTest(unittest.TestCase):
"""Testing for SimpleArFile class."""
def assertArFileContent(self, arfile, content):
"""Assert tha... |
#!/usr/bin/env python
"""Mailroom assignment, non-dictionary version"""
# Each sublist referred to as a 'donor record'
# with structure: [first_name, last_name, donation1, donation2...]
donor_list = [
["Jane", "Goodall", 324, 234],
["Bob", "Hunter", 2, 3],
["Margie", "Smith", 3],
["Tommmy", "Jarrel", ... |
"""
Tests of re-verification service.
"""
import ddt
from opaque_keys.edx.keys import CourseKey
from course_modes.models import CourseMode
from course_modes.tests.factories import CourseModeFactory
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
from lms.djangoapps.verify_... |
#!/usr/bin/env python
'''
extract mavlink mission from log
'''
import sys, time, os
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument("--output", default='mission.txt', help="output file")
parser.add_argument("logs", metavar="LOG", nargs="+")
args = parser.parse_ar... |
"""
.. module: security_monkey.watchers.s3
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <<EMAIL>> @monkeysecurity
"""
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
from security_monkey.exceptions import BotoConnectionIssue
from security_mo... |
#!/usr/bin/env python
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),
'pirc522')))
from pirc522 import __version__ # flake8: noqa
sys.path.pop(0)
setup(
name='... |
# -*- encoding: utf-8 -*-
import pytest
from abjad import *
from abjad.tools.lilypondparsertools import LilyPondParser
def test_lilypondparsertools_LilyPondParser__spanners__Slur_01():
r'''Successful slurs, showing single leaf overlap.
'''
target = Container(scoretools.make_notes([0] * 4, [(1, 4)]))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.