content stringlengths 4 20k |
|---|
from collections import OrderedDict
from distutils import util
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions # type: ignore
from google.api_core import gapic_v1... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 15:11:58 2015
@author: Sergey
"""
import logging
import os
import shutil
import sys
import time
import winsound
from PyQt5 import QtCore, QtGui, uic
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog
from keithley6487 import Keithley6487... |
import unittest
import json
import mock
from tempodb.protocol.cursor import Cursor, DataPointCursor, SeriesCursor
class DummyType(object):
def __init__(self, data, response, tz=None):
self.data = data
self.response = response
self.tz = tz
class Dummy(object):
pass
class DummyRespon... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv, codecs, cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 09:20:41 2020
@author: wantysal
"""
# Standard imports
import numpy as np
import pytest
# Local application imports
from mosqito.functions.shared.load import load
from mosqito.functions.sharpness.comp_sharpness import comp_sharpness
@pytest.mark.sharpness_din # to... |
from __future__ import unicode_literals
import collections
import datetime
import json
import platform
import types
import unittest
from decimal import Decimal
import rows
from rows import fields
if platform.system() == 'Windows':
locale_name = str('ptb_bra')
else:
locale_name = 'pt_BR.UTF-8'
class Fields... |
import json
from kfp.dsl import ResourceOp
class CreateJobOp(ResourceOp):
"""Represents an Op which will be translated into a Databricks Job creation
resource template.
Example:
import databricks
databricks.CreateJobOp(
name="createjob",
job_name="test-job",
... |
"""Tests the conda forge activity."""
import os
import builtins
import pytest
from rever import vcsutils
from rever.logger import current_logger
from rever.main import env_main
from rever.activities.forge import get_feedstock_url
from rever.activities.forge import get_feedstock_repo_name
from rever.activities.forge i... |
import requests
from unittest import TestCase
from nose.tools import assert_raises
from datetime import datetime, date
from cartodb_services.tools.qps import qps_retry
from cartodb_services.tools.exceptions import (ServiceException,
TimeoutException)
import requests_mock
i... |
from pprint import pprint as pp
class TestSyncStatus(object):
def test_get_status(self, request, bigip):
sync_status = bigip.cm.sync_status
pp(sync_status.raw)
assert sync_status._meta_data['uri'].endswith(
u"/mgmt/tm/cm/sync-status")
sync_status.refresh()
des =... |
import unittest
import image
from config import *
class TestImage(unittest.TestCase):
def setUp(self):
self.im = image.loadImage('test\\resource\\test.png')
self.t = image.loadImage('test\\resource\\i.png')
pass
def tearDown(self):
image.releaseAllWindows()
def test_loadin... |
import abc
import os
import qisys.sh
class DocProject(object):
__metaclass__ = abc.ABCMeta
doc_type = None
def __init__(self, doc_worktree, project, name, depends=None, dest=None):
self.doc_worktree = doc_worktree
self.name = name
self.src = project.src
self.path = projec... |
from __future__ import print_function, unicode_literals
import weblab.experiment.experiment as Experiment
import weblab.experiment.devices.gpib.gpib as Gpib
from voodoo.gen.caller_checker import caller_check
import weblab.experiment.util as ExperimentUtil
import weblab.experiment.exc as ExperimentErrors
impor... |
from bambou import NURESTFetcher
class NUBulkStatisticsFetcher(NURESTFetcher):
""" Represents a NUBulkStatistics fetcher
Notes:
This fetcher enables to fetch NUBulkStatistics objects.
See:
bambou.NURESTFetcher
"""
@classmethod
def managed_class(cls):
... |
import atexit
import os
import tempfile
from mkt.settings import ROOT
_tmpdirs = set()
def _cleanup():
try:
import sys
import shutil
except ImportError:
return
tmp = None
try:
for tmp in _tmpdirs:
shutil.rmtree(tmp)
except Exception, exc:
sys.... |
from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as... |
import rospy
import thread
import threading
import time
import mavros
from math import *
from mavros.utils import *
from mavros import setpoint as SP
from tf.transformations import quaternion_from_euler
class SetpointPosition:
"""
This class sends position targets to FCU's position controller
"""
def... |
import unittest
"""
Given an array of distinct integers, find the length of the longest subarray which contains
numbers that can be arranged in a contiguous sequence.
Input: 10 12 11
Output: 3
Input: 14 12 11 20
Output: 2
Input: 1 56 58 57 90 92 94 93 91 45
Output: 5
"""
"""
Approach:
1. Since all elements are distinc... |
#!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
##################################################################
# Documentation
##################################################################
# Imports
from __future__ import absolute_import, unicode_literals, print_function
from keras.models import... |
# Tests that require installed backends go into
# diofant/test_external/test_autowrap
import io
import os
import shutil
import tempfile
import pytest
from diofant import Eq
from diofant.abc import x, y, z
from diofant.utilities.autowrap import (CodeWrapper, CythonCodeWrapper,
... |
__author__ = 'Mark'
from scipy import stats
def combine_majority_vote(predictions):
majority_vote_predictions = (stats.mode(predictions[:, :, 0])[0])[0]
return majority_vote_predictions.astype(int)
def combine_minimum_rule(predictions):
total_testing_samples = predictions.shape[1]
all_minimum_distan... |
"""
=========================
PLS Partial Least Squares
=========================
Simple usage of various PLS flavor:
- PLSCanonical
- PLSRegression, with multivariate response, a.k.a. PLS2
- PLSRegression, with univariate response, a.k.a. PLS1
- CCA
Given 2 multivariate covarying two-dimensional datasets, X, and Y,
... |
"""Start and stop tsproxy."""
from __future__ import absolute_import
import logging
import os
import re
import signal
import subprocess
import sys
import time
try:
import fcntl
except ImportError:
fcntl = None
import py_utils
from py_utils import retry_util
from py_utils import atexit_with_log
_TSPROXY_PATH = o... |
from django.conf import settings
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from djequis.core.schoology.sql import SELECT_GRADE, UPDATE_GRADE
from djzbar.utils.informix import get_session
import json
import logging
logger = logging.ge... |
"""
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... |
import ppaquette_gym_doom
from collections import deque
import ppaquette_gym_doom.wrappers
import numpy.random as npr
import numpy as np
import random
import gym
from gym import wrappers
import prettytensor as pt
import tensorflow as tf
import cv2
# screen resolution
X, Y = 320, 240
XY = X * Y
# crop a smaller region... |
import parser
def do_test(inv, outv):
try:
tree = parser.parse(inv)
actual_output = tree.excel()
except Exception as e:
print("ERROR")
print(e)
else:
if actual_output != outv:
print(u"FAIL {:>30} \u2192 {:30}".format(inv, actual_output))
print... |
# -*- encoding: utf-8 -*-
"""Test class for CLI Foreman Discovery"""
from robottelo.decorators import stubbed
from robottelo.test import CLITestCase
class DiscoveryTestCase(CLITestCase):
"""Implements Foreman discovery CLI tests."""
@stubbed()
def test_positive_discovered_host_facts(self):
"""@Te... |
import abc
import eventlet
import Queue
import six
import time
from st2actions.container.service import RunnerContainerService
from st2actions.runners import get_runner
from st2common import log as logging
from st2common.constants.action import (LIVEACTION_STATUS_FAILED,
LIVEACT... |
# -*- coding: utf-8 -*-
import os.path
import unittest
from odoo.tests.common import tagged
from odoo.tools.mimetypes import guess_mimetype
def contents(extension):
with open(os.path.join(
os.path.dirname(__file__),
'testfiles',
'case.{}'.format(extension)
), 'rb') as f:
return... |
# -*- coding: utf-8 -*-
import numpy as np
from nose.tools import (
assert_almost_equal,
assert_warns_regex,
assert_raises_regex,
)
from .. import Surface
def test_surface():
volume = np.random.uniform(10, 100)
tau = np.random.uniform(.5, 5.)
x = [tau, 0, 0]
sigma = [volume/tau, 0, 0]
... |
#!/usr/bin/env python3
from pgmpy.extern.six.moves import filter, reduce
from pgmpy.factors.base import BaseFactor
from pgmpy.extern import six
class FactorSet(object):
r"""
Base class of *DiscreteFactor Sets*.
A factor set provides a compact representation of higher dimensional factor
:math:`\phi_... |
import numpy as np
import scipy.spatial.distance
from matplotlib import pyplot as plt
def get_precision_at_recall_at_matrices(distance_matrix,labels,self_distance=True,nicest=True,remove_singleton_queries=True):
"""
:param distance_matrix: A float matrix expected to have the distances between samples. Order... |
"""Stuff that differs in different Python versions and platform
distributions."""
# flake8: noqa
import os
import imp
import sys
import site
__all__ = ['WindowsError']
uses_pycache = hasattr(imp, 'cache_from_source')
class NeverUsedException(Exception):
"""this exception should never be raised"""
try:
Wi... |
"""
Hypothesis strategies for eliot.
"""
from __future__ import unicode_literals
from functools import partial
from six import text_type as unicode
from hypothesis.strategies import (
builds,
dictionaries,
fixed_dictionaries,
floats,
integers,
lists,
just,
none,
one_of,
recurs... |
"""version 1.5.0
Revision ID: f75b4068af0a
Revises: 430a70c8aa21
Create Date: 2017-07-05 14:34:45.988817
"""
# revision identifiers, used by Alembic.
revision = 'f75b4068af0a'
down_revision = 'eb7141efd75a'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialect... |
import numpy as np
from learning_functions import hypothesis
#################
# Error functions
#################
def measure_error(V, index, kernel_times, delay_indexes, image_indexes, input_to_image, kernel_to_input, h0, h1, h2, ims, ims2):
'''
Gives the difference between the value and the prediction
... |
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License");... |
# -*- coding: utf-8 -*-
import codecs
import csv
import sys
from opinions.models import QuestionSource, Question, Option, Answer
from votes.models import Member
from . import http_cache
from . import parse_tools
CSV_URL = 'http://www.kansanmuisti.fi/storage/vaalikone/mtv2007/Eduskuntavaalikonedata_2007.csv'
OPTION_S... |
""" DIRAC Workload Management System utility module to get available memory and processors from mjf
"""
import os
import urllib2
__RCSID__ = "$Id$"
def getJobFeatures():
features = {}
if 'JOBFEATURES' not in os.environ:
return features
for item in ( 'allocated_cpu', 'hs06_job', 'shutdowntime_job', 'grace_s... |
import argparse
import functools
import json
import logging
import math
import os
import jinja2
from tabulate import tabulate
import yaml
from rally_runners.reliability import analytics
from rally_runners.reliability import graphics
from rally_runners import utils
REPORT_TEMPLATE = 'rally_runners/reliability/templat... |
from cStringIO import StringIO
import numpy as np
import scipy.ndimage as nd
import PIL.Image
from IPython.display import clear_output, Image, display
from google.protobuf import text_format
import caffe
# list of image names to merge, with first name the base, and second name the target
painting_list = [('leonardo_d... |
import re
import copy
class CSS(object):
ESCAPE_RE = r'\\[^0-9a-fA-F]|\\[0-9a-fA-F]'
ATTR_RE = r"""
\[
((?:%s|[\w\-])+)
(?:
(\W)?
=
(?:"((?:\\"|[^"])*)"|([^\]]+))
)?
\]""" % ESCAPE_RE
CLASS_ID_RE = r"""
(?:
(... |
import re
import os
import sys
from inspect import ismethod
from time import sleep
from OSEncryptionState import *
class EncryptBlockDeviceState(OSEncryptionState):
def __init__(self, context):
super(EncryptBlockDeviceState, self).__init__('EncryptBlockDeviceState', context)
def should_enter(self):
... |
"""
PythonDBAGraphs: Graphs to help with Oracle Database Tuning
Copyright (C) 2016 Robert Taft Durrett (Bobby Durrett)
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... |
# coding: utf-8
from __future__ import division, print_function
import os
# Third-party
import numpy as np
from astropy.utils.data import get_pkg_data_filename
from astropy.constants import G
import gala.potential as gp
from gala.units import galactic
_G = G.decompose(galactic).value
# Project
from ..core import c... |
# -*- coding: utf-8 -*-
"""
mediatum - a multimedia content repository
Copyright (C) 2013 Tobias Stenzel <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the Licens... |
from django.urls import reverse, resolve
from test_plus.test import TestCase
from turnos.tests.factories import TurnoFactory
class TestUserURLs(TestCase):
"""Test URL patterns for turnos app."""
def setUp(self):
self.user = self.make_user()
self.turno = TurnoFactory()
def test_list(sel... |
__all__ = []
import matplotlib.cm as mcm
from functools import wraps # enables @wraps
from lib.plotter.plot_filer import _PlotFiler as PF
from roc_plot import _RocPlot as Rocp
from roc_grid import _RocGrid as Rgrid
from frames import _Frames as Frs
from mater import _Mater as Mater
from rec_plot import _RecPlot as Re... |
from os import path
from os.path import dirname
def get_base_file_path():
return path.join(dirname(__file__), '..', '..')
def get_base_interface_path():
return path.join(get_base_file_path(), 'interface')
def get_about_dialog_file_path():
return path.join(get_base_interface_path(), 'About.glade')
def get_textbox_... |
from ..utils import *
##
# Hero Powers
# Totemic Call
class CS2_049:
def activate(self):
totems = [t for t in self.entourage if not self.controller.field.contains(t)]
yield Summon(CONTROLLER, random.choice(totems))
# Healing Totem
class NEW1_009:
events = OWN_TURN_END.on(Heal(FRIENDLY_MINIONS, 1))
##
# Mini... |
from math import log10
from .pagerank_weighted import pagerank_weighted_scipy as _pagerank
from .preprocessing.textcleaner import clean_text_by_sentences as _clean_text_by_sentences
from .commons import build_graph as _build_graph
from .commons import remove_unreachable_nodes as _remove_unreachable_nodes
def _set_gr... |
import re
import zlib
import base64
import calendar
import itertools
from six import iterkeys, iteritems, PY3
if PY3:
long = int
def dt_epoch_msecs(value):
"""
Calculate miliseconds since epoch start for python datetimes.
"""
return long(calendar.timegm(value.timetuple())) * 1000
def np_dt_epoc... |
""" Ldap utilities.
Utilities for wrapping communication with LDAP servers.
TODO: Consolidate Cerebrum.modules.Ldap and
Cerebrum.modules.bofhd.bofhd_email:LdapUpdater into this module.
Also, the scripts in contrib/exchange/ use Ldap extensively -- there should
probably be a generic implementation of those objects he... |
# -*- coding: utf-8 -*-
import pytest
from onionbalance import consensus
from onionbalance import config
# Mock hex-encoded HSDir fingerprint list
MOCK_HSDIR_LIST = [
"1111111111111111111111111111111111111111",
"2222222222222222222222222222222222222222",
"3333333333333333333333333333333333333333",
"44... |
from falcon import HTTPNotFound
from ...auth import login_required, check_team_auth
from ... import db
from ...utils import unsubscribe_notifications, create_audit
from ...constants import ADMIN_DELETED
@login_required
def on_delete(req, resp, team, user):
"""
Delete team admin user. Removes admin from the t... |
from msrest.serialization import Model
class JobPatchOptions(Model):
"""Additional parameters for patch operation.
:param timeout: The maximum time that the server can spend processing the
request, in seconds. The default is 30 seconds. Default value: 30 .
:type timeout: int
:param client_reques... |
import cv2
import logging
from ..utils.stoppablethread import StoppableLoopThread
logger = logging.getLogger(__name__)
class Camera(StoppableLoopThread):
def __init__(self, camera_id=-1, fps=25, resolution=[320, 240]):
StoppableLoopThread.__init__(self, fps)
self.capture = cv2.VideoCapture(cam... |
'''
layanmovie XBMC Plugin
Copyright (C) 2013 dmdsoftware
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 versio... |
#!/usr/bin/env python
import ROOT as root
import numpy as np
from array import array
from PandaCore.Tools.Misc import *
from PandaCore.Utils.load import Load
from PandaCore.Tools.root_interface import read_files, draw_hist
from os import getenv, system, path
from pprint import pprint
from multiprocessing.pool import T... |
"""
FreeTextBlock can render and process FreeTextIdevices as XHTML
"""
import logging
from exe.webui.block import Block
from exe.webui.element import TextAreaElement
from exe.webui import common
log = logging.getLogger(__name__)
# =============================================... |
import sys, os, argparse
from sdf_timing import sdfparse
model_carry4 = {
'type': 'CARRY4',
'srcs': {'O5', '?X', '?X_LFF', '?X_LBOTH'},
'out': {'CO0', 'CO1', 'CO2', 'CO3', 'O0', 'O1', 'O2', 'O3'},
'mux': '?CY0',
'pins': {
'DI0': {
'type': 'A'
},
'DI1': {
... |
#-*-coding:utf-8-*-
import re
import web
import os
import json
from pymongo import MongoClient
from lrucache import lrucache
__author__ = 'george.yang'
def getInput(input):
return htmlquote(dict(input))
def htmlquote(inputData):
if isinstance(inputData,dict) == False:
return web.net.htmlquote(inpu... |
{
'name': 'Sale Exception Print',
'version': '13.0.1.0.0',
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'license': 'AGPL-3',
'depends': [
'sale_exception',
],
'data': [
'views/exception_rule_views.xml'
],
'demo': [
],
'installable': True,
'auto... |
import pandas as pd
from glob import glob
import numpy as np
from astLib import astStats as ast
from astLib import astCalc as aca
from sklearn import mixture
import h5py as hdf
import emcee
import sys
# buzzard simulation cosmology
aca.H0 = 70
aca.OMEGA_M0 = 0.286
aca.OMEGA_L0 = 0.714
# millennium cosmology
#aca.H0 =... |
from oslo_config import cfg
from magnum.common.x509 import extensions
from magnum.i18n import _
ALLOWED_EXTENSIONS = ['"%s"' % e.value for e in extensions.Extensions]
DEFAULT_ALLOWED_EXTENSIONS = [
extensions.Extensions.KEY_USAGE.value,
extensions.Extensions.EXTENDED_KEY_USAGE.value,
extensions.Extensions... |
import argparse
import logging
import requests
from coapthon.defines import LOCALHOST, COAP_DEFAULT_PORT, DEFAULT_CH_PATH, Types, Codes, Content_types
from coapthon.forward_proxy.coap import CoAP
from coapthon.serializer import Serializer
from coapthon.messages.message import Message
from coapthon.messages.request imp... |
from django.contrib.auth.models import User
from django.http import Http404
from rest_framework import serializers
from openedx.core.djangoapps.course_groups.cohorts import is_course_cohorted
from notification_prefs import NOTIFICATION_PREF_KEY
from lang_pref import LANGUAGE_KEY
class NotifierUserSerializer(serializ... |
# -*- coding: utf-8
from __future__ import absolute_import
import unittest
from oaxmlapi import commands, datatypes
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
class TestModifyOnConditionClass(unittest.TestCase):
def test_str(self):
slip = data... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 01 13:15:06 2018
@author: tih
"""
import os
import csv
import datetime
def Create(wp_y_irrigated_dictionary, wp_y_rainfed_dictionary, wp_y_non_crop_dictionary, Basin, Simulation, year, Dir_Basin):
"""
Creates a csv file that can be used to create sheet3b.
Pa... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
import os, re, commands, glob, shutil
from autotest.client.shared import error
from autotest.client import utils
from virttest import utils_test, utils_misc, data_dir
def run_performance(test, params, env):
"""
KVM performance test:
The idea is similar to 'client/tests/kvm/tests/autotest.py',
but we ... |
import claripy
import logging
import pyvex
from angr.engines.engine import SuccessorsMixin
from ..light import VEXMixin
from ..lifter import VEXLifter
from ..claripy.datalayer import ClaripyDataMixin, symbol
from ....utils.constants import DEFAULT_STATEMENT
from .... import sim_options as o
from .... import errors
fro... |
# -*- coding: utf-8 -*-
import random
import copy
from C2DMatrix import SPoint, C2DMatrix
from CMineSweeper import CMinesweeper
from CGenAlg import CGenAlg
from SVector2D import SVector2D
# For paint
import pygame
from pygame.locals import *
from sys import exit
dCrossoverRate = 0.7
dMutationRate = 0.1
dMineScale ... |
import Gaffer
import GafferUI
from Qt import QtCore
from Qt import QtGui
from ._CellPlugValueWidget import _CellPlugValueWidget
class _EditWindow( GafferUI.Window ) :
# Considered private - use `_EditWindow.popupEditor()` instead.
def __init__( self, plugValueWidget, **kw ) :
GafferUI.Window.__init__( self, ""... |
"""DQfD Agent implementation."""
import copy
import functools
import operator
from typing import Optional
from acme import datasets
from acme import specs
from acme import types as acme_types
from acme.adders import reverb as adders
from acme.agents import agent
from acme.agents.tf import actors
from acme.agents.tf i... |
import operator
from nose.tools import *
import Factory
def test_alias():
assert Factory.Factory is Factory.bind
def test_callable_object():
class CallMe(object):
def __init__(self, x):
self.x = x
def __call__(self, y):
return self.x + y
fac = Factory.Factory(CallMe... |
"""Home of the `Sequential` model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from tensorflow.python.keras import layers as layer_module
from tensorflow.python.keras.engine import base_layer
from tensorflow.python.keras.engine import ba... |
import random
DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
ALL_DIRECT = ((-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1))
def printMaze(maze):
for line in maze:
print(' '.join(['X' if el == 1 else "-" for el in line]))
def neighbours(coor, maze, direct=DIRECTIONS):
x, y = co... |
"""
This auth module is intended to allow OpenStack client-tools to select from a
variety of authentication strategies, including NoAuth (the default), and
Keystone (an identity management system).
> auth_plugin = AuthPlugin(creds)
> auth_plugin.authenticate()
> auth_plugin.auth_token
abcdefg
> ... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019 Caleb Bell <<EMAIL>>
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... |
"""Check that available RPM packages match the required versions."""
import re
from openshift_checks import OpenShiftCheck, OpenShiftCheckException
from openshift_checks.mixins import NotContainerizedMixin
class PackageVersion(NotContainerizedMixin, OpenShiftCheck):
"""Check that available RPM packages match th... |
import pytest
from babel import core
from babel.core import default_locale, Locale
def test_locale_provides_access_to_cldr_locale_data():
locale = Locale('en', 'US')
assert u'English (United States)' == locale.display_name
assert u'.' == locale.number_symbols['decimal']
def test_locale_repr():
asse... |
# Simple OpenSG Benchmark
import sys
from osgbench import *
# Load the scene
print "Loading Siena (high)...",
sys.stdout.flush()
scene=loadScene("/home/reiners/models/dvs_it.osb.gz")
addRef(scene)
print "done"
# Define the Window's parameters
win=TestWindow()
win.open()
#win.setFullscreen()
# Define the Test(s)
test... |
from __future__ import print_function, unicode_literals
from datetime import datetime
from time import mktime
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
import requests
... |
from django.db.models.expressions import Func
from django.db.models.fields import FloatField, IntegerField
__all__ = [
'CumeDist', 'DenseRank', 'FirstValue', 'Lag', 'LastValue', 'Lead',
'NthValue', 'Ntile', 'PercentRank', 'Rank', 'RowNumber',
]
class CumeDist(Func):
function = 'CUME_DIST'
output_fiel... |
"""
=============================================
Find Regular Segments Using Compact Watershed
=============================================
The watershed transform is commonly used as a starting point for many
segmentation algorithms. However, without a judicious choice of seeds, it
can produce very uneven fragment ... |
import numpy as np
import board
class Game:
def __init__(self):
self.players = []
self.board = board.Board()
def addPlayer(self, player, log_move_history = True):
self.players.append((player, log_move_history))
def getScore(self):
return self.board.getScore()
def ru... |
import logging
_plugins = {}
class _ID(object):
"""
A wrapper class used to represent a plug-in as
an abstract entity which is always instantiated
(even if its respective plug-in does not exist)
and which can be asked for basic information
(name, exists?, is avail. for a corpus?,...).
"""... |
import maya.cmds as cmds
from cmt.dge import dge
from cmt.test import TestCase
import math
class DGETests(TestCase):
def test_add(self):
loc = cmds.spaceLocator()[0]
result = dge("x+3.5", x="{}.tx".format(loc))
cmds.connectAttr(result, "{}.ty".format(loc))
cmds.setAttr("{}.tx".form... |
"""Synse Server wrapper object definition.
The global server state and server initialization and setup functionality
are defined here.
"""
import asyncio
import functools
import os
import signal
import sys
from structlog import get_logger
import synse_server
from synse_server import (app, cache, config, errors, loo... |
from spack import *
class RCar(RPackage):
"""Functions and Datasets to Accompany J. Fox and S. Weisberg, An R
Companion to Applied Regression, Second Edition, Sage, 2011."""
homepage = "https://r-forge.r-project.org/projects/car/"
url = "https://cloud.r-project.org/src/contrib/car_2.1-4.tar.gz"
... |
"""
Glance Image Cache Invalid Cache Entry and Stalled Image cleaner
This is meant to be run as a periodic task from cron.
If something goes wrong while we're caching an image (for example the fetch
times out, or an exception is raised), we create an 'invalid' entry. These
entires are left around for debugging purpos... |
import os, numpy as np, cv2
class RadonFilter:
def __init__(self):
pass
def RadonDemo(self):
origimg = cv2.imread('./SheppLogan_Phantom.tif', cv2.IMREAD_UNCHANGED)
longaxis = np.round(np.sqrt(origimg.shape[0] ** 2.0 + origimg.shape[1] ** 2.0))
img = np.zeros((longaxis, longaxis... |
"""
.. moduleauthor:: Russell Sim <<EMAIL>>
"""
class PublishProvider:
def __init__(self, experiment_id):
raise NotImplemented()
def execute_publish(self, request):
"""
return the user dictionary in the format of::
{"id": 123,
"display": "John... |
#!/usr/bin/env python
import numpy as np
from matplotlib import pyplot as pl
from scipy.special import lpmn
from argparse import ArgumentParser
parser = ArgumentParser(description="Creates 2D plots of power in an oscillation "
"mode multiplet, as in Gizon & Solanki (2003).")
parser.add_argumen... |
# -*- coding: utf-8 -*-
from django import forms
from django.core.validators import RegexValidator
from django.utils.safestring import mark_safe
class SearchForm(forms.Form):
defaults = {
'content_type': 'all',
}
query = forms.CharField(label='Search', required=False)
content_type = forms.Cho... |
import unittest
from unittest.mock import Mock, patch
from airflow.models import Connection
from airflow.models.dag import DAG
from airflow.providers.jira.sensors.jira import JiraTicketSensor
from airflow.utils import db, timezone
DEFAULT_DATE = timezone.datetime(2017, 1, 1)
jira_client_mock = Mock(name="jira_client_... |
import sys
class Error(Exception):
pass
# Local errors
class UnregisteredEnv(Error):
"""Raised when the user requests an env from the registry that does
not actually exist.
"""
pass
class DeprecatedEnv(Error):
"""Raised when the user requests an env from the registry with an
older versio... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Associates each component to a language and to the bundle that provides its
factory
:author: Thomas Calmant
:license: Apache Software License 2.0
:version: 3.0.0
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "Licen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.