content
stringlengths
4
20k
from django.db import connection, models from .fields import ( ArrayField, BigIntegerRangeField, DateRangeField, DateTimeRangeField, FloatRangeField, HStoreField, IntegerRangeField, JSONField, ) class PostgreSQLModel(models.Model): class Meta: abstract = True required_db_vendor = 'postgre...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.cache import BaseCacheModule class CacheModule(BaseCacheModule): def __init__(self, *args, **kwargs): self.empty = {} def get(self, key): return self.empty.get(key) def set(self, ...
"""A more or less complete user-defined wrapper around list objects.""" import collections class UserList(collections.MutableSequence): def __init__(self, initlist=None): self.data = [] if initlist is not None: # XXX should this accept an arbitrary sequence? if typ...
from Symtab import ModuleScope from PyrexTypes import * from UtilityCode import CythonUtilityCode from Errors import error from Scanning import StringSourceDescriptor import MemoryView class CythonScope(ModuleScope): is_cython_builtin = 1 _cythonscope_initialized = False def __init__(self, context): ...
from .mininode import * from .script import CScript, OP_TRUE, OP_CHECKSIG # Create a block (with regtest difficulty) def create_block(hashprev, coinbase, nTime=None): block = CBlock() if nTime is None: import time block.nTime = int(time.time()+600) else: block.nTime = nTime bloc...
from spack import * class RDorng(RPackage): """Provides functions to perform reproducible parallel foreach loops, using independent random streams as generated by L'Ecuyer's combined multiple-recursive generator [L'Ecuyer (1999), <doi:10.1287/opre.47.1.159>]. It enables to easily conve...
import unittest from mock import MagicMock, ANY from collections import defaultdict from boto.dynamodb2.items import Item from flotilla.db import DynamoDbLocks from flotilla.scheduler.scheduler import FlotillaScheduler from flotilla.scheduler.db import FlotillaSchedulerDynamo SERVICE = 'test' REVISION = 'rev1' REVISIO...
""" CNAME Lookup Middleware Middleware that translates an unknown domain in the host header to something that ends with the configured storage_domain by looking up the given domain's CNAME record in DNS. This middleware will continue to follow a CNAME chain in DNS until it finds a record ending in the configured stor...
#!/usr/bin/python import sys import paramiko import cmd import re from subprocess import Popen from threading import Thread from time import sleep import os class iperfNode(object): def __init__(self, host, user, pwd): self.host = host self.user = user self.pwd = pwd self.chan = None self.conn = None se...
import os import sys from distutils.command.build import build as old_build from distutils.util import get_platform from numpy.distutils.command.config_compiler import show_fortran_compilers class build(old_build): sub_commands = [('config_cc', lambda *args: True), ('config_fc', lambda...
import mock from nova.scheduler.filters import aggregate_instance_extra_specs as agg_specs from nova import test from nova.tests.unit.scheduler import fakes @mock.patch('nova.scheduler.filters.utils.aggregate_metadata_get_by_host') class TestAggregateInstanceExtraSpecsFilter(test.NoDBTestCase): def setUp(self):...
# -*- coding: utf-8 -*- import six import logging from importlib import import_module from sqlalchemy import create_engine def multidb_binds(databases, package=None, engine_params=None): '''Creates dictionary to be passed as `binds` parameter to `sqlalchemy.orm.sessionmaker()` from dictionary mapping models m...
from ..relocation import Relocation from ...errors import CLEError from .. import Backend class ThreadManager: """ This class tracks what data is thread-local and can generate thread initialization images Most of the heavy lifting will be handled in a subclass """ def __init__(self, loader, arch, ...
from test.test_json import PyTest, CTest # 2007-10-05 JSONDOCS = [ # http://json.org/JSON_checker/test/fail1.json '"A JSON payload should be an object or array, not a string."', # http://json.org/JSON_checker/test/fail2.json '["Unclosed array"', # http://json.org/JSON_checker/test/fail3.json '{...
# Run the _testcapi module tests (tests for the Python/C API): by defn, # these are all functions _testcapi exports whose name begins with 'test_'. import os import pickle import random import subprocess import sys import time import unittest from test import support from test.support import MISSING_C_DOCSTRINGS try:...
#!/usr/bin/python import hashlib import operator import os import shutil import stat import subprocess import sys import tempfile def rel_to_abs(rel_path): return os.path.join(script_path, rel_path) java_bin_path = os.getenv('JAVA_HOME', '') if java_bin_path: java_bin_path = os.path.join(java_bin_path, 'bi...
from urllib.parse import parse_qs from .exposition import _bake_output from .registry import REGISTRY def make_asgi_app(registry=REGISTRY): """Create a ASGI app which serves the metrics from a registry.""" async def prometheus_app(scope, receive, send): assert scope.get("type") == "http" # P...
import gc from PyQt4.QtCore import * from PyQt4.QtGui import * from tortoisehg.hgqt import run import dbgutil, infobar, widgets class DebugMenuActions(dbgutil.BaseMenuActions): """Set up top-level debug menu""" def _setupMenu(self, menu): if self._workbench(): m = menu.addMenu('&InfoBar...
"""Unit tests for layout functions.""" import sys from nose import SkipTest from nose.tools import assert_equal import networkx as nx class TestLayout(object): numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test @classmethod def setupClass(cls): global numpy try: ...
from distutils import cygwinccompiler from distutils import extension from distutils import util import errno import os import os.path import pkg_resources import platform import re import shlex import shutil import sys import sysconfig import setuptools from setuptools.command import build_ext # TODO(atash) add flag...
#!/usr/bin/python # # Browse a Python dictionary in a two pane graphical interface written # in GTK. # # The GtkDictBrowser class is supposed to be generic enough to allow # applications to override enough methods and produce a # domain-specific browser provided the information is presented as a # Python dictionary. # ...
# # big5hkscs.py: Python Unicode Codec for BIG5HKSCS # # Written by Hye-Shik Chang <<EMAIL>> # import _codecs_hk, codecs import _multibytecodec as mbc codec = _codecs_hk.getcodec('big5hkscs') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.M...
from __future__ import absolute_import import warnings from decorator import decorator, decorate from inspect import stack from pyemma.util.exceptions import PyEMMA_DeprecationWarning __all__ = ['alias', 'aliased', 'deprecated', 'shortcut', 'fix_docs', ] def f...
from __future__ import print_function import sqlite3 def hr_department_history_export_sqlite_10(client, args, db_path, table_name): conn = sqlite3.connect(db_path) conn.text_factory = str cursor = conn.cursor() try: cursor.execute('''DROP TABLE ''' + table_name + ''';''') e...
import math import unittest from IECore import * import random import os class BoolVectorDataTest( unittest.TestCase ) : def test( self ) : trueFalse = [ True, False ] random.seed( 0 ) for i in range( 0, 100 ) : s = random.randint( 0, 100 ) b = BoolVectorData( s ) self.assertEqual( s, len( b ) ) ...
""" Convenience routines for creating non-trivial Field subclasses. Add SubfieldBase as the __metaclass__ for your Field subclass, implement to_python() and the other necessary methods and everything will work seamlessly. """ from django.utils.maxlength import LegacyMaxlength class SubfieldBase(LegacyMaxlength): ...
import unittest import numpy as np from molmod import * __all__ = ["QuaternionTestCase"] class QuaternionTestCase(unittest.TestCase): def test_rotation_matrix(self): q1 = np.random.normal(0,1,4) q1 /= np.linalg.norm(q1) r1 = quaternion_to_rotation_matrix(q1) factor, q2 = rotati...
""" Test for split test XModule """ from django.core.urlresolvers import reverse from mock import MagicMock from nose.plugins.attrib import attr from courseware.module_render import get_module_for_descriptor from courseware.model_data import FieldDataCache from student.tests.factories import UserFactory, CourseEnrollm...
""" Same as fonts_demo using kwargs. If you prefer a more pythonic, OO style of coding, see examples/fonts_demo.py. """ from matplotlib.font_manager import FontProperties import matplotlib.pyplot as plt import numpy as np plt.subplot(111, axisbg='w') alignment = {'horizontalalignment': 'center', 'verticalalignment':...
""" Django settings for projwatson project. Generated by 'django-admin startproject' using Django 1.9.2. 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...
import os from distutils.core import setup from setuptools import find_packages with open('version.py') as f: exec(f.read()) CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public Licens...
import io import textwrap import unittest from email import message_from_string, message_from_bytes from email.generator import Generator, BytesGenerator from email import policy from test.test_email import TestEmailBase, parameterize @parameterize class TestGeneratorBase: policy = policy.default def msgmak...
import random import time import subprocess import vlc import os # create list of all videos in folder 'videos' subfolder = "videos" videos = os.listdir(subfolder) # specify clip length intervall = 3 # seconds # setup vlc instance player = vlc.MediaPlayer() try: print("Script running... press Ctrl+C to quit.")...
'''Matchers for stubbing and verifications. Common matchers for use in stubbing and verifications. ''' __all__ = ['any', 'contains', 'times'] class Matcher: def matches(self, arg): pass class Any(Matcher): def __init__(self, wanted_type=None): self.wanted_type = wanted_type def matches(se...
""" Tests rotated rectangular and box masks. """ import unittest import nest class RotatedRectangularMask(unittest.TestCase): def setUp(self): nest.ResetKernel() def test_RotatedRectangularMask(self): """Test rotated rectangular mask. We have: lower_left: [-1.,...
"""The Flavor Rxtx API extension.""" from nova.api.openstack import extensions from nova.api.openstack import wsgi ALIAS = 'os-flavor-rxtx' authorize = extensions.os_compute_soft_authorizer(ALIAS) class FlavorRxtxController(wsgi.Controller): def _extend_flavors(self, req, flavors): for flavor in flavors...
from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson from ansible.module_utils import basic from ansible.modules.network.check_point import cp_mgmt_security_zone_facts OBJECT = { ...
from unittest2 import TestCase from jsonschema.exceptions import ValidationError from st2common.util import schema as util_schema TEST_SCHEMA_1 = { 'additionalProperties': False, 'title': 'foo', 'description': 'Foo.', 'type': 'object', 'properties': { 'arg_required_no_default': { ...
######################################################################## # # File Name: HTMLElement.py # # """ WWW: http://4suite.com/4DOM e-mail: <EMAIL> Copyright (c) 2000 Fourthought Inc, USA. All Rights Reserved. See http://4suite.com/COPYRIGHT for license and copyright information """ from...
"""The tests for the Alexa component.""" # pylint: disable=protected-access import asyncio import datetime import pytest from homeassistant.core import callback from homeassistant.setup import async_setup_component from homeassistant.components import alexa from homeassistant.components.alexa import const SESSION_ID...
import sys, os from optparse import OptionParser from androguard.core import androconf from androguard.core.bytecodes import apk, dvm from androguard.core.analysis import analysis sys.path.append("./elsim") from elsim import elsim from elsim.elsim_dalvik import ProxyDalvik, FILTERS_DALVIK_SIM from elsim.elsim_dalvik...
# coding: utf-8 ''' Django模板引擎的自定义过滤器,需要在模板中引用 {% load forum_extras %} ''' import json, re, random from datetime import date, datetime from django import template from django.utils import timezone from markdown import markdown register = template.Library() @register.filter(name='dump_errors') def dump_errors(err...
""" Based on "python-archive" -- http://pypi.python.org/pypi/python-archive/ Copyright (c) 2010 Gary Wilson Jr. <<EMAIL>> and contributers. 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 Software without...
from types import IntType, StringType import struct _have_rfc3542 = False try: import _rfc3542 from _rfc3542 import * _have_rfc3542 = True __doc__ = _rfc3542.__doc__ except ImportError: pass if _have_rfc3542: class SocketOptionInteger(object): """ internal class """ def __in...
#!/usr/bin/env python """ Cobbler external inventory script ================================= Ansible has a feature where instead of reading from /etc/ansible/hosts as a text file, it can query external programs to obtain the list of hosts, groups the hosts are in, and even variables to assign to each host. To use t...
from ddapp import lcmobjectcollection from ddapp import geometryencoder from ddapp import ioUtils from ddapp.uuidutil import newUUID import os class MeshManager(object): def __init__(self): self.meshes = {} self.cacheDirectory = '/tmp' self.cacheDataType = 'stl' self.collection = ...
from openerp import models, fields class SaleConfiguration(models.TransientModel): _inherit = 'sale.config.settings' group_sale_add_variants = fields.Boolean( string='Allow to add variants from template in Sale order', implied_group='sale_order_add_variants.group_sale_add_variants')
from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch from django.http import HttpRequest import json from testcases import TestCaseWithFixture class ViewsWithoutSlashesTestCase(TestCaseWithFixture): urls = 'slashless.api.urls' def setUp(self): super(ViewsWitho...
"""Zenodo GitHub API.""" from __future__ import absolute_import import uuid from flask import current_app from invenio_db import db from invenio_files_rest.models import ObjectVersion from invenio_github.api import GitHubRelease from invenio_github.utils import get_contributors, get_owner from invenio_indexer.api im...
from ansible.modules.storage.netapp.netapp_e_alerts import Alerts from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args __metaclass__ = type from units.compat import mock class AlertsTest(ModuleTestCase): REQUIRED_PARAMS = { 'api_username': 'rw', 'api_p...
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'core', 'version': '1.0'} EXAMPLES = r''' # Recursively find /tmp files older than 2 days - find: paths: "/tmp" age: "2d" recurse: yes # Recursively find /tmp files older than 4 weeks and equal or gr...
"""Emit ScriptResult status transition event.""" from maasserver.models import Event from maasserver.preseed import CURTIN_INSTALL_LOG from maasserver.utils.signals import SignalsManager from metadataserver.enum import ( RESULT_TYPE, SCRIPT_STATUS, SCRIPT_STATUS_CHOICES, SCRIPT_STATUS_FAILED, SCRI...
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'waw%j=vza!vc1^eyosw%#_!gg96%zb7sp*+!o...
from coalib.parsing.StringProcessing import unescaped_split from coalib.tests.parsing.StringProcessing.StringProcessingTestBase import ( StringProcessingTestBase) class UnescapedSplitTest(StringProcessingTestBase): bs = StringProcessingTestBase.bs test_basic_pattern = r"'" test_basic_expected_results...
from scapy.all import * from poison import Poison from threading import Thread from zoption import Zoption import time import config import util class icmp(Poison): def __init__(self): super(icmp, self).__init__('ICMP Redirection') conf.verb = 0 self.local = (config.get('ip_addr'), get_if...
from django.conf.urls.defaults import * from django.conf import settings from django.views.generic.simple import direct_to_template urlpatterns = patterns('main.views', url(r'^contact/$', 'contact', name="contact"), <<<<<<< HEAD url(r'^about/$', 'about', name="about"), url(r'^links/$', 'links', name="links...
#!/usr/bin/env python ''' work out total flight time for a mavlink log ''' import sys, time, os, glob import os, sys from math import * from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--condition", default=None, help="condition for packets") parser.add_argument("...
from django.contrib.auth.models import Group from django.test import TestCase, RequestFactory from django.utils.translation import gettext from base.business.learning_unit_year_with_context import get_with_context from base.forms.learning_unit.edition_volume import VolumeEditionForm, VolumeEditionBaseFormset, \ Vo...
from __future__ import absolute_import from __future__ import unicode_literals import sys from itertools import cycle from . import colors from .multiplexer import Multiplexer from .utils import split_buffer from compose import utils class LogPrinter(object): """Print logs from many containers to a single outpu...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} import sys # noqa import json import re API_BASE = 'https://api.github.com' class GitHubResponse(object): def __init__(self, response, info): self.content = respo...
# local storage in browser import sys from javascript import JSObject class __UnProvided(): pass class LocalStorage(): storage_type = "local_storage" def __init__(self): if not sys.has_local_storage: raise EnvironmentError("LocalStorage not available") self.store = JSObject(__...
# encoding: utf-8 # module atk # from /usr/lib/python2.7/dist-packages/gtk-2.0/atk.so # by generator 1.135 # no doc # imports import gobject as __gobject import gobject._gobject as __gobject__gobject import __main__ as ____main__ class Rectangle(__gobject.GBoxed): # no doc def __delitem__(self, y): # real si...
#!/usr/bin/env python # -*- coding: utf-8 -*- from gi.repository import Gtk import DataViewerClass as dv # ===== Variables Globales ==================== window = Gtk.Window() screen = window.get_screen() screenWidth, screenHeight = screen.width(), screen.height() # =============================================== ...
from __future__ import division import random import tempfile from twisted.internet import defer, reactor from twisted.trial import unittest from twisted.web import client, resource, server from p2pool import data, node, work from p2pool.bitcoin import data as bitcoin_data, networks, worker_interface from p2pool.uti...
"""Test bitcoind aborts if can't disconnect a block. - Start a single node and generate 3 blocks. - Delete the undo data. - Mine a fork that requires disconnecting the tip. - Verify that bitcoind AbortNode's. """ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import get_datadi...
"""The event extraction worker.""" import logging import os import pdb import threading from dfvfs.lib import definitions as dfvfs_definitions from dfvfs.resolver import context from dfvfs.resolver import resolver as path_spec_resolver from plaso.lib import classifier from plaso.lib import errors from plaso.lib impo...
#!/usr/bin/env python3 """Unit tests for the keyword only argument specified in PEP 3102.""" __author__ = "Jiwon Seo" __email__ = "seojiwon at gmail dot com" import unittest from test.support import run_unittest def posonly_sum(pos_arg1, *arg, **kwarg): return pos_arg1 + sum(arg) + sum(kwarg.values()...
from __future__ import unicode_literals, division, absolute_import import time import logging import posixpath from flask import render_template, Blueprint, request, redirect, flash, send_file from flask.helpers import url_for from flexget.plugin import DependencyError, get_plugin_by_name from flexget.ui.webui import r...
"""Journal using twisted.enterprise.row RDBMS support. You're going to need the following table in your database:: | CREATE TABLE journalinfo | ( | commandIndex int | ); | INSERT INTO journalinfo VALUES (0); """ from __future__ import nested_scopes # twisted imports from twisted.internet impo...
import os import re import signal from sos.plugins import Plugin, RedHatPlugin # Class name must be the same as file name and method names must not change class Ovirt(Plugin, RedHatPlugin): """oVirt Engine""" plugin_name = "ovirt" profiles = ('virt',) packages = ( 'ovirt-engine', '...
from UIBase import UIBase from getpass import getpass import sys from threading import Lock, currentThread class TTYUI(UIBase): def __init__(s, config, verbose = 0): UIBase.__init__(s, config, verbose) s.iswaiting = 0 s.outputlock = Lock() s._lastThreaddisplay = None def isusab...
import argparse import json import os import netaddr PREFIX_NAME = 'RPC' SNAT_POOL = ( 'create ltm snatpool %(prefix_name)s_SNATPOOL { members replace-all-with {' ' %(snat_pool_addresses)s } }' ) MONITORS = ( 'create ltm monitor mysql %(prefix_name)s_MON_GALERA { count 0 database' ' information_sch...
{ 'name': 'Dates on Sales Order', 'version': '1.0', 'category': 'Sales Management', 'complexity': "easy", 'description': """ Add additional date information to the sales order. =================================================== You can add the following additional dates to a sale order: * Requ...
from openerp.osv import fields, osv class accountSalereportWizard(osv.osv_memory): _name = "sale.report.wiz" _description = "Account Sale Report Wizard" #This method filter list of products depends of origin. def onchange_origin(self, cr, uid, ids, origin, context=None): if origin: ...
""" Middleware for Language Preferences """ from openedx.core.djangoapps.user_api.preferences.api import get_user_preference from lang_pref import LANGUAGE_KEY # TODO PLAT-671 Import from Django 1.8 # from django.utils.translation import LANGUAGE_SESSION_KEY from django_locale.trans_real import LANGUAGE_SESSION_KEY ...
"""Scans and creates communication interfaces.""" __author__ = 'Bitcraze AB' __all__ = [] import logging logger = logging.getLogger(__name__) from .radiodriver import RadioDriver from .udpdriver import UdpDriver from .serialdriver import SerialDriver from .debugdriver import DebugDriver from .usbdriver import UsbDr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 1) Create the data type # se = {11,222,11,222} # print(se) # Different between type: list, dictionary and set # li = [11,222,11,222] # dic = {"k1":123} # se = {"123","456"} # s = set() #create an empty Set # # s1 = set(li) # Distinct the value from the dataset # print(...
from neutron.tests.tempest import auth from neutron.tests.tempest.common import cred_provider from neutron.tests.tempest import config from neutron.tests.tempest import exceptions CONF = config.CONF class Manager(object): """ Base manager class Manager objects are responsible for providing a configurat...
from tests.unit import AWSMockServiceTestCase from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.s3.tagging import Tag class TestS3Tagging(AWSMockServiceTestCase): connection_class = S3Connection def default_body(self): return """ <Tagging> ...
from m5.SimObject import SimObject from m5.params import * from m5.proxy import * from MemObject import MemObject class ArmTableWalker(MemObject): type = 'ArmTableWalker' cxx_class = 'ArmISA::TableWalker' port = MasterPort("Port for TableWalker to do walk the translation with") sys = Param.System(Paren...
#!/usr/bin/env python3 import argparse import os import subprocess import sys def setup(): global args, workdir programs = ['ruby', 'git', 'apt-cacher-ng', 'make', 'wget'] if args.kvm: programs += ['python-vm-builder', 'qemu-kvm', 'qemu-utils'] elif args.docker: dockers = ['docker.io',...
from suds import * from suds.client import Client from sys import exit from optparse import OptionParser from aviary.util import * wsdl = 'file:/var/lib/condor/aviary/services/query/aviary-query.wsdl' parser = build_basic_parser('Query submission summaries remotely via SOAP.','http://localhost:9091/services/query/get...
from __future__ import absolute_import, division, print_function ANSIBLE_METADATA = { 'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1' } import base64 import json import os from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url __...
""" Astronomical and physics constants in SI units. See :mod:`astropy.constants` for a complete listing of constants defined in Astropy. """ import numpy as np from .constant import Constant, EMConstant # PHYSICAL CONSTANTS class CODATA2014(Constant): default_reference = 'CODATA 2014' _registry = {} _...
from UM.Operations.Operation import Operation from UM.Operations.GroupedOperation import GroupedOperation from UM.Scene.SceneNode import SceneNode ## A specialised operation designed specifically to modify the previous operation. class PlatformPhysicsOperation(Operation): def __init__(self, node, translation): ...
__all__ = [ "ReqlCursorEmpty", "RqlCursorEmpty", "ReqlError", "RqlError", "ReqlCompileError", "RqlCompileError", "ReqlDriverCompileError", "ReqlServerCompileError", "ReqlRuntimeError", "RqlRuntimeError", "ReqlQueryLogicError", "ReqlNonExistence...
""" .. _ex-read-events: ===================== Reading an event file ===================== Read events from a file. For a more detailed discussion of events in MNE-Python, see :ref:`tut-events-vs-annotations` and :ref:`tut-event-arrays`. """ # Authors: Alexandre Gramfort <<EMAIL>> # Chris Holdgraf <<EMAIL>> #...
from __future__ import absolute_import from __future__ import division from math import sqrt, sin, cos, atan2 from core.point3d import Point3D class Point(object): __slots__ = ["x", "y"] def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __str__(self): ...
import numpy as np import igraph def prefAttch(d_seq, min_p): """ Sampling a node to attach using a linear preferential attachment. ------------PARAMETERS------------ @param d_seq : A list containing the degree sequence where each index refers to a node @returns : The sampled node ----------...
"""Functions used by multiple tflite test files.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.lite.python import schema_py_generated as schema_fb from tensorflow.lite.python import schema_util from tensorflow.lite.tools import visualiz...
#!/usr/bin/env python import webapp2 import tba_config from controllers.backup_controller import TbaCSVBackupEventsEnqueue, TbaCSVBackupEventDo, TbaCSVRestoreEventsEnqueue, TbaCSVRestoreEventDo from controllers.backup_controller import TbaCSVBackupTeamsEnqueue from controllers.datafeed_controller import TbaVideosGet...
import webob from webob import exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.console import api as console_api from nova import exception def _translate_keys(cons): """Coerces a console instance into proper dictionary format.""" pool = cons['pool'] info = {'i...
from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' # 25 Ottobre 2006 TIME_FORMAT = 'H:i:s' # 14:30:59 DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59 YE...
#!/opt/anaconda/bin/python # Description: Script to perform time series photometry # Laboratorio Nacional de Astrofisica, Brazil # Jul 2017 # import os, sys import time start_time = time.time() #--- SET UP PIPELINE PARAMETERS --- PHOTROOTDIR="/Users/edermartioli/Desktop/fotometria/" NIGHT="17jul13" OBJECT="hats-24" ...
#!/usr/bin/env python import sys sys.path.append("../tools") import mergejs source_directory = "../lib" config_filename = "full.cfg" output_filename = "OpenLayers.js" def minimize(text): try: import jsmin return jsmin.jsmin(text) except Exception, e: import minimize return min...
from codecs import BOM_UTF8 from urllib import urlopen from itertools import chain from __init__ import Graph, Node, Edge, bfs from __init__ import WEIGHT, CENTRALITY, EIGENVECTOR, BETWEENNESS import os try: MODULE = os.path.dirname(os.path.realpath(__file__)) except: MODULE = "" #### COMMONSENSE SEMA...
import xbmc, xbmcaddon, xbmcgui, xbmcplugin, os, sys, xbmcvfs, glob import shutil import urllib2,urllib import re import uservar from datetime import date, datetime, timedelta from resources.libs import extract, downloader, notify, loginit, debridit, traktit, skinSwitch, uploadLog, wizard as wiz ADDON_ID = userv...
import socket import sys import os def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", 40404)) x = parse_args(sys.argv) if "" != x: # print("XZES:: Sent request:", x) s.send(x.encode('utf-8')) else: print("\nPlease pass an XML and XSL f...
import unittest from airflow.contrib.hooks import bigquery_hook as hook class TestBigQueryTableSplitter(unittest.TestCase): def test_internal_need_default_project(self): with self.assertRaises(Exception) as context: hook._split_tablename('dataset.table', None) self.assertIn('INTERNAL...
from .response import JSONResponse from .view import View class Resource(View): """ Base class for HTTP Resources (RESTful?) """ # TODO: Optimize for alphanumeric as base pattern id_pattern = '{id}' # Allow nested resources nested_collection_resources = None nested_entity_resources =...