content stringlengths 4 20k |
|---|
from questionnaire.models import *
from searchengine.models import *
from django.shortcuts import render_to_response, get_object_or_404
import sys
id_questionnaire = 1
qu = get_object_or_404(Questionnaire, id=id_questionnaire)
def get_number_of_h(number):
return str(number.count('.'))
qsets = qu.questionsets()
fo... |
import datetime
import os
import cloudstorage
from google.appengine.ext import webapp
from mcfw.properties import azzert
from rogerthat.bizz import gcs
from rogerthat.consts import ROGERTHAT_ATTACHMENTS_BUCKET
from rogerthat.rpc.users import get_current_user
from rogerthat.templates import render
from rogerthat.trans... |
import os
import unittest
from avocado.core import exit_codes
from avocado.utils import process
basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')
basedir = os.path.abspath(basedir)
class StandaloneTests(unittest.TestCase):
def setUp(self):
self.original_pypath = os.environ... |
"""
Load test for operations involving side inputs.
The purpose of this test is to measure the cost of materialization and
accessing side inputs. The test uses synthetic source which can be
parametrized to generate records with various sizes of keys and values,
impose delays in the pipeline and simulate other performa... |
"""
tests.constants
===============
Constants for testing.
.. moduleauthor:: mulhern <<EMAIL>>
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import pyudev
import pyblk
CONTEXT = pyudev.Conte... |
from concurrent.futures.thread import ThreadPoolExecutor
from typing import Union, Optional, Set
from google.cloud.pubsub_v1.subscriber.futures import StreamingPullFuture
from google.cloud.pubsublite.cloudpubsub.internal.client_multiplexer import (
ClientMultiplexer,
)
from google.cloud.pubsublite.cloudpubsub.int... |
from spack import *
class Cpuinfo(CMakePackage):
"""cpuinfo is a library to detect essential
for performance optimization information about host CPU."""
homepage = "https://github.com/Maratyszcza/cpuinfo/"
git = "https://github.com/Maratyszcza/cpuinfo.git"
version('master') |
def _getdefaultlocale():
return __BRYTHON__.language,None
def localeconv():
""" localeconv() -> dict.
Returns numeric and monetary locale-specific parameters.
"""
# 'C' locale default values
return {'grouping': [127],
'currency_symbol': '',
... |
"""Code to handle the Plenticore API."""
from __future__ import annotations
import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
import logging
from aiohttp.client_exceptions import ClientError
from kostal.plenticore import PlenticoreApiClient, PlenticoreAuthenticationException
... |
"""Tests for betterwalk.walk(), copied from CPython's tests for os.walk."""
import os
import unittest
import betterwalk
class WalkTests(unittest.TestCase):
testfn = os.path.join(os.path.dirname(__file__), 'temp')
def test_traversal(self):
# Build:
# TESTFN/
# TEST1/ ... |
# -*- coding: UTF-8 -*-
"""
Copyright (C) 2015 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.
... |
from collections import OrderedDict
from typing import Dict, Type
from .base import TenantServiceTransport
from .grpc import TenantServiceGrpcTransport
from .grpc_asyncio import TenantServiceGrpcAsyncIOTransport
# Compile a registry of transports.
_transport_registry = OrderedDict() # type: Dict[str, Type[TenantSer... |
#!/usr/bin/env python3
"""
* Copyright (c) 2015 BEEVC - Electronic Systems This file is part of BEESOFT
* 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... |
# -*- coding: utf-8 -*-
import os
import pytest
from PIL import Image
from danube_delta.cli import photos
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixtures')
def test_find_images_handles_usual_types_of_images():
path = os.path.join(FIXTURES_DIR, 'photos')
basenames = frozenset([
os... |
from optparse import make_option
import django
from django.core.handlers.wsgi import WSGIHandler
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp import AdminMediaHandler
def null_technical_500_response(request, exc_type, exc_value, tb):
raise exc_type, exc_val... |
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # ty... |
pcbnew = __import__('pcbnew')
from kicad.pcbnew import layer as pcbnew_layer
from kicad.point import Point
from kicad import units
class Track(object):
def __init__(self, width, start, end, layer='F.Cu', board=None):
self._track = pcbnew.TRACK(board and board.native_obj)
self._track.SetWidth(int(w... |
from __future__ import unicode_literals, absolute_import
from django.test import TestCase, RequestFactory, Client
from django.urls import reverse
from django.test import override_settings
from mock import patch
from requests_oauthlib import OAuth2Session
from ci import github, oauth_api
from ci.tests import utils
impor... |
""" This module contains the StringCommandHandler class """
from .handler import Handler
class StringCommandHandler(Handler):
"""
Handler class to handle string commands. Commands are string updates
that start with ``/``.
Args:
command (str): The name of the command this handler should liste... |
#!/usr/bin/env python
# train and predict, based on validation params
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression as LR
from KaggleWord2VecUtility import KaggleWord2VecUtility
#
train_file = 'data/labeledTr... |
import os
from scipy import misc
import numpy as np
SUPPORTED_FORMATS=("png","jpg","PNG","JPG")
IMG_SAVE_PATH = "~/Desktop/ML/results/"
def checkfit(X,Y):
if not isinstance(X,np.ndarray):
X=np.array(X)
if not isinstance(Y,np.ndarray):
Y=np.array(Y)
if len(X)!=len(Y):
raise ValueError("The length of the feature... |
from collections import defaultdict
from chroma_core.services import log_register
log = log_register(__name__)
class ObjectCache(object):
instance = None
def __init__(self):
from chroma_core.models import ManagedFilesystem, ManagedHost, LNetConfiguration, LustreClientMount
from chroma_core.... |
from django.conf.urls import patterns, url
from risk_management import views
urlpatterns = patterns(
'',
url(
regex=r'^assumption_profile$',
view=views.AssumptionProfileAPI.as_view(),
name='assumption_profile_api'
),
url(
regex=r'^create_risk_profile$',
view=v... |
# -*- coding: utf-8 -*-
"""
AllDb
Eksportowanie danych do pliku pdf
"""
from __future__ import with_statement
__author__ = "Karol Będkowski"
__copyright__ = "Copyright (c) Karol Będkowski, 2009-2010"
__version__ = "2010-06-11"
import logging
from cStringIO import StringIO
from alldb.model import objects
from alldb... |
# bokeh_periodic_table.py
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.plotting import figure
from bokeh.sampledata.periodic_table import elements
from bokeh.transform import dodge, factor_cmap
output_file("periodic.html")
periods = ["I", "II", "III", "IV", "... |
"""GCE metadata."""
import requests
import socket
from base import retry
from system import environment
_METADATA_SERVER = 'metadata.google.internal'
_RETRIES = 3
_DELAY = 1
@retry.wrap(
retries=_RETRIES,
delay=_DELAY,
function='python.google_cloud_utils.compute_metadata.get')
def get(path):
"""Get ... |
from decimal import Decimal
from restorm.clients.base import ClientMixin, BaseClient
JSON_LIBRARY_FOUND = True
# Prefer json over simplejson
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
JSON_LIBRARY_FOUND = False
class CustomEncoder(json.JSONEn... |
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Field, MultiField, HTML, Button
from crispy_forms.bootstrap import *
from minimo.movimento.models import *
class RegistraDocumentoForm(forms.ModelForm):
class... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 13:57:54 2016
@author: ajaver
"""
import json
import os
import subprocess as sp
import warnings
from collections import OrderedDict
import numpy as np
import tables
from tierpsy.helper.misc import TimeCounter, print_flush, ReadEnqueue, FFPROBE_CMD
def dict2recarray... |
from pymongo import MongoClient
import tornado.ioloop
import tornado.web
from tornado.options import define, options
from bson.objectid import ObjectId
define('port', default=8888, help='run on the given port', type=int)
client = MongoClient()
db = client.urlist
class MainHandler(tornado.web.RequestHandler):
... |
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import subprocess
import sys
import contextlib
from distutils.command.build_ext import build_ext
from distutils.sysconfig import get_python_inc
from distutils import ccompiler, msvccompiler
from setuptools import Extension, setup, find_pack... |
from marshmallow import fields
from .exceptions import UnsupportedValueError
def handle_length(schema, field, validator, parent_schema):
"""Adds validation logic for ``marshmallow.validate.Length``, setting the
values appropriately for ``fields.List``, ``fields.Nested``, and
``fields.String``.
Args:... |
#Representation of gl.xml files
class Command :
def __init__( self ) :
self.name = "";
self.ret_type = "";
self.params = [];
def fromRepr( self, dict ) :
self.name = dict['name'];
self.ret_type = dict['ret_type'];
params_repr = dict['params'];
for param_repr in params_repr :
param = Param(... |
from pysollib.gamedb import registerGame, GameInfo, GI
from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint
from pysollib.stack import \
InvisibleStack, \
ReserveStack, \
WasteStack, \
WasteTalonStack
# *******************************... |
# -*- coding: utf-8 -*-
# requires packages: psycopg2, requests
import sys
import gc
from psycopg2 import connect
from psycopg2.extras import RealDictCursor
from requests import get
from urllib import urlencode
from urlparse import urlunsplit
from json import loads
from time import sleep
coefficient = {'wait': 1.63... |
from __future__ import absolute_import
from copy import copy
import numpy as nm
from sfepy.base.testing import TestCommon
from sfepy.base.base import ordered_iteritems
from sfepy import data_dir
filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom
for geom in ['1_2', '2_3', '2_4', '3_... |
"""Handle the frontend for Home Assistant."""
import os
from . import version, mdi_version
from homeassistant.components import api
from homeassistant.components.http import HomeAssistantView
DOMAIN = 'frontend'
DEPENDENCIES = ['api']
def setup(hass, config):
"""Setup serving the frontend."""
hass.wsgi.regi... |
#!/usr/bin/env python
# encoding: utf-8
'''
gpttwosample -- GPTwoSample on given Data
gpttwosample is a program to perform GPTwoSample on given treatment and control timeseries.
It defines several different classes to perform GPTwoSample tasks,
including accounting for timeshifts between timeseries,
accounting confoun... |
from oslo_log import log
from vitrage.evaluator.base import CONTENT
from vitrage.evaluator.base import SYNTAX
from voluptuous import Error as VoluptuousError
from vitrage.evaluator.template_fields import TemplateFields
from vitrage.evaluator.template_validation import base
from vitrage.evaluator.template_validation.co... |
# Django settings for paquetin project.
import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2',... |
import sys
tokens = [ 'SYMBOL' ]
literals = ['{','}',';', ':']
t_SYMBOL = r'[a-zA-Z_][a-zA-Z0-9_\.]*'
t_ignore = " \t\n"
def t_error(t):
print "Illegal character '%s'" % t.value[0]
t.lexer.skip(1)
import ply.lex as lex
lex.lex()
namespace = "global"
symbols = []
def p_syms(p):
'syms : SYMBOL "{... |
"""Unit tests for TokenResolver functionality"""
# pylint: disable=invalid-name
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
from tokenresolver import TokenResolver
xbmc = __import__('xbmc')
xbmcaddon = __import__('xbmcaddon')
xbmcgui = __import__('xbmcgui')
xbmc... |
import django
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from gm2m import GM2MField
from cbe.business_interaction.models import BusinessInteraction, BusinessInteractionItem
... |
r'''
Semideterministic Forth. (Call it Eighth?)
A variant of peglet.py (for documentation look there) with these changes:
* There's no seclusion: when parsing a rule, it passes in the
current values stack instead of creating a fresh new empty
one.
* There's no memoization, since we'd have to memoize on th... |
__title__ = "Solver z88 FEM unit tests"
__author__ = "Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
import sys
import unittest
from os import listdir
from os.path import join
from os.path import isfile
import FreeCAD
import femsolver.run
from . import support_utils as testtools
from .support_utils import f... |
from builtins import range
from lino.api import dd, rt
from lino.utils import Cycler
def objects():
Client = rt.models.pcsw.Client
Property = rt.models.properties.Property
PP = rt.models.cv.PersonProperty
PERSONS = Cycler(Client.objects.all())
for prop in Property.objects.order_by('id'):
... |
from __future__ import absolute_import, division, print_function
import click
import os
import yaml
from bag8.exceptions import NoProjectYaml
from bag8.utils import simple_name
CURR_DIR = os.path.realpath('.')
class Yaml(object):
def __init__(self, project):
self.project = project
self._data ... |
"""Module for the FilterHelp cog."""
from typing import Optional
from redbot.core import Config, commands
from redbot.core.bot import Red
from .converters import EnabledState, Hideable, Scope
from .formatter import HideHelpFormatter
UNIQUE_ID = 0x10B231A2
class FilterHelp(commands.Cog):
"""Broaden or narrow th... |
"""This package contains the information classes that extend IEC61970::Wires package with power system resources required for distribution network modelling, including unbalanced networks.
"""
from CIM14.IEC61968.IEC61968CIMVersion import IEC61968CIMVersion
nsURI = "http://iec.ch/TC57/2009/CIM-schema-cim14#IEC61968"
... |
# -*- coding: utf-8 -*-
import os
import datetime
from mandrill_send import mandrill_send, __init_plan_maily, __parse_mailheader
import vfp
maildir, planovany, planovany2 = __init_plan_maily()
def zaslat():
return {}
#@requires_login()
#def zaslat():
form = __get_mailform()
if form.process().accepted:
... |
'''
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
'''
cl... |
import datetime
import tweepy
from geopy.geocoders import Nominatim
import json
from secret import *
import boto3
import re
import preprocessor as p
import time
p.set_options(p.OPT.URL, p.OPT.EMOJI)
# Get the service resource.
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
table = dynamodb.Table('fuck... |
# -*- coding: utf-8 -*-
"""Util functions for different things. For example: format time or bytesize correct."""
from flask import request, Response
from functools import wraps
from jinja2.filters import FILTERS
import os
import maraschino
from maraschino import app, logger
from maraschino.models import Setting, XbmcS... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import app.productdb.validators
import django.core.validators
import annoying.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
from code.utils import parsers
from code.processors.StandardsProcessor import StandardsProcessor
class OneToOneProcessor(StandardsProcessor):
def __init__(self, data):
self.__regex = data["regex"]
self.__text = data["text"]
self.__max ... |
from opserver.plugins.alarm_base import AlarmBase
class ProcessStatus(AlarmBase):
def __call__(self, uve_key, uve_data):
err_list = []
if not uve_data.has_key("NodeStatus"):
err_list.append(("NodeStatus != None","None"))
return self.__class__.__name__, err_list
... |
from __future__ import absolute_import
import mock
import celery.contrib.pytest
import plone.testing
import z3c.celery
class EagerLayer(plone.testing.Layer):
def setUp(self):
# No isolation problem, end to end tests use a separate celery app
# which is provided by EndToEndLayer (below).
z... |
from __future__ import unicode_literals
"""
This is where all the plug-in code is executed. The standard method for DocTypes is declaration of a
standardized `DocType` class that has the methods of any DocType. When an object is instantiated using the
`get_obj` method, it creates an instance of the `DocType` class of ... |
import json
import sys
import activityHandle
'''
This script does a parsing of the JSON file containing the file to be rendered
taking the file name as a commandline argument, the JSON format is detailed in
the model.mdj file under the "JSON Activity" diagram.
This file generates an output of the same name as the ori... |
import os.path
import subprocess
import sys
import textwrap
from contextlib import contextmanager
from pathlib import Path
from string import ascii_lowercase
from _pytest.pytester import Pytester
@contextmanager
def subst_path_windows(filepath: Path):
for c in ascii_lowercase[7:]: # Create a subst drive from H-... |
#!/usr/bin/python
# $Id: SparqlQueryTestCase.py 1461 2010-10-02 15:55:16Z graham $
"""
Module to test simple queries against LGPN sample data
$Rev: 1461 $
"""
import os, os.path
import sys
import re
import unittest
import logging
import httplib
import urllib
try:
# Running Python 2.5 with simple... |
import unittest2
from consts.notification_type import NotificationType
from models.notifications.broadcast import BroadcastNotification
class TestBroadcastNotification(unittest2.TestCase):
def setUp(self):
self.notification = BroadcastNotification('Title Here', 'Some body message ya dig')
def test... |
#!/usr/bin/env python
import TUI.Base.TestDispatcher
telmechTester = TUI.Base.TestDispatcher.TestDispatcher("telmech", delay=1.0)
tuiModel = telmechTester.tuiModel
MainData = (
"device=heaters; h8=off; h24=off; h12=off; h20=off; h16=off; h4=off",
"device=covers; covers=close",
"device=tertrot; tertrot=na2... |
import os
import aiohttp
import shutil
import asyncio
import hashlib
from uuid import UUID, uuid4
from .port_manager import PortManager
from .notification_manager import NotificationManager
from ..config import Config
from ..utils.asyncio import wait_run_in_executor
from ..utils.path import check_path_allowed, get_de... |
"""
Soft rectification layers.
"""
__authors__ = "Jesse Livezey"
import logging
import math
import sys
import warnings
import numpy as np
from theano import config
from theano.compat.python2x import OrderedDict
from theano.gof.op import get_debug_values
from theano.printing import Print
from theano.sandbox.rng_mrg im... |
#!/usr/bin/env python2
import argparse
import re
import sys
from collections import defaultdict
from cfme.utils.log import logger
from cfme.utils.conf import cfme_data
from cfme.utils.conf import credentials
from cfme.utils.ssh import SSHClient
from cfme.utils.providers import list_provider_keys, get_mgmt
def parse... |
"""
Dummy easyblock for OpenMPI
@author: Kenneth Hoste (Ghent University)
"""
from easybuild.framework.easyblock import EasyBlock
class EB_OpenMPI(EasyBlock):
pass |
import os
import sys
import simplejson as json
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError, transaction
from django.contrib.auth.models import User
from annotate.models import *
from annotate.utils import fix_transpose
import pi... |
import logging
import os
from yaml import dump
from twisted.internet.defer import inlineCallbacks, succeed, Deferred
from juju.environment.environment import Environment
from juju.charm.tests.test_repository import RepositoryTestBase
from juju.state.machine import MachineState
from juju.state.service import ServiceU... |
# encoding: utf-8
# module samba.dcerpc.dnsserver
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/dnsserver.so
# by generator 1.135
""" dnsserver DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DNS_RPC_RECORDS_ARRAY(__talloc.Object):
# no doc
def __init__(self, *args, **k... |
import sys
import traceback
import gevent
import gevent._threading # This is a clone of the *real* threading module
from gevent.pywsgi import WSGIHandler, WSGIServer
import greenlet
from gunicorn.workers.ggevent import GeventWorker
import gunicorn.glogging
import inbox.log
from inbox.config import config
log = inbox.l... |
import theano
import theano.tensor as T
class Softmax(object):
def __init__(self):
pass
def __call__(self, x):
e_x = T.exp(x - x.max(axis=1).dimshuffle(0, 'x'))
return e_x / e_x.sum(axis=1).dimshuffle(0, 'x')
class ConvSoftmax(object):
def __init__(self):
pass
def _... |
__author__ = 'nmearl'
import ctypes
import numpy as np
from numpy.ctypeslib import ndpointer
import sys
from multiprocessing import Pool
import os
path = os.path.dirname(os.path.realpath(__file__)).split('/')[:-1]
path = '/'.join(map(str, path))
if sys.platform == 'darwin':
# print("It seems you're on mac, loadi... |
import os
import re
from setuptools import setup
HERE = os.path.dirname(os.path.abspath(__file__))
def get_version():
filename = os.path.join(HERE, 'transfluent.py')
contents = open(filename).read()
pattern = r"^__version__ = '(.*?)'$"
return re.search(pattern, contents, re.MULTILINE).group(1)
se... |
import os
import sys
import rospy
from rospkg.rospack import RosPack
from qt_gui.main import Main as Base
class Main(Base):
def __init__(self, filename=None, ros_pack=None):
rp = ros_pack or RosPack()
qtgui_path = rp.get_path('qt_gui')
super(Main, self).__init__(qtgui_path, invoked_file... |
"""This module contains the Review Follower Model."""
__authors__ = [
'"Lennard de Rijk" <<EMAIL>>',
]
from google.appengine.ext import db
import soc.modules.gsoc.models.follower
class ReviewFollower(soc.modules.gsoc.models.follower.Follower):
"""Details specific to a Review Follower.
"""
#: Required pro... |
import subprocess
import sys
import setup_util
from os.path import expanduser
home = expanduser("~")
def start(args):
setup_util.replace_text("php-silex/web/index_raw.php", "192.168.100.102", "" + args.database_host + "")
setup_util.replace_text("php-silex/deploy/php-silex", "\".*\/FrameworkBenchmarks", "\"" + ho... |
##
## SHARDCACHE.PY
##
###############
import select
import socket
import struct
import random
import sys
import time
from chash import CHash
from siphash import SipHash
MSG_GET = chr(0x01)
MSG_SET = chr(0x02)
MSG_DEL = chr(0x03)
MSG_EVI = chr(0x04)
MSG_OFX = chr(0x06)
MSG_ADD = chr(0x07)
MSG_EXI ... |
"""Tests for membership api"""
import pytest
from channels.factories.models import ChannelFactory, ChannelMembershipConfigFactory
from channels.membership_api import (
update_memberships_for_managed_channels,
update_memberships_for_managed_channel,
)
from open_discussions.factories import UserFactory
from prof... |
"""A test suite that runs all tests for pyfakefs at once.
Includes tests with external pathlib2 and scandir packages if installed."""
import sys
import unittest
from pyfakefs.tests import (
dynamic_patch_test,
fake_stat_time_test,
example_test,
fake_filesystem_glob_test,
fake_filesystem_shutil_tes... |
"""VIF drivers for XenAPI."""
from oslo_config import cfg
from oslo_log import log as logging
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova.virt.xenapi import network_utils
from nova.virt.xenapi import vm_utils
xenapi_ovs_integration_bridge_opt = cfg.StrOpt('ovs_integration_... |
from weboob.capabilities.housing import Query
from weboob.tools.test import BackendTest
__all__ = ['PapTest']
class PapTest(BackendTest):
BACKEND = 'pap'
def test_pap(self):
query = Query()
query.area_min = 20
query.cost_max = 900
query.cities = []
for city in self.b... |
from __future__ import unicode_literals
from guessit.textutils import find_first_level_groups
from guessit.patterns import group_delimiters
import functools
import logging
log = logging.getLogger(__name__)
priority = 245
def process(mtree):
"""split each of those into explicit groups (separated by parentheses o... |
"""RebootSchedule Resource formatter."""
from aquilon.worker.formats.formatters import ObjectFormatter
from aquilon.worker.formats.resource import ResourceFormatter
from aquilon.aqdb.model import RebootSchedule
class RebootScheduleFormatter(ResourceFormatter):
suppress_name = True
def extra_details(self, r... |
"""The matrix bot component."""
import logging
import os
from functools import partial
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.notify import ATTR_TARGET, ATTR_MESSAGE
from homeassistant.const import (
CONF_USERNAME,
CONF_PASSWORD,
CONF_VE... |
import re
from .ch import atone
from .util import DefaultOrderedDict
class Desinence(object):
def __repr__(self):
return "<pycollatinus.modele.Desinence[{};{};{}]>".format(self.gr(), self.morphoNum(), self.numRad())
def __init__(self, d, morph, nr, parent=None):
""" Desinence
:param ... |
import pytest
import os
import utils
from utils import kfp_client_utils
from utils import minio_utils
from utils import sagemaker_utils
@pytest.mark.parametrize(
"test_file_dir", ["resources/config/kmeans-mnist-model"],
)
def test_createmodel(kfp_client, experiment_id, sagemaker_client, test_file_dir):
down... |
import numpy as np
from settingobj import SettingObj
from settingitems import *
__all__ = ['BGSubNop', 'BGSubMinimum', 'BGSubLeftEdge', 'BGSubRightEdge']
class BGSubBase(SettingObj):
def func(self, line, lineF, x):
raise NotImplementedError()
class BGSubNop(BGSubBase):
name = 'nop'
label = 'Do nothi... |
#!/usr/bin/env python
import os,sys,time
import numpy as np
import bitarray
import tables as tb
import logging
import yaml
import matplotlib.pyplot as plt
import monopix_daq.scan_base as scan_base
import monopix_daq.analysis.interpreter as interpreter
local_configuration={"exp_time": 1.0,
"cnt_t... |
'''
Wrapper around urlgrabber adding support for backend progress callbacks
http://linux.duke.edu/projects/urlgrabber/help/urlgrabber.grabber.html
'''
import os
import logging
log = logging.getLogger('downloader')
from urlgrabber.grabber import URLGrabber
import encodings.idna #required by urlgrabber
import encodings... |
'''
Tests of non pattern specific parameter.
The tests for all rules will run these tests separately.
'''
import unittest
import numpy as np
from . import test_connect_helpers as hf
class TestParams(unittest.TestCase):
# Setting default parameter. These parameter might be overwritten
# by the classes
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" setup.py
Packaging for dax
"""
import os
from setuptools import setup, find_packages
def get_version():
basedir = os.path.dirname(__file__)
with open(os.path.join(basedir, 'dax/version.py')) as f:
VERSION = None
exec(f.read())
return ... |
# -*- coding: utf-8 -*-
from odoo import api, fields, models
from odoo.tools.translate import _
class Notification(models.Model):
_name = 'mail.notification'
_table = 'mail_message_res_partner_needaction_rel'
_rec_name = 'res_partner_id'
_log_access = False
_description = 'Message Notifications'
... |
"""Modified version of: http://w.holeso.me/2008/08/a-simple-django-truncate-filter/"""
# Copyright 2010,2011 Good Energy Research Inc. <<EMAIL>>, <<EMAIL>>
#
# This file is part of Good Energy.
#
# Good Energy is free software: you can redistribute it and/or modify
# it under the terms of the GNU A... |
"""
Arduino
Arduino Wiring-based Framework allows writing cross-platform software to
control devices attached to a wide range of Arduino boards to create all
kinds of creative coding, interactive objects, spaces or physical experiences.
http://arduino.cc/en/Reference/HomePage
"""
from os.path import isdir, join
fro... |
import glob
import os
import sys
import ah_bootstrap
from setuptools import setup
#A dirty hack to get around some early import/configurations ambiguities
if sys.version_info[0] >= 3:
import builtins
else:
import __builtin__ as builtins
builtins._ASTROPY_SETUP_ = True
from astropy_helpers.setup_helpers impor... |
"""This illustrates how to get all account budgets for a Google Ads customer."""
import argparse
import sys
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id):
ga_service = client.get_service("GoogleAdsService")
... |
import os
import sys
import tempfile
import shutil
from bento.core.platforms.sysconfig \
import \
get_scheme
from bento.utils.utils \
import \
subst_vars
from bento.installed_package_description \
import \
BuildManifest, iter_files
from bento._config \
import \
BUILD_MAN... |
#!/usr/bin/env python
"""Tests the scriptTree jobTree-script compiler.
"""
import unittest
import sys
import os
import random
from sonLib.bioio import TestStatus
from sonLib.bioio import parseSuiteTestOptions
from sonLib.bioio import system
from sonLib.bioio import getTempDirectory
from sonLib.bioio import getTempFil... |
"""Code for loading data."""
# pylint: disable=g-bad-todo
# pylint: disable=g-importing-member
# example comment
import os
import random
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import flags
from utils import get_images
FLAGS = flags.FLAGS
class DataGenerator(object):
"""Data Gen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.