content stringlengths 4 20k |
|---|
"""Check if the sender is a valid zenoss admin. This is called on every
incomming message."""
from Jabber.Plugins import Plugin
from Jabber.ZenAdapter import ZenAdapter
class AAZenossAdminPlugin(Plugin):
capabilities = ['accessControl']
def call(self, sender, log, **kw):
log.debug('Zenoss Admin use... |
"""
.. module: security_monkey.watchers.config_recorder
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Bridgewater OSS <<EMAIL>>
"""
from security_monkey.decorators import record_exception, iter_account_region
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils import try_import_tf
tf = try_import_tf()
class SimpleQModel(TFModelV2):
"""Extension of standard TFModel to provide Q values.
... |
'''
QuickSelect Function that selects kth position element in sorted array using quickSort
Params : a - array to be sorted
start - start position of to be sorted subset
end - end position of to be sorted subset
pos - the k where we need to find kth element
Quick Select... |
# List of known complex data formats
# you can use any other, but thise are widly known and supported by polular
# software packages
# based on Web Processing Service Best Practices Discussion Paper, OGC 12-029
# http://opengeospatial.org/standards/wps
"""List of known mimetypes
"""
from lxml.builder import ElementMa... |
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('cassandra').addHandler(NullHandler())
__version_info__ = (3, 2, 2, 'post0')
__version__ = '.'.join(map(str, __version_info__))
class ConsistencyLevel(object):
"""
Spcifies how many replicas must... |
from neutron_lib import exceptions
from oslo_utils import uuidutils
from neutron.api import extensions
from neutron.api.v2 import base
from neutron.db import servicetype_db
from neutron.extensions import servicetype
from neutron import manager
from neutron.plugins.common import constants
from neutron.services import s... |
#!/usr/bin/env python
import rospy
import math
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
import sys
import smbus
import subprocess
# Bus connecting Raspberry Pi and Arduino
bus = smbus.SMBus(1)
# Address of Arduino Slave
address_UL = 0x04
address_UR = 0x09
address_BL = 0x05
address_BR = ... |
import sys
import urllib
import urllib2
import urlparse
import xbmcgui
import xbmcplugin
import xbmcaddon
import xbmcvfs
import json
import base64
addonID = 'plugin.audio.radiobrowser'
addon = xbmcaddon.Addon(id=addonID)
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
... |
# coding=utf-8
import subprocess
from StorageClient import *
from sandbox_scripts.QualiEnvironmentUtils.Sandbox import *
import tempfile
import pip
try:
imported_tftpy = True
import tftpy
except:
try:
pip.main(["install","tftpy"])
import tftpy
except:
imported_tftpy = False
c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
import feedgen.version
setup(
name = 'feedgen',
packages = ['feedgen', 'feedgen/ext'],
version = feedgen.version.version_full_str,
description = 'Feed Generator (ATOM, RSS, Podcasts)',
author = 'Lars Kiesow',
author_email = '<E... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script searches all directories listed in dirs (relative to ltfatroot)
# for occurrence of ltfatarghelper and replaces it with a defined code.
#
#
from __future__ import print_function
import os
import sys
from collections import defaultdict
# Directories... |
import mock
from rally import exceptions
from rally.task import types
from tests.unit import fakes
from tests.unit import test
class FlavorResourceTypeTestCase(test.TestCase):
def setUp(self):
super(FlavorResourceTypeTestCase, self).setUp()
self.clients = fakes.FakeClients()
self.clients... |
"""Test the FireServiceRota config flow."""
from unittest.mock import patch
from pyfireservicerota import InvalidAuthError
from homeassistant import data_entry_flow
from homeassistant.components.fireservicerota.const import DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME
from tests.comm... |
#! /usr/bin/env python
"""Name of dataset."""
__docformat__ = 'restructuredtext'
COPYRIGHT = """This is public domain."""
TITLE = """Engel (1857) food expenditure data"""
SOURCE = """
This dataset was used in Koenker and Bassett (1982) and distributed alongside
the ``quantreg`` package for R.
Koenker, ... |
import binascii
import os
import mmap
import sys
import time
import errno
from io import BytesIO
from smmap import (
StaticWindowMapManager,
SlidingWindowMapManager,
SlidingWindowMapBuffer
)
# initialize our global memory manager instance
# Use it to free cached (and unused) resources.
mman = SlidingWind... |
#!/usr/bin/env python
"""
extract_hmmer3_protein_match.py [--models hmmer3|custom_hmmer3] <input dir> <output dir>
Approach:
1. Search with Pfam only & require significant MHC_I or MHC_I and C1, and Score(MHC_I)>Score(MHC_II_beta)
2. Extract 1 representative match per gene
3. Update models and re-search
NB: This ver... |
"""Export RT-DC measurement data"""
import codecs
import pathlib
import warnings
import h5py
try:
import imageio
except ModuleNotFoundError:
IMAGEIO_AVAILABLE = False
else:
IMAGEIO_AVAILABLE = True
try:
import fcswrite
except ModuleNotFoundError:
FCSWRITE_AVAILABLE = False
else:
FCSWRITE_AVA... |
from oslo_log import log as oslo_logging
from cloudbaseinit.plugins.common import createuser
LOG = oslo_logging.getLogger(__name__)
class CreateUserPlugin(createuser.BaseCreateUserPlugin):
@staticmethod
def _create_user_logon(user_name, password, osutils):
try:
# Create a user profile ... |
from Tome.helpers.debug import Printer
BASE_PATH = '/home/ahayward3/'
progress = Printer(True)
def getFile(path):
return open(path)
def createFile(path):
return open(path, 'w')
def closeFile(file):
file.close()
def addToNewFile(entry, file):
file.write(entry + '\n')
def raiseColumnError(line... |
# coding: utf-8
RESOURCE_MAPPING = {
'statuses_mentions_timeline': {
'resource': 'statuses/mentions_timeline.json',
'docs': 'https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline'
},
'statuses_user_timeline': {
'resource': 'statuses/user_timeline.json',
'docs... |
"""
Unit test script for mongodb 2.0 driver.
This script is designed to be run from engage.tests.test_drivers.
"""
# Id for the resource to be tested.
# An instance with this id must be present
# in the install script.
resource_id = "mongodb"
# The install script should be a json string
# containing a list which inc... |
import base64
import os
import re
from tempfile import NamedTemporaryFile
import urllib2
from cStringIO import StringIO
from django.contrib.auth.models import User
from django_digest.test import Client as DigestClient
from django.test import TestCase
# from django_nose import FastFixtureTestCase as TestCase
from djan... |
import itertools
import numpy as np
import tables
from sapphire.esd import download_data
from delta import DeltaVal, calculate
from testlist import Tijdtest
DATA_PATH = '/Users/arne/Datastore/tijdtest/tijdtest_data_david.h5'
DELTA_PATH = '/Users/arne/Datastore/tijdtest/tijdtest_delta_david.h5'
def test_log_david(... |
from . import utils
from . import gui
from electroncash.i18n import _
from .uikit_bindings import *
from .custom_objc import *
import json, traceback, requests, sys
from electroncash import PACKAGE_VERSION
issue_template = """<font face=arial color="#414141">
<h2>Traceback</h2>
<pre>
{traceback}
</pre>
<h2>Addition... |
from spell.lib.adapter.tc_item import TcItemClass
#*******************************************************************************
# Local imports
#*******************************************************************************
#*******************************************************************************
# System ... |
from abc import ABCMeta, abstractmethod
class AudioPortBuilder(metaclass=ABCMeta):
"""
Extracts the inputs and outputs of an effect defined in a json.
Use it to get the `AudioPorts`_ (inputs and outputs) to build a connection correctly.
.. _AudioPorts: http://lv2plug.in/ns/lv2core/#AudioPort
"""... |
# coding: utf-8
from odoo.tests import common
class TestMenu(common.TransactionCase):
def test_menu_got_duplicated(self):
Menu = self.env['website.menu']
total_menu_items = Menu.search_count([])
self.menu_root = Menu.create({
'name': 'Root',
})
self.menu_chil... |
import copy, logging
from gi.repository import Gtk, Gdk, GLib, Pango
# local files import
from __main__ import misc, data, undo
from . import schedule
# Setup logger object
log = logging.getLogger(__name__)
class ScheduleDialog:
"""Class implements a dialog box for entry of measurement records"""
# General ... |
'''
System tests for `jenkinsapi.jenkins` module.
'''
# To run unittests on python 2.6 please use unittest2 library
try:
import unittest2 as unittest
except ImportError:
import unittest
from jenkinsapi.job import Job
from jenkinsapi.plugin import Plugin
from jenkinsapi.queue import QueueItem
from jenkinsapi_tes... |
# Various tests of models not related to evaluation, fitting, or parameters
import warnings
import pytest
from astropy import units as u
from astropy.tests.helper import assert_quantity_allclose
from astropy.utils.exceptions import AstropyDeprecationWarning
from astropy.modeling.models import Mapping, Pix2Sky_TAN, G... |
'''
PathwayGenie (c) GeneGenie Bioinformatics Ltd. 2018
PathwayGenie is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=attribute-defined-outside-init
# pylint: disable=no-self-use
import json
import os
import ... |
import logging
import os.path
from uuid import uuid1
from google.appengine.ext.webapp import template
import webapp2
from webapp2_extras import auth
from webapp2_extras import sessions
from webapp2_extras.auth import InvalidAuthIdError
from webapp2_extras.auth import InvalidPasswordError
def user_required(handler):
... |
#!/usr/bin/env python
import cx_Oracle
import time
from collectors.lib import utils
from collectors.lib.collectorbase import CollectorBase
# you can add your sql to get metrics .
# try to use [ | ] to cut the string.
# in this case the first and second is metrics name and val . after all is tags
class Oracle(Collec... |
import logging
import re
from streamlink import NoStreamsError
from streamlink.plugin import Plugin, PluginError, pluginmatcher
from streamlink.plugin.api import StreamMapper, validate
from streamlink.stream import HDSStream, HLSStream, RTMPStream
from streamlink.utils import rtmpparse
log = logging.getLogger(__name_... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui\dialog_help.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUt... |
import os
import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext
# Pisi Modules
import pisi.context as ctx
# ActionsAPI Modules
import pisi.actionsapi
import pisi.actionsapi.get as get
from pisi.actionsapi.shelltools import system
from pisi.actionsapi.shelltools import can_access_fi... |
from __future__ import print_function, division, absolute_import
from os.path import join
import rasterio
import numpy
from . import settings
from .decorators import rasterio_decorator
from .image import BaseProcess
class NDVI(BaseProcess):
def __init__(self, path, bands=None, **kwargs):
bands = [4, 5... |
#!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE, call
import filecmp
import glob
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--mpi_exec', dest='mpi_exec', default='')
parser.add_option('--mpi_np', dest='mpi_np', default='3')
parser.add_option('--exe', dest='... |
import netaddr
from neutron.openstack.common import log as logging
from quark.db import api as db_api
from quark import exceptions as quark_exceptions
from quark import plugin_views as v
LOG = logging.getLogger(__name__)
def _to_mac_range(val):
cidr_parts = val.split("/")
prefix = cidr_parts[0]
#FIXME(... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class EdiskCz(SimpleHoster):
__name__ = "EdiskCz"
__type__ = "hoster"
__version__ = "0.22"
__pattern__ = r'http://(?:www\.)?edisk\.(cz|sk|eu)/(stahni|sk/stahni|en/download)/.*'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import getopt
import sys
import re
from Cerebrum import Errors
from Cerebrum.Utils import Factory
from Cerebrum.modules.dns import HostInfo
from Cerebrum.modules.dns import DnsOwner
logger = Factory.get_logger("cronjob")
db = Factory.get('Database')()
db.cl_init(change_p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygraphviz as pgv
import wx
class GraphImgPanel(wx.Panel):
def __init__(self, parent, size):
wx.Panel.__init__(self, parent = parent, size = size)
self.size = size
rootSizer = wx.BoxSizer(wx.HORIZONTAL)
verticalSizer = wx.BoxSiz... |
import types
import importlib
import logging
from .base import BaseConverter
logger = logging.getLogger("booktype.convert")
def find_all(module_names=None):
if module_names is None:
module_names = ("booktype.convert.converters", )
registry = {}
for module_name in module_names:
try:
... |
"""\
usage: ttx [options] inputfile1 [... inputfileN]
TTX %s -- From OpenType To XML And Back
If an input file is a TrueType or OpenType font file, it will be
dumped to an TTX file (an XML-based text format).
If an input file is a TTX file, it will be compiled to a TrueType
or OpenType font ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
name='oftroute',
version='0.0.1',
description='OpenFlow traceroute',
long_description=longdesc,
author='Atzm WAT... |
import re,cPickle,sys
from xlrd import open_workbook
from rjv.misc import string2number
def get_all_data(fname,sheet='Sheet1',conv2numb=False):
'''
return all data as a list of lists
'''
wb = open_workbook(fname)
sh = wb.sheet_by_name(sheet)
nrows = sh.nrows
ncols = sh.ncols
d... |
import sys
import os.path
import gobject
from rgain import rgio
from rgain.script import ou, un, Error, common_options
# calculate the gain for the given files
def calculate_gain(files, ref_level):
# this has to be done here since Gstreamer hooks into the command line
# arguments if it's imported on module ... |
from dbaas_zabbix.database_providers import DatabaseZabbixProvider
class Host(object):
def __init__(self, address, dns):
self.address = address
self.hostname = dns
class Engine(object):
def __init__(self, name, version='0.0.0'):
self.engine_type = EngineType(name)
self.versio... |
import logging
from pathlib import Path
from types import FunctionType
from unittest.mock import MagicMock, call, patch
import numpy as np
import pytest
from Elevator import DIM_NAMES_GEO
from calculators import CALCULATORS, ChunkCalculator, derived, wind_dir, wind_dir_10, HeightType
from utils import DIM_BOTTOM_TOP
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import mock
import uuid
import collections
import pytest
import processors.base.helpers as helpers
class TestValidateIdentifier(object):
@py... |
'''
Created on Mar 18, 2017
@author: Luca Fontanili
'''
import sys
import queue
import copy
rows = ['1','2','3','4','5','6','7','8','9']
cols = ['A','B','C','D','E','F','G','H','I']
default = ['1','2','3','4','5','6','7','8','9']
def create_board(arg):
board = dict()
count = 0
for c in cols:
for... |
"""Parent client for calling the Cloud Spanner API.
This is the base from which all interactions with the API occur.
In the hierarchy of API concepts
* a :class:`~google.cloud.spanner.client.Client` owns an
:class:`~google.cloud.spanner.instance.Instance`
* a :class:`~google.cloud.spanner.instance.Instance` owns a... |
import common as c
from config import ssl_dir, os_name
import sys
import xml.etree.ElementTree as ET
c.print('>> Downloading ssl for Qt for {}'.format(os_name))
if os_name == 'linux':
os_url = 'linux_x64'
tool_name = 'tools_openssl_x64'
root_path = 'Tools/OpenSSL/binary'
elif os_name == 'win32':
os_ur... |
"""Guess the MIME type of a file.
This module defines two useful functions:
guess_type(url, strict=1) -- guess the MIME type and encoding of a URL.
guess_extension(type, strict=1) -- guess the extension for a given MIME type.
It also contains the following, for tuning the behavior:
Data:
knownfiles -- list of fil... |
from rdmo.core.renderers import BaseXMLRenderer
from rdmo.core.utils import get_languages
class XMLRenderer(BaseXMLRenderer):
def render_document(self, xml, views):
xml.startElement('rdmo', {
'xmlns:dc': 'http://purl.org/dc/elements/1.1/'
})
for view in views:
self... |
import os
import sys
import gzip
from appenv import env, log
from errors import NotFoundError
from simpledb import simpledb
class cls_valcabuary(list):
def __init__(self):
self.extend(simpledb.get_valcabuary())
log.info('imported %d words from simpledb to valcabuary' % len(self))
def hit(self,... |
"""
Handles relaying between networks.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = "%%VERSION%%"
__author__ = supybot.authors.jemfinch
# This is a di... |
from bcc import BPF, USDT
import argparse
import re
import subprocess
examples = """examples:
dbslower postgres # trace PostgreSQL queries slower than 1ms
dbslower postgres -p 188 322 # trace specific PostgreSQL processes
dbslower mysql -p 480 -m 30 # trace MySQL queries slower than 30ms
db... |
""" import the necessary modules """
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text
# Create a class that will give us an object that we can use to connect to a database
class MySQLConnection(object):
def __init__(self, app, db):
config = {
'host': 'localhost',
... |
# coding: utf-8
"""
Kinow API
Client API for Kinow back-office
OpenAPI spec version: 1.3.32
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kinow_client
from kinow_clie... |
from document import Document
from op import Op
import unittest
class TestSimpleNodeOperations(unittest.TestCase):
def setUp(self):
self.doc0 = Document()
self.doc1 = Document()
self.doc1.snapshot = {'first': 'some string',
'second': {'third':'more string',
... |
import os
import re
import subprocess as sp
import sys
from paver.easy import task, needs, path, sh
from paver.setuputils import setup
import conda_helpers as ch
import path_helpers as ph
import platformio_helpers as pioh
import versioneer
DEFAULT_ARDUINO_BOARDS = ['mega2560']
setup(name='dmf-control-board-firmwar... |
#!/usr/bin/env python
import logging
import sys
import glob, os
import importlib
import pdb
import numpy
from blocks.monitoring.evaluators import DatasetEvaluator
from blocks.model import Model
import cPickle
import matplotlib.colors as colors
import data
import plotly
import plotly.plotly as py
import plotly.grap... |
"""
Request Body validating middleware.
"""
import functools
import re
from nova.api.openstack import api_version_request as api_version
from nova.api.validation import validators
from nova import exception
from nova.i18n import _
def _schema_validation_helper(schema, target, min_version, max_version,
... |
from openerp.osv import orm, fields
from openerp import netsvc
from openerp.tools.translate import _
from openerp.addons.decimal_precision import decimal_precision as dp
from openerp.addons.account_banking.parsers.models import (
mem_bank_transaction as bt
)
class banking_import_transaction(orm.Model):
_inher... |
from collections import namedtuple
from database import Database
from local_repositories.tasks import datetime_utils
TASKS_DB_COLLECTION = 'tasks'
DEFAULT_EXECUTION_TIME = '00:00:00'
STATUS = namedtuple('Status', ['active', 'inactive'])('active', 'inactive')
TASK = namedtuple('DictKeys', ['name', 'status', 'execution... |
import os
from ._shared import *
class Historique(Rule):
"""Handles history"""
def __init__(self, bot, config, basepath):
self.config = config
self.bot = bot
self.basepath = basepath
self.history = self.read()
def __call__(self, serv, author, args):
"""Handles his... |
"""
Unittests.
"""
import base64
import json
import os
import mock
from contextlib import nested
from requests_kerberos import HTTPKerberosAuth
from . import TestCase, unittest
from reclient import connectors
HTTP_AUTH = ('name', 'password')
PARAMS = {
'baseurl': 'http://127.0.0.1/',
'auth': HTTP_AUTH,
}
... |
"""Simple script to convert CSV output from rf_benchmark to Markdown format.
The input CSV should have the following fields:
- CNN
- input resolution
- end_point
- FLOPS (Billion)
- RF size hor
- RF size ver
- effective stride hor
- effective stride ver
- effective padding hor
- effective padding ver
Since usually in... |
"""The tests for Home Assistant frontend."""
# pylint: disable=protected-access,too-many-public-methods
import re
import time
import unittest
import requests
import homeassistant.bootstrap as bootstrap
from homeassistant.components import frontend, http
from homeassistant.const import HTTP_HEADER_HA_AUTH
from tests.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**windows_setup.py**
**Platform:**
Windows.
**Description:**
Defines the pyinstaller configuration file.
**Others:**
"""
# from __future__ import unicode_literals
import os
__author__ = "Thomas Mansencal"
__copyright__ = "Copyright (... |
# Village People, 2017
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
from .agent import ReportingAgent
from models import get_model
from utils.torch_types import TorchTypes
from collections import namedtuple
import time
# from termcolor import c... |
import json
import uuid
from openstackclient.tests.functional.network.v2 import common
class NetworkSegmentRangeTests(common.NetworkTests):
"""Functional tests for network segment range"""
def setUp(self):
super(NetworkSegmentRangeTests, self).setUp()
# Nothing in this class works with Nova ... |
import os
import re
from invenio.config import CFG_SITE_NAME, \
CFG_SITE_URL, \
CFG_SITE_SUPPORT_EMAIL
from invenio.access_control_admin import acc_get_role_users,acc_get_role_id
from invenio.websubmit_config import CFG_WEBSUBMIT_COPY_MAILS_TO_ADMIN
from invenio.mailutils import send_email
def Send_Request_... |
__all__ = ['Javascript']
from weboob.tools.log import getLogger
class Javascript(object):
HEADER = """
function btoa(str) {
var buffer;
if (str instanceof Buffer) {
buffer = str;
} else {
buffer = new Buffer(str.toString(), 'binary');
}
retur... |
import rospy
import os
import sys
import threading
from roslib.packages import get_pkg_dir
from python_qt_binding.QtGui import *
from python_qt_binding.QtCore import *
from python_qt_binding import loadUi
from airbus_cobot_gui.res import R
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus
from airbus_py... |
import bottle_helpers as bh
from werkzeug.security import generate_password_hash
class ConfigAPI(object):
def __init__(self, api, config):
self.api = api
self.config = config
#self.validator = validator
api.add_route('config', {
'getall': {
'fn': self.getall
},
'get': {
'fn': self.get,
'i... |
import json
class SdsStreamPropertyOverride(object):
"""Sds Stream PropertyOverride definitions"""
@property
def SdsTypePropertyId(self):
return self.__sdsTypePropertyId
@SdsTypePropertyId.setter
def SdsTypePropertyId(self, sdsTypePropertyId):
self.__sdsTypePropertyId = sdsTypeProp... |
import os
import shutil
import unittest
import subprocess
import shlex
def run_cmd(app, cmd):
"""Run a command and return a tuple with (stdout, stderr, exit_code)"""
os.environ['FLASK_APP'] = app
process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=sub... |
"""Test the avoid_reuse and setwalletflag features."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_approx,
assert_equal,
assert_raises_rpc_error,
)
def reset_balance(node, discardaddr):
'''Throw away all owned coins by the node so it gets a b... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_text
from django.contrib.auth.models import User
from django.templatetags.static import static
from django.template.... |
"""jeu URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... |
_super = super
def super(type, self):
if issubclass(type, object):
return _super(type, self)
class proxy(object):
def __init__(self, type, obj):
object.__setattr__(self, '__type__', type)
object.__setattr__(self, '__obj__', obj)
def __getattribute__(self, name):
... |
#!/usr/bin/env python
from saml2 import BINDING_HTTP_REDIRECT
__author__ = 'rolandh'
from idpproxy import exception_log
from idpproxy import bad_request
from urlparse import parse_qs
from saml2.httputil import Response, NotFound, ServiceError, unpack_redirect
import logging
logger = logging.getLogger(__name__)
# =... |
#!/usr/bin/env python
import os
import sys
from setuptools import setup
os.system('make rst')
try:
readme = open('README.rst').read()
except FileNotFoundError:
readme = ""
setup(
name='leicaautomator',
version='0.0.2',
description='Automate scans on Leica SPX microscopes',
long_description=r... |
def zigzag(numbers):
"""actually one array would be enought to solve it"""
if not numbers:
return 0
numbers = list(numbers)
up = [numbers[0]]
down = [numbers[0]]
up_len = 1
down_len = 1
for i in range(1, len(numbers)):
if up_len % 2:
if numbers[i] > up[-1]:
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: /data
url(r'^data/?$', views.data, name='data'),
# ex: /jobs
url(r'^jobs/?$', views.jobs, name='jobs'),
# ex: /addjob
url(r'^addjob/?$', views.addjob, name='addjob'),
#... |
from opensextant.TaxCat import TaxCatalogBuilder, Taxon
def create_entity(name):
"""
Create a generic person name taxon, rather than a particular personality/celebrity
"""
taxon = Taxon()
n = name.strip().lower()
taxon.name = 'person_name.{}'.format(n)
taxon.phrase = n
taxon.is_valid =... |
"""Module tests."""
from __future__ import absolute_import, print_function
import socket
import pytest
from flask import Flask
from invenio_db import db
from invenio_oaiserver import InvenioOAIServer, current_oaiserver
def test_version():
"""Test version import."""
from invenio_oaiserver import __version_... |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import unittest
import commands
import common as cm
import agents as ag
import utils as ut
from fpdtest import FPDTest
TEST_TIMEOUT = 10
user_path = os.path.expanduser
class Test(FPDTest):
def setUp(self):
self.... |
# coding=utf-8
from __future__ import unicode_literals, print_function
from datetime import datetime
from celery import group
from urlobject import URLObject
from webhookdb import db, celery
from webhookdb.process import process_label
from webhookdb.models import IssueLabel, Repository, Mutex
from webhookdb.exceptions... |
"""Optimization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def learning_rate_factor(name, step_num, hparams):
"""Compute the designated learning rate factor from hparams."""
if name == "constant":
... |
from __future__ import print_function
import sys
import doctest
from unittest import TestCase
from zipline.lib import adjustment
from zipline.modelling import (
engine,
expression,
)
from zipline.utils import (
memoize,
test_utils,
)
class DoctestTestCase(TestCase):
@classmethod
def setUpCla... |
import requests, json, time, currency, exchange, pools
class Miner:
def cost(alg):
#returns lowest cost of alg in H/s/BTC/Day
pass
def order(alg, cost):
#opens a new order with alg algorithm costing cost btc
pass
def getOrders():
#returns dictionary of order dictionarys
pass
def getOrder(alg):
#re... |
from nose.tools import * # flake8: noqa
import functools
from framework.auth.core import Auth
from api.base.settings.defaults import API_BASE
from tests.base import ApiTestCase
from tests.factories import (
ProjectFactory,
AuthUserFactory,
RegistrationFactory
)
class TestRegistrationEmbeds(ApiTestCase):... |
"""
URLConf for Django user profile management.
Recommended usage is to use a call to ``include()`` in your project's
root URLConf to include this URLConf for any URL beginning with
'/profiles/'.
If the default behavior of the profile views is acceptable to you,
simply use a line like this in your root URLConf to set... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import re
from babelfish import Language, language_converters, LanguageReverseConverter
from guessit import guessit
from requests import Session
from subliminal import __short_version__
from subliminal.cache import region, SHOW_EXPIRATION_... |
from ..core import *
import ctypes
# Linear solvers
# ==============
# Linear solve
# ------------
lib.ElLinearSolve_s.argtypes = \
lib.ElLinearSolve_d.argtypes = \
lib.ElLinearSolve_c.argtypes = \
lib.ElLinearSolve_z.argtypes = \
lib.ElLinearSolveDist_s.argtypes = \
lib.ElLinearSolveDist_d.argtypes = \
lib.ElLinearS... |
#!/usr/bin/env python
"""
Generated Mon Feb 9 19:08:05 2009 by generateDS.py.
"""
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from . import indexsuper as supermod
class DoxygenTypeSub(supermod.DoxygenType):
node_type = "doxygen"
def __init__(self, version=None, compound=None):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.