content
stringlengths
4
20k
#!/usr/bin/env python """ Script to pull in the 10th and 90th percentiles of a set of models and write them out to files. Requires the node_js server to be running locally. Limited to a single season, region and variable. """ import urllib import simplejson import numpy as np import copy models = ["ACCESS1-0", "AC...
import numpy as np import astropy.coordinates as acoo import astropy.units as auni vlsr0 = 232.8 # from mcmillan 2017 def correct_pm(ra, dec, pmra, pmdec, dist, vlsr=vlsr0, split=None): if split is None: return correct_pm0(ra, dec, pmra, pmdec, dist, vlsr=vlsr0) else: N = len(ra) n1 ...
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
"""Filters for filtering the data of the tracking app endpoints.""" from functools import wraps from django.db.models import Q from django_filters.constants import EMPTY_VALUES from django_filters.rest_framework import ( BaseInFilter, DateFilter, Filter, FilterSet, NumberFilter, ) from timed.trac...
TEST_ALLOWED_HOST = { 'id': 12345, 'name': 'Test Allowed Host', 'accountId': 1234, 'credentialId': None, 'createDate': '2020-01-01 00:00:01', 'iscsiAclCredentials': { 'id': 129, 'allowedHostId': 12345, 'subnetId': 12345678 }, 'subnetsInAcl': [{ 'id': 12345...
"""The Netatmo integration.""" import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( ATTR_EVENT_TYPE, ATTR_FACE_URL, ATTR_ID, ATTR_IS_KNOWN, ATTR_NAME, ATTR_PERSONS, DATA_PERSONS, DEFAULT_PERSON, ...
VERSION = (0, 1, 6, "final") def get_version(): if VERSION[3] != "final": return "%s.%s.%s%s" % (VERSION[0], VERSION[1], VERSION[2], VERSION[3]) else: return "%s.%s.%s" % (VERSION[0], VERSION[1], VERSION[2]) __version__ = get_version() try: from django.conf import settings # default ...
import hildon import gtk import osso import pango from portrait import FremantleRotation import pge_editor import os from subprocess import * import commands import gobject import pge_preferences import pge_recentchooser LANGUAGES = (('.R','R'), ('.ada','ada'), ('.c','c'), ('.change...
from .resource import Resource class VirtualNetworkGatewayConnection(Resource): """A common class for general resource information. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param...
"""Saver for eager mode TensorFlow.""" # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LIC...
# -*- coding: utf-8 -*- """ reporead_inotify command Watches repo.files.tar.gz files for updates and parses them after a short delay in order to catch all updates in a single bulk update. Usage: ./manage.py reporead_inotify [path_template] Where 'path_template' is an optional path_template for finding the repo.files...
import time, calendar, math # some multipliers for interpreting GPS output METERS_TO_FEET = 3.2808399 # Meters to U.S./British feet METERS_TO_MILES = 0.00062137119 # Meters to miles METERS_TO_FATHOMS = 0.54680665 # Meters to fathoms KNOTS_TO_MPH = 1.1507794 # Knots to miles per hour KNOTS_TO_KPH = 1.852 # Knots to ki...
from ironicclient import client as ironic_client from ironicclient import exc as ironic_exception import mock from oslo_config import cfg from nova import exception from nova import test from nova.tests.unit.virt.ironic import utils as ironic_utils from nova.virt.ironic import client_wrapper CONF = cfg.CONF FAKE_CLI...
def is_real(name, checksum): frequencies = {} for letter in name: if letter not in frequencies: frequencies[letter] = 1 continue frequencies[letter] += 1 sorted_letters = sorted(frequencies.keys(), key=lambda k: (frequencies[k], ord("z") - ord(k)), reverse=True) ...
# -*- coding: utf-8 -*- """ setup :copyright: © 2013 by Openlabs Technologies & Consulting (P) Limited :license: BSD, see LICENSE for more details. """ import os from setuptools import setup, Command class RunAudit(Command): """Audits source code using PyFlakes for following issues: - Names w...
# -*- coding: utf-8 -*- import os # This file is part of DEAP. # # DEAP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser 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 -*- """ Created on Thu Mar 3 18:33:13 2016 @author: rachel3834 """ ############################################################################## # GRID STATISTICS ############################################################################## from sys import argv, exit ...
# -*- coding: utf-8 -*- """ #TopicModeling V2 /scripts/verificadorPaquetes.py ######### # 02/08/2015 # Sistema desarrollado por el GIL, Instituto de Ingenieria UNAM # <EMAIL> # Verifica que las dependencias utilizadas por TopicModeling existan # return: # True -> si todas las dependencias están instaladas # False -> ...
"""SECS 2 byte unsigned integer variable type.""" from .base_number import BaseNumber class U2(BaseNumber): """ Secs type for 2 byte unsigned data. :param value: initial value :type value: list/integer :param count: number of items this value :type count: integer """ format_code = 0...
from collections import OrderedDict from rest_framework.reverse import reverse def filter_best_submissions(submissions): best = {} eid = None for i,s in enumerate(submissions): if s.exercise_id != eid: eid = s.exercise_id best[eid] = {} if s.status == 'ready': ...
# Based on this file: # https://github.com/pallets/werkzeug/blob/master/werkzeug/_reloader.py import time, os, sys, subprocess PY2 = sys.version_info[0] == 2 class Reloader(object): RELOADING_CODE = 3 def start_process(self): """Spawn a new Python interpreter with the same arguments as this one,...
''' This module provides functions for embedding Bokeh plots in various different ways. There are a number of different combinations of options when embedding Bokeh plots. The data for the plot can be contained in the document, or on a Bokeh server, or in a sidecar JavaScript file. Likewise, BokehJS may be inlined in ...
# -*- 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 model 'PageCommunity' db.create_table('zorna_community_pages', ( ('id', self.gf('django...
# -*- coding: utf-8 -*- import re from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): depends_on = ( ('main', '0038_add_depends_optional_description.py'), ) def forwards(self, orm): Depend = orm['packages.Depend'] ...
from indico.core.db import DBMgr from MaKaC.user import AvatarHolder, Avatar, GroupHolder from MaKaC.conference import CategoryManager, ConferenceHolder ch = ConferenceHolder() ah = AvatarHolder() gh = GroupHolder() print "Cleaning index..." userIds = [] DBMgr.getInstance().startRequest() for av in ah.getList(): ...
from generator.analysis.Analysis import Analysis from generator.analysis.AtomicBasicBlock import E, S from generator.coder.elements import DataObject, Include import logging class CFGRegions(Analysis): """Generates assertions that are inserted before each system call to track the control flow within the system...
import os import sys ###### # Warning: relpath might be replaced by equivalent os.relpath introduced in # Python 2.6 (Calibre 7). # It is still here to ensure compatibility with Calibre 6 (Python 2.5) def relpath(target, base): """ Find relative path from base to target if target== "/local/chris/appli" and...
"""The HTTP api to control the cloud integration.""" import asyncio from functools import wraps import logging import aiohttp import async_timeout import attr from hass_nabucasa import Cloud, auth, thingtalk from hass_nabucasa.const import STATE_DISCONNECTED import voluptuous as vol from homeassistant.components impo...
import numpy as np import matplotlib.pyplot as plt import quantities as pq from ..misc.plot import simpleaxis def plot_raster(trials, color="#3498db", lw=1, ax=None, marker='.', marker_size=10, ylabel='Trials', id_start=0, ylim=None): """ Raster plot of trials Parameters ---------- ...
import unittest from os.path import dirname, join as pjoin from nose.tools import assert_equal from ..ott_tsv import get_parser SAMPLE_DIR = pjoin(dirname(__file__), '..', '..', 'sample_data') def simplify_row(row): return dict(filter( lambda i: i[1] is not None, row.serialize().items())) class TestO...
# Propositions about taxonomies - for use as a 'patch language' from org.opentreeoflife.taxa import Rank import sys # A different false value, used here to mean "I don't know" Dunno = None def proclaim(tax, prop): # called make_claim in claim.py attitude1 = prop.proclaim(tax, True) if attitude1: ...
from os.path import join from urllib import urlencode from plone.formwidget.contenttree import ContentTreeFieldWidget from plone.memoize.instance import memoize from plone.z3cform import layout from plone.z3cform.layout import wrap_form, FormWrapper from Products.Archetypes.event import ObjectInitializedEvent from Prod...
import os import ftplib import fnmatch import ConfigParser from contextlib import closing Config = ConfigParser.ConfigParser() Config.read("C:/Apps/LiClipse Workspace/samplePython/ftpsamples/filegenie.ini") def ConfigSectionMap(section): attrib = {} options = Config.options(section) for option in options:...
# -*- coding -*- """ Provides some command utility functions. TODO: matcher that ignores empty lines and whitespace and has contains comparison """ from __future__ import unicode_literals from hamcrest import assert_that, is_not, equal_to, contains_string # DISABLED: from beehive4cmd.hamcrest_text import matches_re...
import json from itertools import imap from collections import OrderedDict # Lense Libraries from lense.client import SUPPORT_CACHE from lense.client.args.options import OPTIONS from lense.client.handlers.base import ClientHandler_Base def get_commands(): """ Return a list of supported commands from the cache...
""" Module for helper apps relating to the LSST-DM reporting cycle and LSST-SIMS work planning. """ from __future__ import print_function import re from io import StringIO from jira import JIRA SERVER = "https://jira.lsstcorp.org/" MAX_RESULTS = None # Fetch all results def cycles(): return ['S14', ...
import json import csv from api.models import * from api import db import sys import operator def wards(year, ballot, lvl_id): rows = db.session.query(Ward).filter(Ward.year == year).all() results = [] for row in rows: if (ballot == "national"): dataset = populate_dataset(json.loads(row.results_national)) el...
''' GenderGenreMod4 Copyright 2016 Brian N. Larson and licensors GENDER/GENRE PROJECT CODE: Module 4 This code is the fourth segment used to generate and analyze the data for the article Gender/Genre: The Lack of Gendered Register in Texts Requiring Genre Knowledge. _Written Communication_, 33(4), 360–384. https://do...
import sys import os import struct import numpy import struct import gdal import osr import gdalnumeric from gdalconst import * def main(): if(len(sys.argv)==3): inputFile = sys.argv[1] outputFile = sys.argv[2] if(os.path.exists(inputFile)): if(not os.path.exists(outputFile)): inputDat...
# -*- coding: utf-8 -*- """ Creates a new SeleniumBase presentation with boilerplate code. Usage: seleniumbase mkpres [FILE.py] [LANG] or sbase mkpres [FILE.py] [LANG] Example: sbase mkpres new_presentation.py --en Language Options: --en / --English | --zh / --Chinese --nl / --Dutch ...
from django.http import HttpResponse from django.shortcuts import render from django.shortcuts import redirect from moviealert.forms import MovieForm from moviealert.models import TaskList, RegionData from datetime import date import json def home(request): form = MovieForm() if request.method == 'POST' and r...
""" Detects installed OSes (needs root privileges)""" import os import subprocess import re import tempfile import logging import misc.misc as misc # constants WIN_DIRS = ["windows", "WINDOWS", "Windows"] SYSTEM_DIRS = ["system32", "System32"] WINLOAD_NAMES = ["Winload.exe", "winload.exe"] SECEVENT_NAMES = ["SecEve...
"""Dispatches tests, either sharding or replicating them. Performs the following steps: * Create a test collection factory, using the given tests - If sharding: test collection factory returns the same shared test collection to all test runners - If replciating: test collection factory returns a unique test co...
"""Session Handling for SQLAlchemy backend.""" import re import time from sqlalchemy.exc import DisconnectionError, OperationalError import sqlalchemy.interfaces import sqlalchemy.orm from sqlalchemy.pool import NullPool, StaticPool import nova.exception import nova.flags as flags import nova.openstack.common.log as...
import copy class Config(object): """ The configration of the earo application. """ __config__ = { 'app_name': 'earo', 'source_event_cls': (), 'processors_tag_regex': ['.*'], 'dashboard_host': '0.0.0.0', 'dashboard_port': 9527 } """ The default confi...
import grequests import requests import re from hashlib import md5 from collections import OrderedDict class Kitten(object): def __init__(self, config): self.bduss = config['bduss'] self.headers = { 'Cookie': 'BDUSS={0};STOKEN={1};'.format(config['bduss'], config['stoken']) } ...
import threading import random import time import logging import sys from os.path import dirname from hazelcast import six from hazelcast.six.moves import range sys.path.append(dirname(dirname(dirname(__file__)))) import hazelcast def do_benchmark(): THREAD_COUNT = 1 ENTRY_COUNT = 10 * 1000 VALUE_SIZE =...
from bs4 import BeautifulSoup from sickbeard import classes, show_name_helpers, logger from sickbeard.common import Quality import generic import cookielib import sickbeard import urllib import urllib2 import re class ADDICTProvider(generic.TorrentProvider): def __init__(self): generic.TorrentPro...
#!/usr/bin/env python """ This file shows how you can define a custom stringifier for PuDB. A stringifier is a function that is called on the variables in the namespace for display in the variables list. The default is type()*, as this is fast and cannot fail. PuDB also includes built-in options for using str() and ...
"""Certbot constants.""" import logging import os import pkg_resources from acme import challenges from certbot.compat import misc SETUPTOOLS_PLUGINS_ENTRY_POINT = "certbot.plugins" """Setuptools entry point group name for plugins.""" OLD_SETUPTOOLS_PLUGINS_ENTRY_POINT = "letsencrypt.plugins" """Plugins Setuptools...
#!/usr/bin/env python from __future__ import division #----------------------------------------------------------------------------- # Copyright (c) 2013, The BiPy Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this softw...
from copy import deepcopy as _deepcopy class GraphError(Exception): pass class Graph(object): def __init__(self, matrix, unconnected=0): self.vertex_num = len(matrix) _ = {len(row) for row in matrix} if len(_) != 1 or self.vertex_num not in _: raise IndexError sel...
from oslo_config import cfg __all__ = [ 'RUNNER_NAME_WHITELIST', 'MANIFEST_FILE_NAME', 'LOCAL_RUNNER_DEFAULT_ACTION_TIMEOUT', 'REMOTE_RUNNER_DEFAULT_ACTION_TIMEOUT', 'REMOTE_RUNNER_DEFAULT_REMOTE_DIR', 'REMOTE_RUNNER_PRIVATE_KEY_HEADER', 'PYTHON_RUNNER_DEFAULT_ACTION_TIMEOUT', 'PYTH...
# -*- coding: utf-8 -*- import json from requestor import Requestor from util.constants.facebook import REPLY_URL, WELCOME_TEXT class Replier(object): def __init__(self, access_token): self.access_token = access_token self.requestor = Requestor(REPLY_URL) def wit_send(self, request, response): recipient_id ...
"""Boardgame class""" class BoardGame(object): """Object containing information about a boardgame""" def __init__(self, data): self._data = data def __repr__(self): return("Boardgame(" + self.name + ")") def data(self): """Internal data dictionary""" retur...
import logging from functools import reduce from operator import or_ from collections import OrderedDict from django.shortcuts import get_object_or_404 from django.db.models import Subquery from rest_framework.renderers import JSONRenderer from rest_framework import viewsets, mixins from rest_framework.exceptions imp...
import os import stat import logging import subprocess import re import threading import tempfile import shutil from pexpect import EOF, TIMEOUT, spawn, pxssh from wlauto.exceptions import HostError, DeviceError, TimeoutError, ConfigError from wlauto.utils.misc import (which, strip_bash_colors, escape_single_quotes, ...
######################################### # mqttPubSubConfig.py # # by Kyle Clinton ######################################### ### # I am running Mosquitto on my main computer # I know Mosquitto is available for Mac and Linux, # but I am sure it is also available or Windows too ### from java.lang import String python =...
# -*- coding: utf-8 -*- """ `input` type question """ from __future__ import print_function, unicode_literals from prompt_toolkit.token import Token from prompt_toolkit.shortcuts import create_prompt_application from prompt_toolkit.validation import Validator, ValidationError from prompt_toolkit.layout.lexers import Si...
from zope.interface import implements from twisted.python.failure import Failure from feat.agents.base import replay from feat.common import log, defer, serialization, time from feat.agencies.interface import (IAgencyInitiatorFactory, ILongRunningProtocol) from feat.interface.seri...
# -*- coding: utf-8 -*- from django.db import models from monitoreo.monitoreo.models import * # Create your models here. # Indicador 15. Propiedades y Bienes CHOICE_AMBIENTE = ((1,"1"),(2,"2"),(3,"3"),(4,"4"),(5,"5")) CHOICE_TIPO_CASA = ((1,"Madera rolliza"),(2,"Adobe"),(3,"Tabla"), (4,"Minifald...
"""Tests for distributed training utils of the Actor/Learner API.""" from absl.testing import parameterized from absl.testing.absltest import mock import numpy as np import reverb import tensorflow as tf from tf_agents.system import system_multiprocessing as multiprocessing from tf_agents.train.utils import test_u...
from __future__ import absolute_import from Qpyl.core.qparameter import QPrm from Qpyl.core.qlibrary import QLib from Qpyl.core.qstructure import QStruct from Qpyl.core.qtopology import QTopology def is_close(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def te...
import base64 from collections import OrderedDict from asn1crypto.core import Sequence, OctetBitString, IA5String, Null from asn1crypto.keys import PublicKeyInfo from asn1crypto.algos import AlgorithmIdentifier from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, ...
import consolidated_invoice import wizard
from .fetchers import NUPerformanceMonitorsFetcher from .fetchers import NUMetadatasFetcher from .fetchers import NUAlarmsFetcher from .fetchers import NUGlobalMetadatasFetcher from .fetchers import NUSubnetsFetcher from bambou import NURESTObject class NUIKEGatewayConnection(NURESTObject): """ Represent...
import os import re import markdown from flask import Markup from config import GIT_REPO_DIR_PATH, ACCEPTED_FILE_FORMATS from gitmanager import git_update, check_local_repo # Global Config DATA_DIR_PATH = GIT_REPO_DIR_PATH FILE_DOT_MD_REGEX = ACCEPTED_FILE_FORMATS class DataStore(object): """ Class to ...
import matplotlib.pyplot as plt import chimera, numpy as np def ramaPlot(res_L, saveFilePath = ""): plt.ion() fig = plt.figure(figsize = (8,8)) ax = fig.add_subplot(111, aspect = 'equal') ax.set_title("2D Ramachandran Plot of ZIKA VIRUS PDB: " + saveFilePath, fontsize = 16) ax.set_xlabel...
""" OpenStack Call Tracing Tool To use this: 1. include the tools directory in your project (__init__.py and tracer.py) 2. import tools.tracer as early as possible into your module 3. add --trace-calls or -t to any argument parsers if you want the argument to be shown in the usage page Usage: Add this as early as pos...
from .config import DatabaseConfig from connection import DatabaseConnection from .database import ( AdminSpatialUnitSet, alchemy_table, alchemy_table_relationships, Base, Content, Enumerator, Model, Respondent, Role, STDMDb, Survey, table_mapper, table...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import random, time from PIL import Image, ImageTk from Tkinter import Tk, Frame, Canvas, ALL, NW WIDTH = 300 HEIGHT = 300 DELAY = 100 DOT_SIZE = 10 ALL_DOTS = WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE) RAND_POS = 27 RESIZE = 5, 5 x = [0] * ALL_DOTS y = [0] * ALL_DO...
import os from mi.logging import config from mi.core.log import get_logger from mi.core.exceptions import NotImplementedException __author__ = 'wordenm' log = get_logger() class ParticleDataHandler(object): def __init__(self): self._samples = {} self._failure = False def addParticleSample(...
import os from samba.tests.samba_tool.base import SambaToolCmdTest import shutil class GpoCmdTestCase(SambaToolCmdTest): """Tests for samba-tool time subcommands""" gpo_name = "testgpo" def test_gpo_list(self): """Run gpo list against the server and make sure it looks accurate""" (result,...
"""Template demonstrating how to create examples for PyNEST ---------------------------------------------------------------- [[ Titles should be one line and state what the example does. It should begin with a verb in the present tense and include type of model and/or method]] [[ Extended summary - a detailed expl...
import asyncio import gc import logging import re import time import redis from stratus.event import Event, CommandHookEvent, RegexHookEvent, EventType from stratus.irc.client import IRCClient from stratus.loader.pluginloader import Loader logger = logging.getLogger("bot") def clean_name(n): """strip all space...
import os import json def check_directory(output_directory): try: os.stat(output_directory) except Exception: os.mkdir(output_directory) print("[!] %s didn't exist and has been created." % output_directory) def load_targets(target_hosts, output_directory, quiet): if (os.path.isdi...
from base.models import session_exam def create_session_exam(number_session, learning_unit_year, education_group_year): a_session_exam = session_exam.SessionExam(number_session=number_session, learning_unit_year=learning_unit_year, ...
# -*- coding: utf-8 -*- def tolocstr(localstr): if (localstr in ['en_US','en-US','en','enus','EN-US','english','English','US']): return 'en_US' elif (localstr in ['pt_BR','pt-BR','pt','ptbr','PT-BR','portuguese','Portuguese','Portugues','PT']): return 'pt_BR' elif (localstr in ['de_DE','de-D...
"""Tests for projectq.ops._basics.""" import math import numpy as np import pytest from projectq.types import Qubit, Qureg from projectq.ops import Command, X from projectq import MainEngine from projectq.cengines import DummyEngine from projectq.types import WeakQubitRef from projectq.ops import _basics @pytest....
import hashlib import logging import sys from pathlib import Path from datetime import datetime from Pegasus.api import * logging.basicConfig(level=logging.DEBUG) PEGASUS_LOCATION = "/usr/bin/pegasus-keg" # --- Work Dir Setup ----------------------------------------------------------- RUN_ID = "black-diamond-integ...
""" Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, yo...
""" Custom-written perl inline shellcode injector Approach by @the_grayhound and @christruncer Updated by @ChrisTruncer """ from tools.evasion.evasion_common import evasion_helpers from tools.evasion.evasion_common import gamemaker from tools.evasion.evasion_common import shellcode_help class PayloadModule: de...
""" example_fit_data ---------------- This example demonstrates BurnMan's functionality to fit various mineral physics data to an EoS of the user's choice. Please note also the separate file example_fit_eos.py, which can be viewed as a more advanced example in the same general field. teaches: - least squares fittin...
import hashlib import pkg_resources from xml.dom import minidom import xml.etree.ElementTree as XML from jenkins_jobs import errors __all__ = [ "XmlJobGenerator", "XmlJob" ] def remove_ignorable_whitespace(node): """Remove insignificant whitespace from XML nodes It should only remove whitespace in ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest from caffe2.python import workspace, brew, model_helper from caffe2.python.modeling.compute_histogram_for_blobs import ( ComputeHistogramForBlobs ) i...
import mock from rally.benchmark.context.quotas import neutron_quotas as quotas from tests.unit import test class NeutronQuotasTestCase(test.TestCase): @mock.patch("rally.benchmark.context.quotas.quotas.osclients.Clients") def test_update(self, client_mock): neutron_quotas = quotas.NeutronQuotas(cli...
import unittest import sys from unittest import mock sys.modules['pyglet'] = mock.Mock() class MockWindow(object): clear = mock.Mock() import pyglet pyglet.window.Window = MockWindow from pycomponents.core import World, Entity from pycomponents.pyglet import PygletGame, RenderingSystem class TestPygletWrappe...
from Plugins.Plugin import PluginDescriptor from Components.PluginComponent import plugins import os from mimetypes import guess_type, add_type add_type("audio/dts", ".dts") add_type("audio/mpeg", ".mp3") add_type("audio/x-wav", ".wav") add_type("audio/x-wav", ".wave") add_type("audio/ogg", ".oga") add_type("audio/og...
# Django settings for project project. import os.path HERE = os.path.abspath(os.path.join(os.path.dirname(__file__))) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { # Sometimes, you don't need a database for a shareabou...
import gst import gst.interfaces from twisted.internet import defer from flumotion.common import messages from flumotion.common.i18n import N_, gettexter from flumotion.component import feedcomponent from flumotion.component.effects.volume import volume __version__ = "$Rev$" T_ = gettexter() class Soundcard(feedco...
import numpy as np def iter_loadtxt(filename, delimiter=',', skiprows=0, dtype=float, cols=None, maxlength=None): def iter_func(): with open(filename, 'r') as infile: for _ in range(skiprows): next(infile) for line in infile: line = line.rstrip().spli...
import superdesk from superdesk.errors import ProviderError class AddProvider(superdesk.Command): """Add ingest provider.""" option_list = { superdesk.Option('--provider', '-p', dest='provider'), } def run(self, provider=None): if provider: try: ...
from . import Job, call class PBSJob(Job): """ A job subclass for running tasks on a PBS queue. """ def __init__(self, alias, command, depends_on=[], queue='work'): super(PBSJob, self).__init__(alias, command, depends_on) self.queue = queue self.id = None self.waiting = True ...
import numpy as np import sys from random import randint import torch import torch.nn as nn from torch.autograd import Variable from scipy.io import loadmat from scipy.io import savemat mat = loadmat('./cache/script2.mat') codeJ = mat['codeJ'] dim_voc = 539 bsz = 1 dim_h = 100 dim_cate_new = 19 dim_color = 17 dim_gend...
# coding=utf-8 """ Created on 18 January 2014 @author: Cenk Bircanoglu """ import operator from similarityPy.measure.similarity_measure import SimilarityMeasure from similarityPy.measure.similarity_measure_type import SimilarityMeasureType class DiceDissimilarity(SimilarityMeasure): similarity_measure_type = Sim...
""" Support for Roller shutters. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/rollershutter/ """ import os import logging import voluptuous as vol from homeassistant.config import load_yaml_config_file from homeassistant.helpers.entity_component impo...
import distutils.version import glob import logging import os import shutil import subprocess import test_runner_errors LOGGER = logging.getLogger(__name__) XcodeIOSSimulatorDefaultRuntimeFilename = 'iOS.simruntime' XcodeIOSSimulatorRuntimeRelPath = ('Contents/Developer/Platforms/' ...
import functools import six import falcon from oslo_config import cfg from oslo_log import log as logging from oslo_policy import policy from deckhand import errors from deckhand import policies CONF = cfg.CONF LOG = logging.getLogger(__name__) _ENFORCER = None def reset(): global _ENFORCER if _ENFORCER: ...
# -*- coding:utf-8 -*- from numpy import * import operator import matplotlib.pyplot as plt #page17 def creatDataSet(): group=array([[1,1.1],[1,1],[0,0],[0,1]]) labels=['A','A','B','B'] return group,labels #page19 def classify0(inX,dataSet,labels,k): dataSetSize=dataSet.shape[0] diffMat=tile(inX,(dataSetSize,1...
from __future__ import unicode_literals from django.db import models from base.models import (TimeStampedModel, ) class Contact(TimeStampedModel): """Model representing details of User submitting queries.""" name = models.CharField(max_length=100,) email = models.EmailField(max_length=70,) message =...