content
stringlengths
4
20k
"""Generate Blink C++ bindings (.h and .cpp files) for use by Dart:HTML. If run itself, caches Jinja templates (and creates dummy file for build, since cache filenames are unpredictable and opaque). This module is *not* concurrency-safe without care: bytecode caching creates a race condition on cache *write* (crashes...
""" Locates imports that violate cirq's submodule dependencies. Specifically, this test treats the modules as a tree structure where `cirq` is the root, each submodule is a node and each python file is a leaf node. While a node (module) is in the process of being imported, it is not allowed to import nodes for the fi...
import re from warnings import warn from contextlib import suppress import numpy as np import pandas as pd from ..exceptions import PlotnineError, PlotnineWarning from ..utils import match, join_keys from .facet import facet, combine_vars, layout_null from .facet import add_missing_facets, eval_facet_vars from .strip...
import time, pytz, os from base64 import b64encode from django.http import HttpResponse, JsonResponse from django.core.files.storage import FileSystemStorage from django.utils.translation import ugettext from django.views.decorators.csrf import csrf_exempt from django.utils import timezone from pa3_web.models import...
#!/bin/env python # -*- coding: utf-8 -*- from Sire.Mol import * from Sire.IO import * from Sire.Vol import * from Sire.FF import * from Sire.MM import * from Sire.Maths import * from Sire.Qt import * from Sire.Units import * from Sire.System import * from Sire.Move import * t = QTime() wate...
# -*- coding: utf-8 -*- import pytest import resolvedeps def create_dag(): """ This is the test graph, taken from: https://en.wikipedia.org/wiki/Topological_sorting#Examples Imagine the edges all having downward pointing arrows. 5 7 3 | / \ / | 11 8 | | \ \__|__ | ...
from couchbase.exceptions import NotFoundError, ArgumentError, TimeoutError from couchbase.tests.base import MockTestCase class EndureTest(MockTestCase): #XXX: Require LCB 2.1.0 def test_excessive(self): self.assertRaises(ArgumentError, self.cb.set, ...
assert str is not bytes import sys import threading import queue TK_PULL_DELAY = 100 # milliseconds DESTROY = object() # this is Multi-Thread support for Tk class TkMt: def __init__(self, root): self._root = root self._queue = queue.Queue() self._closed = False self._roo...
#!/tps/bin/python import mpcsutil from string import * import sys, re from datetime import datetime def jpl_time_to_mysql_time(jplt): date_s = "" if jplt == "": dt = datetime.datetime.now() mtime = dt.strftime("%Y-%m-%d %H:%M:%S") return mtime if jplt.find("T") != -1 and...
from __future__ import print_function import sys import re def parse_file(fn, cl, tl, sl): p = False section = "" resec = re.compile("[ /]\* SECTION: ") f = open(fn, "r") for l in f: if "*/" in l: p = 0 if resec.match(l): a = l.split() section = a[2] sl.append(section) cl[section] = [] if...
# -*- 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 'Post.filtering_result' db.add_column('feedjack_post', 'filtering_result', ...
from odoo import api, fields, models, _ class Company(models.Model): _inherit = 'res.company' leave_timesheet_project_id = fields.Many2one( 'project.project', string="Internal Project", help="Default project value for timesheet generated from time off type.") leave_timesheet_task_id = fie...
import json import os import gql import voxjar.auth from voxjar.push_request import PushRequest from voxjar.transport import HttpTransport class Client(object): """Voxjar API client. Args: url (str, optional): The URL for the API. token (str, optional): The JWT authenticating this Client to ...
#coding=UTF-8 from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext from pyspark.sql.types import * from datetime import date, datetime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_A_D004_SCORE_DETAIL').setMaster(sys.argv[2]) sc = SparkContext(conf = conf) s...
from config import config, ConfigSlider, ConfigSelection, ConfigYesNo, \ ConfigEnableDisable, ConfigSubsection, ConfigBoolean, ConfigSelectionNumber, ConfigNothing, NoSave from enigma import eAVSwitch, getDesktop from SystemInfo import SystemInfo import os class AVSwitch: def setInput(self, input): INPUT = { "ENCO...
from time import localtime, mktime, time, strftime from enigma import eEPGCache, eTimer, eServiceReference, ePoint from Screens.Screen import Screen from Screens.TimerEdit import TimerSanityConflict from Screens.ChoiceBox import ChoiceBox from Components.ActionMap import ActionMap from Components.Button import Button...
"""Check every 'TODO' declared in comments have an owner assigned""" # pylint: disable=W0511 import re import six from pylint.interfaces import IRawChecker from pylint.checkers import BaseChecker MSGS = { 'W9000': ('todo has no owner: \"%s\"', 'unowned-todo', 'Used to indicate when...
import unittest import zof.exception as _exc class ExceptionTestCase(unittest.TestCase): def test_timeout(self): ex = _exc.TimeoutException(1, 5) self.assertEqual(ex.xid, 1) self.assertEqual(ex.timeout, 5) self.assertEqual(ex.message, '') self.assertEqual(str(ex), '[Timeout...
import os import fiona from pyproj import Proj from vistas.core.gis.extent import Extent from vistas.core.plugins.data import FeatureDataPlugin, VariableStats, TemporalInfo class Shapefile(FeatureDataPlugin): id = 'shapefile' name = 'Shapefile Data Plugin' description = 'A plugin to read shapefiles (.s...
__doc__ = """generate_resource_whitelist.py [-o OUTPUT] INPUTS... INPUTS are paths to unstripped binaries or PDBs containing references to resources in their debug info. This script generates a resource whitelist by reading debug info from INPUTS and writes it to OUTPUT. """ # Whitelisted resources are identified by...
# coding=utf-8 import os import xmltodict from .session import Session from .report import Host, Report from .vulnerability import Vulnerability class Nessus(object): def __init__(self, user, pw, host='localhost', port=8834, verifySSL=True): """Create a session and make it the active one""" self....
import pytest import sys import os import traceback import random import time import json import Queue from twisted.application import service, internet from twisted.python.log import ILogObserver from twisted.internet import reactor, task, defer, threads from threading import Thread from kademlia import log from cal...
#!/usr/bin/python # -*- coding: utf-8 -*- import pymysql read = open('mysql_conf.properties', 'r') host = read.readline().strip('\n') user = read.readline().strip('\n') password = read.readline().strip('\n') db = read.readline().strip('\n') read.close() def insert_blog(sql, blog_id, status, text): conn = pymysq...
#!/usr/bin/env python3 import re import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse from core.parser import Parser from core.display import Display, ProgressBar class Gather(): def __init__(self, domain, display=None): self.domain = domain self.disp...
from datetime import datetime, timedelta from celery.task import periodic_task, task from corehq.apps.reminders.models import (CaseReminderHandler, CaseReminder, CASE_CRITERIA) from django.conf import settings from dimagi.utils.logging import notify_exception from casexml.apps.case.models import CommCareCase from d...
from wpilib import Joystick, Timer class XboxController(object): """ Allows usage of an Xbox controller, with sensible names for xbox specific buttons and axes. """ def __init__(self, port): """ :param port: The port on the driver station that the controller is ...
import logging import os from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def count_trainable_parameters(model): mo...
""" Utilities to process parametric job definitions and generate bunches of parametric jobs. It exposes the following functions: getParameterVectorLength() - to get the total size of the bunch of parametric jobs generateParametricJobs() - to get a list of expanded descriptions of all the jobs """ __RCSID_...
from typing import Any, Mapping, Optional, cast from flask import current_app from eduid_common.api.app import EduIDBaseApp from eduid_common.authn.utils import no_authn_views from eduid_common.config.base import FlaskConfig from eduid_common.config.parsers import load_config from eduid_webapp.jsconfig.settings.comm...
from __future__ import print_function, division, absolute_import import math import os from toolz import identity from ..compatibility import PY2 # Ideally this function should be defined in this file, but old versions of # distributed rely on it being in dask.utils. We can't define it here and # import it there du...
import os import time import sys import matplotlib import re from optparse import OptionParser, OptionValueError import numpy as np import matplotlib.pyplot as plt import scipy.linalg def sw(x, eps): if (x < - eps): return 0 return 0.5 * (x + eps) - eps / np.pi * np.cos(0.5 * np.pi * x / eps) def yie...
""" SPL type definitions. ******** Overview ******** SPL is strictly typed, thus when invoking SPL operators using classes from ``streamsx.spl.op`` then any parameters must use the SPL type required by the operator. """ from future.builtins import * import collections import datetime import time import streamsx.spl...
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) with open('user.txt','r') as u: for line in u: usrnm=line usrnm=usrnm.rstrip('\n') with open('pass.txt','r') as p: for line in p: ...
import xbmc import xbmcplugin import xbmcaddon import xbmcgui import urllib import urllib2 import re import sys import os import time import socket from StringIO import StringIO import gzip module_log_enabled = False http_debug_log_enabled = False LIST = "list" THUMBNAIL = "thumbnail" MOVIES = "movies" TV_SHOWS = "t...
from optparse import OptionParser from ConfigParser import ConfigParser import base64 import logging import os import time from vc3client.client import VC3ClientAPI if __name__ == '__main__': logging.basicConfig() log = logging.getLogger() log.setLevel(logging.INFO) parser = OptionParser(usage='%pr...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import configargparse import uuid import os import json from datetime import datetime, timedelta import logging import shutil import requests import platform from . import config log = logging.getLogger(__name__) def parse_unicode(bytestring): decoded_string...
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'myGates.views.home_view'), url(r'^login/$', 'myGates.views.loginview'), url(r'^a...
from telemetry.perf_tests_helper import FlattenList from telemetry.util import statistics from telemetry.value import list_of_scalar_values from telemetry.value import scalar from telemetry.web_perf.metrics import rendering_stats from telemetry.web_perf.metrics import timeline_based_metric class SmoothnessMetric(time...
#!/usr/bin/env python import vim __all__ = [ 'read', 'readlines', 'getbuffer', ] def getbuffer(fpath): """ Return bufer number of fpath, fpath should be a full path of a file. """ for buf in vim.buffers: if buf.name == fpath: return buf else: return None def read(file_path)...
""" Django settings for prikmeter_server project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ imp...
"""Check how Qt behaves when trying to execute JS.""" import pytest @pytest.mark.parametrize('js_enabled, expected', [(True, 2.0), (False, None)]) def test_simple_js_webkit(webview, js_enabled, expected): """With QtWebKit, evaluateJavaScript works when JS is on.""" # If we get there (because of the webview ...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( clean_html, qualities, ) class ClubicIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?clubic\.com/video/(?:[^/]+/)*video.*-(?P<id>[0-9]+)\.html' _TESTS = [{ 'url': 'http://www....
import unittest from models import model class test_Rooms(unittest.TestCase): """ Testing strategy partitioons: name -> len(name) -> 0 , postive, -> name : whitespace, str(number), asscii charcters -> name : duplicates --> bad types max_population -...
from ckantoolkit import _ import json from ckanext.scheming.validation import scheming_validator import logging logger = logging.getLogger(__name__) import ckan.lib.navl.dictization_functions as df StopOnError = df.StopOnError def envidat_shortname_validator(key, data, errors, context): value = data.get(key) ...
"""Support automatic deprecation and obsoletion of parsec config items.""" from logging import DEBUG, WARNING from cylc.flow import LOG from cylc.flow.parsec.exceptions import UpgradeError from cylc.flow.parsec.OrderedDict import OrderedDict class converter: """Create custom config value converters.""" def...
import os import random import string import types from hashlib import sha1 import logging; from django.core.cache import cache log = logging.getLogger(__name__) def gen_random(n=8): return ''.join(random.choice(string.ascii_uppercase) for x in range(n)) class UUIDLogMiddleware(object): def process_request(...
import pymongo import bottle import cgi import re import dictionaryDAO from flask import json from bottle import route, request from bson import json_util from bson.json_util import dumps from bottle import static_file __author__ = 'Sagar Gugwad' # This program implements a restful api to return synonyms for a wor...
import asyncio import weakref import warnings from .pl import PL from .ps import CPU_ARCH, ZU_ARCH, ZYNQ_ARCH from .mmio import MMIO from .uio import get_uio_device, UioController __author__ = "Peter Ogden" __copyright__ = "Copyright 2017, Xilinx" __email__ = "<EMAIL>" def get_uio_irq(irq): """Returns the UIO de...
from lxml import etree from odoo import models, api from odoo.tools.translate import encode, xml_translate, html_translate def edit_translation_mapping(data): data = dict(data, model=data['name'].partition(',')[0], value=data['value'] or data['src']) return '<span data-oe-model="%(model)s" data-oe-translatio...
from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_array_almost_equal, assert_ from scipy.sparse import csr_matrix, csc_matrix import pytest def test_csc_getrow(): N = 10 np.random.seed(0) X = np.random.random((N, N)) X[X > 0.7] = 0 ...
#Apache OCW lib immports import ocw.data_source.local as local import ocw.plotter as plotter import ocw.utils as utils from ocw.evaluation import Evaluation import ocw.metrics as metrics # Python libraries import numpy as np import numpy.ma as ma import matplotlib.pyplot as plt from mpl_toolkits.basemap imp...
''' SASSIE: Copyright (C) 2011 Joseph E. Curtis, Ph.D. 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. ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # __author__ = 'maximus' """ For Dlink DES-3028, DES-3528, DES-3552, DGS-3426G, DGS-3627G Get config: upload config to tftp server Transport: telnet """ import logging import time from protocols.telnet import Telnet import re import pexpect class Dlink(Telnet): de...
""" Support for ThinkingCleaner. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.thinkingcleaner/ """ import time import logging from datetime import timedelta import homeassistant.util as util from homeassistant.const import (STATE_ON, STATE_OFF...
import unittest import ccs import time #################################################################################################################### # BTCE # ##############################################...
import os import re from setuptools import find_packages from setuptools import setup BASE_NAME = 'ceda_opensearch' V_FILE = open(os.path.join(os.path.dirname(__file__), BASE_NAME, '__init__.py')) README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() VERSION = re.c...
"""A evaluation framework using distributed strategy.""" import os from absl import app from absl import flags import gin.tf import train_eval_lib_local flags.DEFINE_enum('mode', None, ['cpu', 'gpu'], 'Distributed strategy approach.') flags.DEFINE_string('checkpoint_path', None, 'Path to checkpoint...
# * * # * If you have any questions about the licensing restrictions on using * # * Nmap in other works, are happy to help. As mentioned above, we also * # * offer alternative license to integrate Nmap into proprietary * # * appl...
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 2 of the License, or (at your option) any la...
"""Tests for Calibrator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from six.moves import range from tensorflow.lite.python import lite_constants as constants from tensorflow.lite.python.opt...
""" Provides typed unmarshaller classes. """ from logging import getLogger from suds import * from suds.umx import * from suds.umx.core import Core from suds.resolver import NodeResolver, Frame from suds.sudsobject import Factory log = getLogger(__name__) # # Add typed extensions # type = The expected xsd type # re...
from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class GetWordList(Choreography): def __init__(self, temboo_session): """ Create a n...
from django.test import TestCase from accounts.utils import bootstrap_permissions from accounts.models import ROLE_PARTNER, ROLE_MANAGER from accounts.tests.factories import CtsUserFactory from catalog.tests.factories import DonorFactory from reports.filters import PackageReportFilter, DonorByShipmentReportFilter, \ ...
""" 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/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
# -*- coding: utf-8 -*- """Unit test for the measurementset module.""" import os import time import shutil import tempfile import unittest import numpy from data_models.memory_data_models import Configuration from data_models.polarisation import ReceptorFrame from astropy.coordinates import EarthLocation try: ...
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import logging import multiprocessing import os import time from datetime import timedelta from django.core.management.base import BaseCommand from django.db import close_old_connections, connections, reset_queries fr...
import wx from cairis.core.armid import * import cairis.gui.WidgetFactory __author__ = 'Shamal Faily' class NewEnvironmentDialog(wx.Dialog): def __init__(self,parent): wx.Dialog.__init__(self,parent,NEWENVIRONMENT_ID,'New Environment',style=wx.DEFAULT_DIALOG_STYLE|wx.MAXIMIZE_BOX|wx.THICK_FRAME|wx.RESIZE_BORDER...
import unittest from mock import patch from pybuilder.plugins.python.core_plugin import init_python_directories from pybuilder.plugins.python.core_plugin import (DISTRIBUTION_PROPERTY, PYTHON_SOURCES_PROPERTY, SCRIPTS_...
''' This test file exercises the code in sources DataSourceAltCloud.py ''' import os import shutil import tempfile from cloudinit import helpers from cloudinit import util from unittest import TestCase # Get the cloudinit.sources.DataSourceAltCloud import items needed. import cloudinit.sources.DataSourceAltCloud fro...
from neutron.agent.linux import of_monitor from neutron.common import utils from neutron.tests.common import net_helpers from neutron.tests.functional import base as functional_base class OFMonitorTestCase(functional_base.BaseSudoTestCase): DEFAULT_FLOW = {'table': 0, 'cookie': '0', 'actions': 'NORMAL'} def...
__author__ = "Luke" import numpy as np import time import httplib, urllib from pprint import pprint import os SERVER_UPDATE_LIMIT = 16 MAX_RETRIES = 25 lastSentList = {} def uploadData(data, APIKey): try: lastSent = lastSentList[APIKey] if ((time.time() - lastSent) < SERVER_UPDATE_LIMIT): ...
# # Cython - Compilation-wide options and pragma declarations # # Perform lookups on builtin names only once, at module initialisation # time. This will prevent the module from getting imported if a # builtin name that it uses cannot be found during initialisation. cache_builtins = True embed_pos_in_docstring = Fal...
from peewee import CharField, IntegerField, FloatField, ForeignKeyField, DateTimeField from database import SyncModel from customer import Customer,CustomerTag from product import ProductBrand,ProductCategory,Product class CustomerSalePointProgrammeRule(SyncModel): odoo_id = IntegerField(unique=True) name = C...
import pymake.data, pymake.parser, pymake.parserdata, pymake.functions import unittest import logging def multitest(cls): for name in cls.testdata.keys(): def m(self, name=name): return self.runSingle(*self.testdata[name]) setattr(cls, 'test_%s' % name, m) return cls class TestBa...
from _base import base # Helper class to ease the inclusion of scipy.optimize solvers. class _scipy_base(base): def __init__(self,solver_name,constrained): base.__init__(self) try: exec('from scipy.optimize import %s as solver' % solver_name) from numpy import concatenate, array except ImportError: rai...
"""hug/use.py Provides a mechanism for using external hug APIs both locally or remotely in a seamless fashion Copyright (C) 2016 Timothy Edmund Crosley 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 the So...
from io import BytesIO from decimal import Decimal, getcontext getcontext().prec = 36 import pytest from pyhdb.protocol import types # ########################## Test value unpacking ##################################### @pytest.mark.parametrize("input,expected", [ (b"\x01\x15\xCD\x5B\x07", 123456789), (b"\...
"""Tests for `maasserver.regiondservices.ntp`.""" from crochet import wait_for from testtools.matchers import AllMatch, Equals, IsInstance, MatchesStructure from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from maasserver.models.config import Config from maasserver.regiondservi...
""" This module provides simple session handling and WSGI Middleware. You should instantiate SessionStore, and pass it to WSGI middleware along with next WSGI application in chain. Example: >>> environ = {} >>> >>> def my_start_response(status, headers): ... environ['HTTP_COOKIE'] = headers[0][1] ... >>> def my_app...
import argparse import time import os import json import gettext # Import external modules # Import internal modules from fabtotum.development.templating import create_from_template, create_dir, create_link, build_path # Set up message catalog access tr = gettext.translation('fab_creator', 'locale', fallback=True) _...
"""This example lists all creative groups.""" import argparse import sys from apiclient import sample_tools from oauth2client import client # Declare command-line flags. argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument( 'profile_id', type=int, help='The ID of the profile to get crea...
import os import logging import unittest import argparse logLevels = {0: logging.CRITICAL + 1, 1: logging.CRITICAL, 2: logging.CRITICAL, 3: logging.WARNING, 4: logging.INFO, 5: logging.DEBUG} def configureLogging(verbosity): logger = logging.getLog...
from sugar3 import logger logger.cleanup() logger.start('shell') import logging logging.debug('STARTUP: Starting the shell') import os import sys import subprocess import shutil # Disable overlay scrolling before GTK is loaded os.environ['GTK_OVERLAY_SCROLLING'] = '0' os.environ['LIBOVERLAY_SCROLLBAR'] = '0' impo...
#!/usr/bin/env python # # Raspberry Pi Robot Costume ''' In this project, we're making a Raspberry Pi Robot Costume. The costume will count candy placed in a bin, and speak out loud to the giver. Well use the GrovePi, with an Ultrasonic Sensor, an LED Bar graph, 4 Chainable LED's, and the RGB LCD Display. We'll also ...
import os from pdb import pm from miasm2.analysis.sandbox import Sandbox_Win_x86_32 from miasm2.os_dep import win_api_x86_32_seh from miasm2.jitter.csts import * def deal_exception_access_violation(jitter): jitter.pc = win_api_x86_32_seh.fake_seh_handler(jitter, win_api_x86_32_seh.EXCEPTION_ACCESS_VIOLATION) r...
# encoding: 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 'CodeSnippet' db.create_table('canvas_codesnippet', ( ('id', self.gf('django.db...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by mqingyn on 2015/1/15. """ tornado task manager """ import datetime, time, functools from tornado.options import define, options, parse_command_line from tornado.log import app_log from tornado.ioloop import PeriodicCallback, IOLoop define("tasks", default=Non...
""" Higher order classes for Libvirt Sandbox Service (lxc) service container testing """ from avocado.utils import process from avocado.utils import service from . import lvsb_base from . import virsh from .compat_52lts import results_stdout_52lts class SandboxService(object): """ Management for a single n...
from oslo_db.sqlalchemy import utils INDEXES = [ ('block_device_mapping', 'snapshot_id', ['snapshot_id']), ('block_device_mapping', 'volume_id', ['volume_id']), ('dns_domains', 'dns_domains_project_id_idx', ['project_id']), ('fixed_ips', 'network_id', ['network_id']), ('fixed_ips', 'fixed_ips_inst...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from mock import MagicMock, patch import os import subprocess from uiautomator.adb import Adb class TestAdb(unittest.TestCase): def setUp(self): self.os_name = os.name def tearDown(self): os.name = self.os_name def test_seri...
import numpy as np import nltk from tqdm import tqdm import pickle import math import os import random from cornell_data import CornellData from batch import Batch # Monkey patch math.isclose for Python <3.5 if not hasattr(math, 'isclose'): math.isclose = lambda a, b, rel_tol=1e-09, abs_tol=0.0: \ abs(a - b) <= ma...
#!/usr/bin/env python # coding: utf-8 import os import sys import logging import argparse import collections from sear.lexicon import DictLexicon logging.basicConfig(level=logging.INFO) arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-t", "--test", type=int, choices=(0, 1), default=0) arg_parser....
import os import validators from celery.result import AsyncResult from flask import Blueprint, jsonify, current_app, abort from flask import request from werkzeug.utils import secure_filename from app.views import process api = Blueprint('api', __name__, url_prefix='/api/v2') TASK_RESULTS = {} @api.route('/app/<s...
""" mac.py Created by Thomas Morin on 2014-06-23. Copyright (c) 2014-2015 Orange. All rights reserved. """ from exabgp.protocol.ip import IP from exabgp.bgp.message.update.nlri.qualifier.rd import RouteDistinguisher from exabgp.bgp.message.update.nlri.qualifier.labels import Labels from exabgp.bgp.message.update.nlri...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Run with nosetests test_dd_data.py -s -v """ import sys sys.path.append('..') from nose.tools import * import os import subprocess import shutil import numpy as np import pandas as pd from sip_models.res.cc import cc import sip_formats.convert as sip_converter from c...
from setuptools import setup,find_packages with open('fabric_powershell/version.py') as fin: exec(fin) setup( name='fabric-powershell', version=__version__, packages=find_packages(exclude=['tests*']), # dependencies install_requires=['fabric'], # PyPI MetaData author='Adam Kerz...
""" We want to limit the size of position we can take, both for a given strategy and across strategies When we want to trade (create an instrument / strategy order) we check that the new net position for that instrument (for the strategy, and across all strategies) doesn't exceed any limits """ from syscore.objec...
import os import io import datetime import json import pytest import mongomock import pymongo # NOTE: Can't do normal import since name contains hyphen. script = __import__('six-scraper') # Test data, utilities and fixtures RAW_DATA = """ABB LTD N (ABBN/CH0012221716) 29.07.2014; Time;Price;Vol...
import six from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest.lib import exceptions as lib_exc from ironic_tempest_plugin.common import waiters from ironic_tempest_plugin.tests.api.admin import api_microversion_fixture from ironic_tempest_plugin....
#!/usr/bin/env python import socket import sys import paho.mqtt.client as mqtt import time import datetime import logging logging.basicConfig(filename='led_strip_mqtt.log', level=logging.WARN) # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, r...