content
string
import pytest import mock from hpe_test_utils import OneViewBaseTest from oneview_module_loader import IdPoolsIpv4RangeModule FAKE_MSG_ERROR = 'Fake message error' DEFAULT_RANGE_TEMPLATE = dict( name='Ipv4Range', uri='rest/range/test', subnetUri='rest/subnet/test', type='Range', enabled=True, ...
"""Lizard Widgets""" from django.utils.safestring import mark_safe from django.template import Context, loader class WorkspaceAcceptable(object): """Wrapper/Interface for WorkspaceAcceptable items and html generation. This is used for documentation, to define an interface and to generate the html. ...
import os import unittest from datetime import timedelta from unittest.mock import MagicMock, patch from jinja2 import StrictUndefined from airflow.exceptions import AirflowException from airflow.models import TaskInstance from airflow.models.dag import DAG from airflow.operators.dummy_operator import DummyOperator f...
import os from addons.base.apps import BaseAddonAppConfig from addons.s3.views import s3_root_folder HERE = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_PATH = os.path.join( HERE, 'templates' ) class S3AddonAppConfig(BaseAddonAppConfig): name = 'addons.s3' label = 'addons_s3' full_name = ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'tree_page.ui' # # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): ...
from distutils.core import setup, Extension from cpucat.cpucat_sth import PACKAGE, VERSION setup(name="CPUcat", version=VERSION, description="Just like CPU-Z on Windows.", author="CUI Hao", author_email="<EMAIL>", ext_modules = [Extension("cpuinfo._cpuidcall", ["cpuin...
""" Django settings for rms project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Bui...
from .element import Element from .groups import GroupXVIII from .periods import * class He(Element, PeriodI, GroupXVIII): __slots__ = () @property def atomic_number(self): return 2 @property def isotopes_distribution(self): return {3: 1e-06, 4: 0.999999} @property def i...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import shutil import time from textwrap import dedent from pants.backend.jvm.ivy_utils import IvyUtils from pants.backend.jvm.targets.jar_dependency import ...
from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.template import Template, Context from .activation import STATUS from .exceptions import FlowRuntimeError from .fields import FlowReferenceField, TaskReferenceField, TokenField from .managers import P...
import sigrokdecode as srd from .lists import * class SamplerateError(Exception): pass class Decoder(srd.Decoder): api_version = 3 id = 'dali' name = 'DALI' longname = 'Digital Addressable Lighting Interface' desc = 'DALI lighting control protocol.' license = 'gplv2+' inputs = ['logic'...
from collections import defaultdict from django.conf import settings from django.core.urlresolvers import reverse from django.template import defaultfilters as filters from django.utils.http import urlencode from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy fr...
# -*- encoding: utf-8 -*- """ @authors: Andrés Felipe Calderón <EMAIL> Sebastián Ortiz V. <EMAIL> @license: GNU AFFERO GENERAL PUBLIC LICENSE SIIM Models are the data definition of SIIM2 Framework Copyright (C) 2013 Infometrika Ltda. This program is free software: you can redistribute it and/or modify...
from .services.datastore_admin import DatastoreAdminClient from .services.datastore_admin import DatastoreAdminAsyncClient from .types.datastore_admin import CommonMetadata from .types.datastore_admin import CreateIndexRequest from .types.datastore_admin import DeleteIndexRequest from .types.datastore_admin import Ent...
import random map_height = 5 map_width = 5 def find_neighbors(j, k, island_map): neighbors_found = set() if j > 0 and island_map[(j - 1, k)] == 1: neighbors_found.add((j - 1, k)) if j < map_height - 1 and island_map[(j + 1, k)] == 1: neighbors_found.add((j + 1, k)) if k > ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright (c) 2014 windpro Author : windpro E-mail : <EMAIL> Date : 14/12/29 Desc : 缓存更新控制器,具体实现需要继承interface.BaseUpdate """ from interface import BaseUpdate, BaseRoute import datetime import gevent.lock from Queue import Queue, Full, Empty import gevent ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Thu Jun 9 09:48:40 2016 @author: mints """ from providers.basic import BasicLookup from lib.html_addons import replace_empty, distance_column_arcsec class WSALookup(BasicLookup): CATALOGS = {'UKIDSS_LAS': '101', 'UKIDSS_GPS': '102', ...
import urllib, sys import log def make_url(params): url = 'plugin://script.media.aggregator/?' + urllib.urlencode(params) return url def get_params(): if len(sys.argv) < 3: return None param = dict() paramstring = sys.argv[2] if len(paramstring) >= 2: params = sys.argv[2] cleanedparams = params.replace(...
""" A simple test plugin. """ from ocupado.plugin import Plugin class Test(Plugin): """ A simple test plugin for testing. """ def __init__(self, key): """ Creates an instance of a Plugin. :param str key: A dummy input used for testing. """ pass def authe...
""" Nodes Related Intricacies """ ### INCLUDES ### import logging from py_knife.ordered_dict import OrderedDict from gate.database import ModifiedOrderedDict from gate.modbus import MODBUS_REG_NUM from node import Node ### CONSTANTS ### ## Logger ## LOGGER = logging.getLogger(__name__) # LOGGER.setLevel(logging.D...
# -*- coding: utf-8 -*- #The following code assumes that Biopython is installed from Bio.Seq import Seq from Bio import motifs from Bio.Alphabet import IUPAC #imports the NCBI_utils lib containing the functions for GI accession and BLAST import MG_synth_lib as MGlib #random number generation import random #mean and s...
#!/usr/bin/env python import numpy as np from gpaw.mpi import world from gpaw.blacs import BlacsGrid, Redistributor from gpaw.utilities import compiled_with_sl def test(comm, M, N, mcpus, ncpus, mb, nb): grid0 = BlacsGrid(comm, 1, 1) desc0 = grid0.new_descriptor(M, N, M, N, 0, 0) A_mn = desc0.zeros(dtype...
"""**SAFE (Scenario Assessment For Emergencies) - API** The purpose of the module is to provide a well defined public API for the packages that constitute the SAFE engine. Modules using SAFE should only need to import functions from here. Contact : <EMAIL> .. note:: This program is free software; you can redistribut...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'ContentBlock.added' db.add_column('suave_contentblock', 'added', self....
from datetime import date import unittest import os from ...workbook import Workbook from ..helperfunctions import _compare_xlsx_files class TestCompareXLSXFiles(unittest.TestCase): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None ...
from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtSvg import * from PyQt4.QtXml import * from PolygonImage import PolygonImage import numpy as np class SVGPaintView(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) self.paint_colour = (0, 0, 1) # Curr...
import binascii import datetime import json import logging import os import random import requests from retrying import retry import string import subprocess import sys requests.packages.urllib3.disable_warnings() LOGNAME_LENGTH = 16 LOGGING_PREFIX = 'GCP_INTEGRATION_TEST_' DEFAULT_TIMEOUT = 30 # seconds ROOT_END...
import datetime import hashlib import uuid import factory import factory.fuzzy import packaging.utils from warehouse.packaging.models import ( BlacklistedProject, Dependency, DependencyKind, File, JournalEntry, Project, Release, Role, ) from .accounts import UserFactory from .base imp...
# -*- coding: utf-8 -*- import skimage.io import skimage.feature import skimage.color import skimage.transform import skimage.util import skimage.segmentation import numpy # "Selective Search for Object Recognition" by J.R.R. Uijlings et al. # # - Modified version with LBP extractor for texture vectorization def _...
from timelinelib.features.installed.installedfeatureexportimages import InstalledFeatureExportImages from timelinelib.features.installed.installedfeaturescontainers import InstalledFeatureContainers from timelinelib.features.installed.installedfeatureverticalscrolling import InstalledFeatureVerticalScrolling from timel...
import demistomock as demisto from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import] from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import] import dateparser EQUAL = 'equal' BEFORE = 'before' AFTER = 'after' TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S%Z' DT_STRING = "TimeStampCom...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys from setuptools import setup, find_packages DESCRIPTION = """ Extension for python-social-auth [https://pypi.python.org/pypi/python-social-auth/] that add ability to create posts in social nets from registered user directly. Module contains...
import numpy as np import pandas as pd from numba import njit @njit def series_nlargest(): series = pd.Series(np.arange(10)) return series.nlargest(4) # Expect series of 9, 8, 7, 6 print(series_nlargest())
# encoding: utf-8 # The main definition of the evolutionary algorithm import argparse import initialize import json import logging import multiprocessing import network import numba import numpy as np import random import scoring import time import utils from twisted.internet import reactor __author__ = 'Jason Ansel' ...
import random import weakref import collections namedtuple = collections.namedtuple randint = random.randint def _roller(low, high): return [randint(low, high), randint(low, high)] class DieRoll: def __init__(self, *args, roller=None): if roller is None: roller = _roller self.ro...
from atom.api import Atom, Bool, Int, Typed from enaml.qt.QtCore import Qt, QEvent, QRect, QSize, QPoint, QMargins, Signal from enaml.qt.QtGui import QApplication, QFrame class QDockFrame(QFrame): """ A QFrame base class for creating dock frames. """ #: No resize border. NoBorder = 0 #: Resize ...
from sys import exit from glutton.utils import get_log from glutton.ensembl_biomart import download_database_biomart, get_all_species_biomart, get_latest_release_biomart from glutton.ensembl_pycogent import download_database_pycogent, get_all_species_pycogent from glutton.ensembl_sql import download_database_sql, get...
import re import sys class Ingredient: def __init__(self, name, capacity, durability, flavor, texture, calories): self.name = name self.capacity = capacity self.durability = durability self.flavor = flavor self.texture = texture self.calories = calories class Recipe...
__version__ = '0.2' __versionTime__ = '2013-01-22' __author__ = 'Max Kolosov <<EMAIL>>' __doc__ = ''' pybass_ape.py - is ctypes python module for BASS_APE - extension to the BASS audio library that enables the playback of Monkey's Audio streams. ''' import sys, ctypes, platform, pybass QWORD = pybass.QWORD...
from fractions import Fraction # polygon intersection.. doesnt work. # assume - input polys are clockwise-ordered set of 3 or more points # assume - points are using rational numbers for coordinates (Fractions) # assume - polygons are simple # design - dont use angles # point = [x,y] # line = [a,b,c] where ax+by+c ...
""" Takes a directory as input and walks through it recursively looking for all .txt files. Each file should contain complete messages in the format of playdiplomacy.com and separated by some number of "=========="'s on a new line. It also takes a file that is just the playdiplomacy gamehistory page saved. The output...
from __future__ import unicode_literals import datetime from six import iteritems import frappe from frappe import _ from frappe.utils import flt, formatdate from erpnext.controllers.trends import get_period_date_ranges, get_period_month_ranges def execute(filters=None): if not filters: filters = {} columns = ...
# -*- coding: utf-8 -*- """bustools Python tools for electrical busses """ import os, re, codecs # Always prefer setuptools over distutils from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) # from https://github.com/pypa/pip/blob/develop/setup.py def read(*parts): # ...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import pickle import os.path from include.dataset_fnames import generate_station_data_fname, generate_data_fname, generate_response_data_fname from include.feature_lists import numeric_features, numeric_missing_features_list, ...
import logging from dateutil.tz import tz from c7n.exceptions import PolicyValidationError from c7n.policy import execution, ServerlessExecutionMode, PullMode from c7n.utils import local_session, type_schema from c7n_gcp import mu DEFAULT_REGION = 'us-central1' class FunctionMode(ServerlessExecutionMode): sc...
""" This file contains tasks that are designed to perform background operations on the running state of a course. """ from __future__ import absolute_import import logging from collections import OrderedDict from datetime import datetime from time import time import six import unicodecsv from django.contrib.auth.mod...
""" Functions for system package """ import os import platform import re import stat import sys import subprocess class BuildTestCommand(): ret = [] out = "" err = "" def execute(self,cmd): """ execute a system command and return output and error""" self.ret = subprocess.Popen(cmd,sh...
import logging log = logging.getLogger(".") #------------------------------------------------------------------------- # # GNOME/GTK modules # #------------------------------------------------------------------------- from gi.repository import Gtk #---------------------------------------------------------------------...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os import json import logging from ast import literal_eval from datetime import datetime import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.distributed as dist from torch.utils.data.dist...
#!/usr/bin/env python from argparse import ArgumentParser from threading import Thread import time import os from ServerConfig import Client from ServerConfig import Aim from ServerConfig import TellStore def reduceComma(x, y): return x + ',' + y def addPort(x): return x + ':8715:8716' def startSepClient(p...
from __future__ import absolute_import from __future__ import print_function import sys, argparse, os import subprocess, string ## parse command line arguments ## def_dbname = 'autobahn' def_dbuser = 'autouser' def_configdir = '/usr/local/sqlauth' def_superuser = 'postgres' def_sql = 'psql' def_initdb = 'initdb' def...
"""Module keeping state for Ganeti watcher. """ import os import time import logging from ganeti import utils from ganeti import serializer from ganeti import errors # Delete any record that is older than 8 hours; this value is based on # the fact that the current retry counter is 5, and watcher runs every # 5 min...
"""Add salaries table Revision ID: 770ed51b4e16 Revises: 2a9064a2507c Create Date: 2019-01-25 15:47:13.812837 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '770ed51b4e16' down_revision = '2a9064a2507c' branch_labels = None depends_on = None def upgrade(): ...
import ast import datetime import json from django.core.files.base import ContentFile from django.core.exceptions import ValidationError from django.db import transaction from django.utils.timezone import utc from lrs import models from lrs.exceptions import IDNotFoundError, ParamError from lrs.util import etag, get_us...
# # Process: An activity that changes inputs into outputs. It could transform or transport EconomicResource(s). # import graphene from graphene_django.types import DjangoObjectType import valuenetwork.api.types as types from valuenetwork.api.schemas.Auth import _authUser from valuenetwork.api.types.EconomicEvent impo...
import os import time import perf import zopkio.runtime as runtime import zopkio.test_utils as testutilities SAMPLE = lambda size: [str(i) for i in range(1, size + 1)] SMALL_SAMPLE = SAMPLE(3) MEDIUM_SAMPLE = SAMPLE(100) LARGE_SAMPLE = SAMPLE(1000) def test_correctness(): """ Tests if the correct sums are calc...
import copy import numpy as np m_prefs=np.array([[4,0,1,2,3],[1,2,0,3,4],[3,1,0,2,4]]) f_prefs=np.array([[0,1,2,3],[1,0,3,2],[1,2,0,3],[0,3,2,1]]) def array_to_dict(array): dict = {} for x, y in enumerate(array): dict[x] = list(y) return dict def deferred_acceptance(m_prefs,f_prefs): m_pre...
# -*- encoding: utf-8 -*- from opensearchsdk.apiclient import api_base class AppManager(api_base.Manager): """Application resource manage class""" def list(self, page=None, page_size=None): """ get application list with given page and page size. :param page: :param page_size: ...
from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from django.utils import timezone from django.conf import settings from datetime import datetime, timedelta from facepy import GraphAPI from facepy.exceptions import FacepyError import re import io import ...
#!/usr/bin/env python3 import codecs # Make a special character codepage mapping starting from ASCII printable # characters and adding special characters in non-whitespace ASCII control # characters. So that 128 of the 256 available characters can be used # for DTE code units. name = 'thwaite' decoding_table = [ #...
"""This file contains a unit test for ASL securityd log parser.""" import unittest # pylint: disable=unused-import from plaso.formatters import mac_securityd as mac_securityd_formatter from plaso.lib import eventdata from plaso.lib import timelib_test from plaso.parsers import mac_securityd as mac_securityd_parser fr...
# coding=utf-8 """Tests for medusa/test_list_associated_files.py.""" from __future__ import unicode_literals from medusa.name_parser.parser import NameParser import guessit import pytest @pytest.mark.parametrize('p', [ { 'name': u'[HorribleSubs] Cardcaptor Sakura Clear Card - 08 [720p].mkv', 'in...
import base64 import httplib from selenium.webdriver.remote.command import Command from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.common.exceptions import WebDriverException from service import Ser...
""" .. module:: pyfai_azimuthal_integrator_with_bragg_filter :platform: Unix :synopsis: A plugin to integrate azimuthally "symmetric" signals i.e. SAXS, WAXS or XRD.Requires a calibration file .. moduleauthor:: Aaron D. Parsons <<EMAIL>> """ import logging import numpy as np from savu.plugins.filters.base_azimu...
import core.job import core.implant import uuid import time import os class DownloadFileImplant(core.implant.Implant): NAME = "Download File" DESCRIPTION = "Downloads a remote file off the target system." AUTHORS = ["RiskSense, Inc."] STATE = "implant/util/download_file" def load(self): s...
import cgi import glob import io import json import logging import os import random import shutil import string import sys from datetime import datetime, timezone from io import StringIO from shutil import * from subprocess import CalledProcessError, call, check_output from tempfile import * from zipfile import ZipFile...
"""Settings for testing zinnia""" from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS SITE_ID = 1 USE_TZ = True STATIC_URL = '/static/' SECRET_KEY = 'secret-key' ROOT_URLCONF = 'zinnia.tests.implementions.urls.default' PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.SHA1PasswordHasher' ] MIDDLEWARE_CLASSES = [...
# # __all__ = [ 'DEFAULT_ENV_PREFIX', 'DEFAULT_CONFIG_PATH', 'get_config' ] import re import sys import logging import os from os.path import join as pjoin, expanduser try: import configparser except ImportError: import ConfigParser as configparser DEFAULT_CREDENTIALS_FILE = '.libcloudcli/confi...
import os import pytest import OpenSSL import mitmproxy.net.tcp requires_alpn = pytest.mark.skipif( not mitmproxy.net.tcp.HAS_ALPN, reason='requires OpenSSL with ALPN support') @pytest.fixture() def disable_alpn(monkeypatch): monkeypatch.setattr(mitmproxy.net.tcp, 'HAS_ALPN', False) monkeypatch.set...
""" Copyright 2007 Free Software Foundation, Inc. This file is part of GNU Radio SPDX-License-Identifier: GPL-2.0-or-later """ from __future__ import absolute_import from os import path from gi.repository import Gtk from . import Constants, Utils, Dialogs class FileDialogHelper(Gtk.FileChooserDialog, object): ...
import os import glob import subprocess import pandas import numpy as np import matplotlib.pyplot as plt import seaborn.apionly as seaborn from . import viz import wqio from wqio import utils class _WQSample_Mixin(wqio.core.samples._basic_wq_sample): def __init__(self, *args, **kwargs): super().__init_...
# -*- coding: utf-8 -*- #################################################################################################### from OvhApi import Client, dump_json #################################################################################################### client = Client() services = client.get_vps() for se...
# coding=utf-8 import ctypes from copy import copy from multiprocessing import Process, Value, Array, Manager, Lock from random import random, randint import click as cl import numpy as np import qlearning as ql updated_matrix = ql.make_transition_matrix(ql.updated_grid) def update_delta_q(local_q_matrix, state, a...
"""Module containing memtier installation and cleanup functions.""" import json import logging import pathlib import re from typing import Any, Dict, List, Optional, Text, Tuple, Union from absl import flags import dataclasses from perfkitbenchmarker import errors from perfkitbenchmarker import flag_util from perfkit...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import nodeshot.core.base.fields import django.contrib.gis.db.models.fields import django.utils.timezone import django_hstore.fields class Migration(migrations.Migration): dependencies = [ ('layers',...
#!/usr/bin/env python # -*- coding: utf-8 -*- from anki.hooks import wrap from anki.utils import stripHTMLMedia from aqt.editor import Editor, EditorWebView from aqt.utils import tooltip from aqt import dialogs, mw import re import os import sys import copy import pickle from BeautifulSoup import BeautifulSoup from P...
import attr from typing import ClassVar @attr.s(auto_attribs=True) class A1: bar1: int <error descr="Fields with a default value must come after any fields without a default.">baz1</error>: int = 1 foo1: int <error descr="Fields with a default value must come after any fields without a default.">bar2<...
import numpy as np import optimize as opt import matplotlib.pyplot as plt class Trainer: def __init__(self, network, x_train, t_train, x_test, t_test, epoches=20, mini_batch_size=100, optimizer='sgd', optimizer_param={'lr':0.01}): self.network = network self.x_train = x_train ...
import clv_seedling import category import clv_tag import clv_annotation # import seq # import batch_history
# coding=utf-8 import os from django.conf import settings from django.contrib.admin.models import LogEntry from django.core.management.base import BaseCommand from cla_butler.qs_to_file import QuerysetToFile from cla_eventlog.models import Log from cla_provider.models import Feedback from complaints.models import Com...
import threading import unittest from pycoin.serialize import h2b_rev from pycoin.services import providers from pycoin.services.blockchain_info import BlockchainInfoProvider from pycoin.services.blockcypher import BlockcypherProvider from pycoin.services.blockexplorer import BlockExplorerProvider from pycoin.services...
import os import shutil cur_dir= os.getcwd() def make_folder(name): if (os.path.exists('.\\'+name)): return else: os.makedirs('.\\'+name) if os.path.exists(os.path.join(cur_dir,'clean_folder.txt'))==False: txt_file_create=open('clean_folder.txt','w') txt_file= open('cle...
#!/usr/bin/python # alsd -- Ableton Live set dumping utility # by Andrew Bulhak http://dev.null.org/acb/ # # For instructions, read the README, or type alsd.py -h import xml.etree.ElementTree as ET import gzip import plistlib # the maybe monad def bind(val, f): return (val is not None) and f(val) or None hexch...
from pymongo import MongoClient from pymongo.errors import DuplicateKeyError import logging,json logger = logging.getLogger('fource') hdlr = logging.FileHandler('/var/tmp/fource.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger....
from tempest_lib.common.utils import data_utils from tempest_lib import exceptions as lib_exc from tempest.api.compute import base from tempest import config from tempest.openstack.common import log as logging from tempest import test CONF = config.CONF LOG = logging.getLogger(__name__) class ImagesOneServerNegati...
#!/usr/bin/python import time import subprocess import pickle import sys,os from timeout import timeout #============================================================================== # Variables #============================================================================== # Some descriptive variables #name ...
#!/usr/bin/env python ''' Created on Aug 23, 2014 @author: tung ''' import sys, os, time, multiprocessing, optparse import subprocess, logging, datetime def cpu_count(): ''' Returns the number of CPUs in the system ''' num = 1 if sys.platform == 'win32': try: num = int(os.environ[...
import numpy as np class Param: """An learnable parameter array. Attributes: a (array): The parameter itself; typically a matrix. d (array): The gradient, computed externally. """ decay = 0.9 """Coefficient for RMSprop's decaying average.""" def __init__(self, a, name=''): ...
#-*- coding:utf-8 -*- """ This file is part of openexp. openexp 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. openexp is distributed in ...
""" This template creates an internal load balancer. """ def set_optional_property(destination, source, prop_name): """ Copies the property value if present. """ if prop_name in source: destination[prop_name] = source[prop_name] def get_backend_service(properties, project_id, res_name): """ Cre...
from __future__ import division import math import planar from planar.util import cached_property, assert_unorderable, cos_sin_deg class Affine(tuple): """Two dimensional affine transform for linear mapping from 2D coordinates to other 2D coordinates. Parallel lines are preserved by these transforms. Aff...
""" Core implementation of aiosqlite proxies """ import asyncio import logging import sqlite3 import sys import warnings from functools import partial from pathlib import Path from queue import Empty, Queue from threading import Thread from typing import ( Any, AsyncIterator, Callable, Generator, I...
from django.apps import AppConfig from django.db.models import signals class AnalyticsConfig(AppConfig): name = 'waldur_mastermind.analytics' verbose_name = 'Analytics' def ready(self): from waldur_core.quotas.models import Quota from waldur_core.structure.models import BaseResource ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Partially based on AboutMethods in the Ruby Koans # from runner.koan import * def my_global_function(a, b): return a + b class AboutMethods(Koan): def test_calling_a_global_function(self): self.assertEqual(5, my_global_function(2, 3)) # NOTE: ...
# vim: fileencoding=utf8:et:sw=4:ts=8:sts=4 from __future__ import absolute_import from .. import error from ..const import search as searchconst, table, util from ..db import query, txn __all__ = ['create', 'search', 'list', 'set_flags', 'shift', 'remove'] def create(pool, base_id, ctx, value, flags=None, index=...
#!/usr/bin/env python import sys import os.path as path import re import UserDict from warnings import warn import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) import quodlibet.config from quodlibet.formats import MusicFile quodlibet.config.init() class AudioFile(UserDict.DictMixin): """A simple cl...
"""Tests for storage purge.""" import datetime import uuid from oslo_utils import timeutils from jacket import context from jacket import db from jacket.db.storage.sqlalchemy import api as db_api from jacket.storage import exception from jacket.storage import test from oslo_db.sqlalchemy import utils as sqlalchemyu...
import datetime import event import threading from event_scheduler import EventScheduler from file_worker import FileWorker from event import Event from task import Task import time import calendar import arrow from my_exceptions import * import icalendar from icalendar import Calendar class EventOrganizer(EventSched...
import json import sys import re def read_until(fin, tag): while True: line = fin.readline() if not line: print "Unexpected end of file" sys.exit(-1) if tag in line: return def read_mesh_data(in_file, npoints): out_data = [] while True: s = i...
# -*- coding: utf-8 -*- from django import forms from django.template import loader as template_loader from django.template import Context from yawf import get_workflow, get_workflow_by_instance from yawf.exceptions import WorkflowNotLoadedError, NoAvailableMessagesError from yawf.messages.allowed import get_allowed_...