content stringlengths 4 20k |
|---|
"""Contains the logic for `aq show host --all`."""
from sqlalchemy.orm import contains_eager, lazyload
from aquilon.aqdb.model import Host, HardwareEntity, DnsRecord, DnsDomain, Fqdn
from aquilon.worker.broker import BrokerCommand
from aquilon.worker.formats.list import StringAttributeList
class CommandShowHostAll(... |
import sys
sys.path.append( '..' )
from PyRTF import *
def MergedCells( ) :
# another test for the merging of cells in a document
doc = Document()
section = Section()
doc.Sections.append( section )
# create the table that will get used for all of the "bordered" content
col1 = 1000
col2 = 1000... |
import argparse
import subprocess
import os
import xml.etree.ElementTree as etree
import shutil
from . import author
class Failure(Exception):
pass
def parse_author(elem):
attr = 'name', 'email', 'date'
val = []
for a in attr:
v = elem.get(a)
assert v is not None
val.append(v)
... |
r"""Converts WAV audio files into input features for neural networks.
The models used in this example take in two-dimensional spectrograms as the
input to their neural network portions. For testing and porting purposes it's
useful to be able to generate these spectrograms outside of the full model, so
that on-device i... |
" analytical test problem to validate 2D and 3D solvers "
import math
from collections import OrderedDict
from dolfin import *
from nanopores import *
from nanopores.physics.simplepnps import *
# --- define parameters ---
add_params(
bV = -0.1, # [V]
rho = -0.05, # [C/m**2]
h2D = .1,
h3D = .5,
Nmax = 1e5,
damp = 1.,
b... |
import logging
import stripe
from typing import Any, Dict, cast
from django.core import signing
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext as _
from django.shortcuts import render
from djang... |
from gevent import monkey; monkey.patch_all()
from nose.tools import assert_raises
import mock
from . import scheduler as _
from config import config_value
from job import Job
from digits.utils import subclass, override
class TestScheduler():
def get_scheduler(self):
return _.Scheduler(config_value('gpu_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
def plot_cup():
"""
"""
ymin, ymax, zmin, zmax = minmax(dmax)
#print(ymin, ymax, zmin, zmax)
step = 5.0
ny = int( np.around((ymax - ymin)/step) ) + 1
nz = int( np.around((zmax - zmin)/step) ) + 1
print(ny, nz)
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 03 13:30:41 2012
@author: jharston
"""
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
class leslieAlgorithmPage(webapp.RequestHandler):
def get(self):
text_file1 =... |
# -*- coding: utf-8; -*-
import argparse
from .cli_base import CliBase
from customs.utils import logger
from customs import Agency, Rules
class RulesCommand(CliBase):
""" Rules
"""
def __init__(self, sub_parser):
logger.setup_logging('cli')
if not isinstance(sub_parser, argpars... |
import time
import threading
from plan.settings import TICK_RATE
class Ticker(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__callbacks = []
self.__tick_rate = TICK_RATE
self.__is_ticking = False
self.daemon = True
@pro... |
import time
import json
import importlib
import pandas as pd
import logging
from dipde.internals.firingrateorganizer import FiringRateOrganizer
from dipde.internals.internalpopulation import InternalPopulation
from dipde.interfaces.pandas import reorder_df_columns
from dipde.internals import utilities
from dipde.inter... |
import os
import re
from subprocess import Popen,PIPE
from pprint import pprint
try:
import configparser
config = configparser.ConfigParser()
except ImportError:
import ConfigParser
config = ConfigParser.ConfigParser()
class Config:
"""Pseudo class used to share global configuration"""
# Other values ar... |
"""Setup for pip package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['numpy', 'dm-sonnet==1.35', 'tensorflow==1.14',
'tensorflow-probabilit... |
import scrapy
import os
from scrapy.http import Request
from .. import items
class Spider(scrapy.Spider):
name = 'spider'
allowed_domains = ["imdb.com"]
start_urls = [os.environ["START_URL"]]
def start_requests(self):
for url in self.start_urls:
yield Request(url, dont_filter=Fals... |
import re
from django.conf import settings
from django.http import HttpResponseServerError
from django.utils.encoding import smart_unicode
from dojango.util import dojo_collector
class AJAXSimpleExceptionResponse:
"""Thanks to newmaniese of http://www.djangosnippets.org/snippets/650/ .
Full doc (copied from... |
from testtools import TestCase
from testtools.matchers import (
DocTestMatches,
Equals,
LessThan,
MatchesStructure,
Mismatch,
NotEquals,
)
from testtools.matchers._higherorder import (
AfterPreprocessing,
AllMatch,
Annotate,
AnnotatedMismatch,
AnyMatch,
MatchesAny,
... |
"""
@todo: Import ValueMeta from valueabc subpackage
"""
import abc
import meets
# Support functions
class ClsWrapException(Exception):
"""Base exception type for clswrap package."""
pass
class InterfaceTypeError(ClsWrapException, TypeError):
"""Raised during wrapper instantiation, when a passed-in
o... |
import collections
class Counter(collections.Counter):
def __xor__(self, other):
''' Subtract count, but keep only abs results with non-zero counts.
>>> Counter('abbbc') ^ Counter('bccd')
Counter({'b': 2, 'a': 1, 'c': 1, 'd': 1})
>>> a, b = Counter('abbbc'), Counter('bccd')
... |
import datetime
import logging
import uuid
# Django
from django.contrib.auth.mixins import LoginRequiredMixin
from django.forms.models import modelformset_factory
from django.http import (
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.shortcuts import (
get_object_or_404,
render,
)
from dj... |
"""This module is for loading historical data for stocks"""
from yahoo_historical import Fetcher
import arrow
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db.models import Max
from django.http import HttpResponse
from .models import Stock, DailyStockQuote
def create_... |
# Look at words
# Matt Prelee
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sbn
import pickle
import nltk
import re
from sklearn import base
from sklearn.linear_model import LinearRegression, Lasso, ElasticNet
from sklearn.feature_extraction.text import CountVectorizer, Tfidf... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
try:
from cStringIO import StringIO
except ImportError:
... |
import matplotlib
#matplotlib.use('TkAgg')
matplotlib.use('svg')
import matplotlib.pyplot as plt
import pylab as pl
import random as rd
import scipy as sp
import networkx as nx
import numpy as np
import math as mt
import pprint as ppt
time_list = []
energy_state_g = []
energy_state_o = []
perturbation_period = 1000
... |
from epiphany.instruction import Instruction
from epiphany.isa import decode
from epiphany.machine import RESET_ADDR
from epiphany.test.machine import StateChecker, new_state
import opcode_factory
import pytest
def test_execute_gid16():
state = new_state(rfSTATUS=0)
instr = opcode_factory.gid16()
name, e... |
import socket
import netifaces as ni
import json, urllib.request
class RemoteRelay:
def getAll (self):
rcv = False
iter = 0
while (rcv == False):
iter = iter + 1
if (iter > 5):
self.relay1 = "NA"
self.relay2 = "NA"
self... |
import setuptools
if __name__ == "__main__":
setuptools.setup(
name='gitgrid',
version='0.1',
license='MIT',
packages=setuptools.find_packages(),
install_requires=[
'numpy>=1.7',
'mido',
'matplotlib',
],
extras_require={
... |
# This file is generated by /tmp/pip-kUGBJh-build/-c
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
lapack_opt_info={'libraries': ['openblas', 'openblas'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
blas_opt_info=... |
""" Class to render ascii from md """
import mistune
class md_to_ascii(mistune.Renderer):
""" md_to_ascii class """
def __init__(self, colors):
mistune.Renderer.__init__(self)
self.colors = colors
# Pagelayout
def block_code(self, code, lang):
return '\n\033[' + self.colors['c... |
import sys
from distutils.core import setup
setup(name='pystdf',
version='1.3.3',
description="Python module for working with STDF files",
long_description="""
PySTDF is a Python module that makes it easy to work with STDF (Teradyne's Standard Test Data Format). STDF is a commonly used file format in semic... |
import json
import os
import subprocess
import socket
import sys
def do_hooks(hooks):
hook = os.path.basename(sys.argv[0])
try:
hook_func = hooks[hook]
except KeyError:
juju_log('INFO',
"This charm doesn't know how to handle '{}'.".format(hook))
else:
hook_fun... |
"""Unit tests for recommendations_services."""
from core.domain import exp_services
from core.domain import recommendations_services
from core.domain import rights_manager
from core.domain import user_services
from core.platform import models
from core.tests import test_utils
import feconf
(recommendations_models, ex... |
"""docker"""
import http.client
import json
import socket
__all__ = ['HTTPConnection', 'HTTPError', 'get']
class HTTPConnection(http.client.HTTPConnection):
def __init__(self):
http.client.HTTPConnection.__init__(self, 'localhost')
def connect(self):
sock = socket.socket(socket.AF_UNIX, so... |
import json
from sqlalchemy.types import Text
from sqlalchemy.types import TypeDecorator
class JsonObject(TypeDecorator):
"""Represents an immutable json-encoded string."""
impl = Text
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
... |
#!/usr/bin/env python
# Brandon Heller
# Parse processed mongo DB to output CSV suitable for Tableau exploration.
#
# See CommitCSVWriter for the fields and their ordering.
from optparse import OptionParser
import os
import time
from os.path import isfile
import pymongo
# Mode, used for performance testing: [normal,... |
import numpy as np
from numpy.testing import assert_almost_equal as almost
import unittest
from astropy import units as u
import MulensModel as mm
def test_n_lenses():
"""check n_lenses property"""
model_1 = mm.Model({"t_0": 2456789., "u_0": 1., "t_E": 30.})
model_2 = mm.Model({"t_0": 2456789., "u_0": 1.... |
"""Main file for E20-Kit2-Demo"""
# --------------------------------------------------------------------------------------------------------
# Imports and setup
# --------------------------------------------------------------------------------------------------------
# import basic needs
import logging
import time
imp... |
# -*- coding: utf-8 -*-
import sys
import logging.config
import numpy as np
from gmsdk import *
from framework import TAStrategy
from framework import helper
from framework.physics import *
from talib import SMA as MA
def algo(st, bar):
print(st.ticks_to_dataframe()[['datetime', 'symbol', 'last_price']])
... |
#!/usr/bin/python3
import xml.sax
import logging
import re
logger = logging.getLogger(__name__)
class ChunkHandler_m(xml.sax.ContentHandler):
'Chunk class refers to a set of annotation marks in the xml file'
def __init__(self,dictionary):
self.CurrentData = ""
self.trans=""
self.form=... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import tensorflow as tf
from niftynet.engine.image_window import ImageWindow
from niftynet.utilities.util_common import ParserNamespace
from tests.niftynet_testcase import NiftyNetTestCase
def get_static_window_param():
return dict(
... |
from lib.cuckoo.common.abstracts import Signature
class Office_Macro(Signature):
name = "office_macro"
description = "Office文件中包含宏(macro)"
severity = 2
categories = ["office"]
authors = ["KillerInstinct"]
minimum = "0.5"
def run(self):
ret = False
if "static" in self.result... |
# -*- coding: utf-8 -*-
import sys
import os
import json
import argparse
import shutil
from api import Api
# Configuration
template_file_path = "templates/config_bot_default.json"
config_folder = 'config'
setting_file_name = config_folder + '/config_bot.json'
settings = None # Load here configurat... |
#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup_kwargs = {}
try:
setup_kwargs['long_description'] = open('README.rst').read()
except IOError:
# Us... |
import re
import copy
import pprint
import jsonschema
from jsonschema.exceptions import ValidationError
class DRY(object):
string = {'type': 'string'}
class Validator(object):
core_schema = {
'type': 'object',
'properties': {
'id': {
'type': 'object',
... |
from flask import jsonify, request, g
from flask_cors import cross_origin
from alerta.app.auth.utils import permission
from alerta.app.exceptions import RejectException, RateLimit, BlackoutPeriod
from alerta.app.models.alert import Alert
from alerta.app.models.metrics import Timer, timer
from alerta.app.utils.api impo... |
# -*- coding: utf-8 -*-
"""Unshortener Documentation
This module unshortens URLs
"""
import re
import http
from urllib.parse import urlparse
from http import client
from isurlshortener.exceptions import PathMissing, UnhandledHTTPStatusCode, LocationHeaderMissing, ProtocolException
class Unshortener(object):
... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: install_data.py
"""distutils.command.install_data
Implements the Distutils 'install_data' command, for installing
platform-independent data files.""... |
# -*- coding: utf-8 -*-
import sys
import logging
import warnings
from logging.config import dictConfig
from twisted.python.failure import Failure
from twisted.python import log as twisted_log
import scrapy
from scrapy.settings import Settings
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.... |
import json
import uuid
from openstackclient.tests.functional.volume.v1 import common
class QosTests(common.BaseVolumeTests):
"""Functional tests for volume qos. """
def test_volume_qos_create_list(self):
"""Test create, list, delete multiple"""
name1 = uuid.uuid4().hex
cmd_output = ... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2013-2017 Alex Forencich
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 limitation the... |
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.types import CallResult
from autobahn.twisted.wamp import ApplicationSession
class Component(ApplicationSession):
"""
Application component that provides procedures which
return complex results.
""... |
#
# Encapsulation of statistics for a 6D particle distribution.
#
#
# Python imports
import math
# SciPy imports
import numpy as np
import scipy as sp
def calcAverages6D(array6D):
return sp.average(array6D, axis=1)
def subtractAverages6D(array6D):
averages6D = calcAverages6D(array6D)
for nLoop in ran... |
"""compare.py
Compare two files with TTK link output, the first is considered the baseline and
the second the response. Compare the SLINKs on the begin and end offsets of the
events involved and check the SLINKs for the atributes listed in ATTRS.
At thispoint this script is only used for SLINKs.
There is overlap wit... |
from itertools import cycle
from queue import Queue
import re
import random
# This is a block of text extracted from http://en.wikipedia.org/wiki/Poetry
srctxt = """Poetry is a form of literature that uses aesthetic and rhythmic qualities of language such as phonaesthetics
sound symbolism, and metre to evoke meanings ... |
from gosubl import gs
from gosubl import gsq
from gosubl import kv
from gosubl import mg9
from gosubl import ui
from gosubl import vu
import os
import re
import sublime
import sublime_plugin
DOMAIN = 'GsDoc'
GOOS_PAT = re.compile(r'_(%s)' % '|'.join(gs.GOOSES))
GOARCH_PAT = re.compile(r'_(%s)' % '|'.join(gs.GOARCHES)... |
from marshmallow import Schema, fields
class Copy(Schema):
"""Schema for an individual copy.
A title has one or more items in a library.
"""
available = fields.Boolean()
branch = fields.String()
due_date = fields.Date()
id = fields.String()
position = fields.String()
type = fields... |
# -*- coding: utf-8 -*-
import os
import re
import subprocess
from .misc import encode, fsjoin, renice
from .UnRar import ArchiveError, CRCError, PasswordError, UnRar
class SevenZip(UnRar):
__name__ = "SevenZip"
__type__ = "extractor"
__version__ = "0.25"
__status__ = "testing"
__description__ ... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import re
import os
from ._guest_common import *
class GuestUpload(GuestCommand):
def __init__(self, *args, **kwargs):
super(... |
from awsutils.s3client import S3Client
from awsutils.s3.bucket import S3Bucket
class S3Service:
def __init__(self, s3client):
"""
@param s3client: the s3client to be used for communication
@type s3client: S3Client
"""
self.s3client = s3client
def getBucket(self, name):
... |
# -*- coding: utf8 -*-
# Requires python-ntlm (http://code.google.com/p/python-ntlm/) package
from thlib.side.ntlm import HTTPNtlmAuthHandler
try:
import urllib2
import xmlrpclib
from cookielib import CookieJar
from urllib2 import Request, HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, ProxyHan... |
from unittest import TestCase
from Game.GameMode import GameMode
class TestGameMode(TestCase):
def setUp(self):
pass
def test_gm_new(self):
gm = GameMode(mode="test", priority=1)
self.assertIsInstance(gm, GameMode)
def test_gm_new_bad_priority(self):
with self.assertRaise... |
import interfaceIR
from jinja2 import contextfilter
#---------------------------------------------------------------------------------------------------
# Global objects used by the C API
#---------------------------------------------------------------------------------------------------
_CONTEXT_TYPE = interfaceIR.Ba... |
import ctypes
import re
import unicodedata
EnumWindows = ctypes.windll.user32.EnumWindows
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
GetWindowText = ctypes.windll.user32.GetWindowTextW
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
I... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0018_auto_20150207_1535'),
]
... |
import os, sys
def pinghost(hostname='www.google.com', wait='20'):
'''
hostname - either ip or hostname in str type
wait - sec in str type
Date : 29.05.2014
'''
response = os.system("ping -c 1 -t " + wait + ' ' + hostname + " > /dev/null 2>&1")
#time.sleep(int(wait))
if respon... |
rcParams = {
"timeseries": {
"oseries": {
"fill_nan": "drop",
"sample_down": "drop"},
"prec": {
"sample_up": "bfill",
"sample_down": "mean",
"fill_nan": 0.0,
"fill_before": "mean",
"fill_after": "mean"},
"eva... |
"""
Title: Psyko DDoS
Type: Hacking Tool
Version: 1.0
Author: Brandon Hammond
Summary: Psyko DDoS is a Python DDoS
tool that uses TCP packets
to conduct a layer 4 DDoS
attack on the target IP
address at the given port.
It uses multithreading to
distribute the DDoS ... |
import unittest
from clock import Clock
# Tests adapted from `problem-specifications//canonical-data.json`
class ClockTest(unittest.TestCase):
# Create A New Clock With An Initial Time
def test_on_the_hour(self):
self.assertEqual(str(Clock(8, 0)), "08:00")
def test_past_the_hour(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
import djangomosql
VERSION = djangomosql.__version__
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
def get_install_requires():
filename = os.path.join(o... |
# -*- coding: utf-8 -*-
import string
from scrapy.http import Request
from scrapy.selector import Selector
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapC... |
# -*- encoding: utf-8 -*-
from .base import *
DEBUG = False
TESTING = get_env_variable_bool("TESTING")
if get_env_variable_bool("SSL"):
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
ALLOWED_HOSTS = [get_env_variable("ALLOWED_HOSTS")]
DOMAIN = get_env_variable("DOMAIN")
DATABASE = DOMAIN.replace("."... |
__author__ = 'schlitzer'
# stdlib
import argparse
import codecs
import configparser
from collections import deque
import glob
import json
import os
import signal
import sys
import syslog
import time
import logging
from logging.handlers import TimedRotatingFileHandler, SysLogHandler
# 3rd party
import jsonschema
import... |
__author__ = "Simon Wessing"
class HyperVolume:
"""
Hypervolume computation based on variant 3 of the algorithm in the paper:
C. M. Fonseca, L. Paquete, and M. Lopez-Ibanez. An improved dimension-sweep
algorithm for the hypervolume indicator. In IEEE Congress on Evolutionary
Computation, pages 115... |
from __future__ import unicode_literals
import uuid
from datetime import date, datetime, time
import dateutil
from flask import jsonify, request, session
from marshmallow import fields, validate
from marshmallow_enum import EnumField
from werkzeug.exceptions import Forbidden
from indico.core import signals
from indi... |
from sys import maxsize
class Project:
def __init__(self, name=None, description=None, id=None):
self.name = name
self.description = description
self.id = id
def __repr__(self):
return "%s:%s:%s" % (self.id, self.name, self.description)
def __eq__(self, other):
... |
"""
Parser and utilities for the smart 'if' tag
"""
# Using a simple top down parser, as described here:
# http://effbot.org/zone/simple-top-down-parsing.htm.
# 'led' = left denotation
# 'nud' = null denotation
# 'bp' = binding power (left = lbp, right = rbp)
class TokenBase(object):
"""
Base class for ope... |
from nailgun.objects.serializers.base import BasicSerializer
class ReleaseSerializer(BasicSerializer):
fields = (
"id",
"name",
"version",
"can_update_from_versions",
"description",
"operating_system",
"modes_metadata",
"roles_metadata",
"wi... |
"""
DataflowRunner implementation of MetricResults. It is in charge of
responding to queries of current metrics by going to the dataflow
service.
"""
from apache_beam.metrics.metric import MetricResults
# TODO(pabloem)(JIRA-1381) Implement this once metrics are queriable from
# dataflow service
class DataflowMetrics... |
"""Constants for an RCV tabulation"""
from sb1288.decimal5 import Decimal5 as Decimal
from sb1288.decimal5 import Decimal5Total as DecimalTotal
ZERO = Decimal(0)
ONE = Decimal(1)
MIN_RANKINGS_SUPPORTED = 3
RANKING_CODE_SKIPPED = ''
RANKING_CODE_OVERVOTE = '#'
RANKING_CODES_NOT_A_CANDIDATE = set((
RANKING_CODE... |
"""
io.py
Classes for interaction with files.
"""
# Load the needed packages
import code
import pyart
import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '...')
sys.path.insert(0, path)
import artview
from ..core import Component, Variable, common, QtWidgets, QtCo... |
from driver_env import env
from driver_log import Log
import driver_tools
import subprocess
EXTRA_ENV = {
'DO_WRAP': '1',
'ARGS' : '',
'OUTPUT' : '',
'HAVE_OUTPUT' : '0',
}
PATTERNS = [
( '--do-not-wrap', "env.set('DO_WRAP', '0')"),
(('-o','(.*)'), "env.set('OUTPUT', pathtools.normalize($0))\n" ... |
from typing import Any, Dict, List
import re
from absl import logging
from git import GerritGit
from patch_parser import map_comments_to_gerrit, parse_comments, Patch, Patchset
from pygerrit2 import GerritRestAPI
from requests import PreparedRequest
from requests.auth import AuthBase
from http.cookiejar import CookieJa... |
"""This module loads all the selenium tests for the GUI."""
# pylint: disable=unused-import
from grr.gui.plugins import acl_manager_test
from grr.gui.plugins import artifact_manager_test
from grr.gui.plugins import artifact_view_test
from grr.gui.plugins import container_viewer_test
from grr.gui.plugins import crash... |
# -*- coding: utf-8 -*-
"""This file contains a class for basic formatoption properties of simple x-y
plot
"""
from copy import deepcopy
from ..defaults import texts
__author__ = "Philipp Sommer (<EMAIL>)"
__version__ = '0.0'
class BaseFmtProperties(object):
def default(self, x, doc):
"""default property... |
import pytest
from .type_ident import *
from .test_utils import MockUUIDObject
_TYPES = ['int', 'float', 'str', 'ndarray', 'bool', 'uuid']
class TestStandardTyping(object):
# this tests everything in STANDARD_TYPING; it's a little more
# integration test than unit, but the individual tests ensure that each
... |
from datetime import datetime
from jinja2 import Markup
from flask import current_app
class _moment(object):
@staticmethod
def include_moment(version='2.5.1', local_js=None):
js = ''
if local_js is not None:
js = '<script src="%s"></script>\n' % local_js
elif version is not... |
from gtrackcore.preprocess.PreProcMetaDataCollector import PreProcMetaDataCollector
from gtrackcore.preprocess.PreProcessUtils import PreProcessUtils
from gtrackcore.preprocess.memmap.OutputManager import OutputManager
class PreProcessGeSourceJob(object):
VERSION = '0.95'
def __init__(self, trackName,... |
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import editorScene
class editorViewClass(QGraphicsView):
def __init__(self, parend=None):
super(editorViewClass, self).__init__()
self.setDragMode(QGraphicsView.RubberBandDrag)
#self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
... |
# -*- coding: utf-8 -*-
"""This module contains methods for discovering Sonos devices on the
network."""
from __future__ import unicode_literals
import logging
import socket
import select
from textwrap import dedent
import time
import struct
from . import config
from .utils import really_utf8
_LOG = logging.getLogg... |
from django.shortcuts import render
from django.http import JsonResponse
from .forms import EditorTestForm
from .models import Blog
# Create your views here.
def editor_md_test(request):
if request.method == "POST":
form = EditorTestForm(request.POST)
if form.is_valid():
form.save()
... |
from nova import exception
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log
from nova.openstack.common import processutils
from nova import utils
LOG = log.getLogger(__name__)
def teardown_network(container_id):
try:
output, err = utils.execute('ip', '-o', 'netns', '... |
import os
import os.path
import sys
if os.path.exists('../bind2nsd/Config.py'):
sys.path.append('../bind2nsd')
from Utils import *
else:
from bind2nsd.Utils import *
class Key:
def __init__(self, name):
self.name = name
self.algorithm = ''
self.secret = ''
self.ipaddrs = []
... |
from django.conf.urls import url
from django.views.generic import TemplateView
from makam import views
uuid_match = r'(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})'
title_match = r'(?:/(?P<title>[\w-]+))?'
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='makam/index.html'),... |
"""
Generate data useful for the avocado framework and tests themselves.
"""
import logging
import os
import random
import string
import tempfile
_RAND_POOL = random.SystemRandom()
log = logging.getLogger('avocado.test')
def generate_random_string(length, ignore=string.punctuation,
conve... |
import json
from django.core.management.base import BaseCommand
from game.round.models import Round
from game.control.models import Control, Survey
from game.users.models import User
from game.contrib.decimal_encoder import DecimalEncoder
class Command(BaseCommand):
def handle(self, *args, **options):
... |
'''
Created on Aug 21, 2014
@author: davide
'''
class GraphPlotter():
'''
classdocs
'''
def __init__(self, pushupWidget, pushups):
'''
Constructor
'''
self.graphWidget = pushupWidget
self.pushups = pushups
def getGraphWidget(self):
return self... |
import math, sys, time
import random as random
SIZE = 9
GAMES = 200
KOMI = 7.5
EMPTY, WHITE, BLACK = 0, 1, 2
SHOW = {EMPTY: '.', WHITE: 'o', BLACK: 'x'}
PASS = -1
MAXMOVES = SIZE*SIZE*3
TIMESTAMP = 0
MOVES = 0
def to_pos(x,y):
return y * SIZE + x
def to_xy(pos):
y, x = divmod(pos, SIZE)
return x, y
class... |
"""Main product initializer
"""
from zope.i18nmessageid import MessageFactory
from uwosh.librarygroupfinder import config
from Products.Archetypes import atapi
from Products.CMFCore import utils
# Define a message factory for when this product is internationalised.
# This will be imported with the special name "_" i... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os.path
from aldryn_apphooks_config.mixins import AppConfigMixin
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.