code
stringlengths
1
199k
""" PyCOMPSs Testbench ======================== """ import unittest from modules.testOpenclDecorator import testOpenclDecorator def main(): suite = unittest.TestLoader().loadTestsFromTestCase(testOpenclDecorator) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == "__main__": main()
class CheckJSON: def __init__(self, key, obj, ip_info=False): self.key_error = 'Field is not applicable to this license.' if ip_info is True: self.key_error = 'No IP info returned.' self.key = key self.obj = obj def key_valid(self): if self.key not in self.obj: raise KeyError(self.key_error) else: ...
__author__ = 'admin' class ContactHelper: def __init__(self, app): self.app = app def create(self, contact): self.fill_contact_fields(contact) def modify(self, contact): # modify contact self.click_edit_button() self.fill_contact_fields(contact) def set_field_valu...
import logging from abc import abstractmethod from string import Template from parsl.providers.error import SchedulerMissingArgs, ScriptPathError from parsl.launchers.error import BadLauncher from parsl.providers.provider_base import ExecutionProvider logger = logging.getLogger(__name__) class ClusterProvider(Execution...
extensions = ['openstackdocstheme'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Compute API Guide' bug_tag = u'api-guide' repository_name = 'openstack/nova' bug_project = 'nova' html_last_updated_fmt = '%Y-%m-%d %H:%M' copyright = u'2015, OpenStack contributors' version = '2....
""" IOWorkers provide a convenient IO abstraction. Sends are fire-and-forget, and read data is buffered and you can get notifications when data is available. """ import sys import errno from collections import deque import socket from pox.lib.util import assert_type, makePinger from pox.lib.recoco import Select, Task ...
import logging logger = logging.getLogger(__name__) import requests import os from django.core.management.base import NoArgsCommand from apps.subscribers.models import Ticket class Command(NoArgsCommand): help = 'Loops through all subscribers and marks each ticket appropriately.' def handle_noargs(self, **optio...
import collections class Solution: def numSimilarGroups(self, A): UF = {} for i in range(len(A)): UF[i] = i def find(x): if x != UF[x]: UF[x] = find(UF[x]) return UF[x] def union(x, y): UF.setdefault(x, x) UF.setdefault(...
import abc from OHA.helpers.converters.BaseConverter import BaseConverter __author__ = 'indrajit' __email__ = 'eendroroy@gmail.com' class LengthConverter(BaseConverter): def __init__(self, _value, _from=None, _to=None): super(LengthConverter, self).__init__(_value, _from, _to) def _supported_units(self)...
import rem_backend.query_data as qd import rem_backend.propagation_model_estimation as pm import threading import _thread __author__ = "Daniel Denkovski", "Valentin Rakovic" __copyright__ = "Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia" __version__ = "0.1.0...
"""Example code for TensorFlow Wide & Deep Tutorial using TF.Learn API.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import shutil import sys import tensorflow as tf _CSV_COLUMNS = [ 'age', 'workclass', 'fnlwgt', 'education', 'educat...
from dronekit import connect import time import argparse import pprint import rospy import copy from gf_beacon.srv import * import hostapd import beaconencoder import findap class sample_beacon_data: def __init__(self, connect_string): print "init" self.missing_AP = False try: AP...
import pandas as pd import numpy as np import gc import os import re import pickle import string from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer...
def daysSinceEpoc( _unused=0 ): import datetime return (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).days class FilterModule(object): def filters(self): return { 'daysSinceEpoc': daysSinceEpoc, }
import logging import numpy as np from ray.tune.automl.search_policy import AutoMLSearcher logger = logging.getLogger(__name__) LOGGING_PREFIX = "[GENETIC SEARCH] " class GeneticSearch(AutoMLSearcher): """Implement the genetic search. Keep a collection of top-K parameter permutations as base genes, then app...
from abc import ABCMeta, abstractmethod from pathlib import PurePath from textwrap import dedent from typing import List, Tuple, Type from unittest.mock import Mock import pytest from pants.base.exceptions import ResolveError from pants.build_graph.address import Address from pants.engine.fs import ( EMPTY_DIRECTOR...
import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import PathPatch from matplotlib.path import Path from matplotlib.transforms import Bbox from scipy import stats x = np.linspace(0, 1, 200) pdfx = stats.beta(2, 5).pdf(x) path = Path(np.array([x, pdfx]).transpose()) patch = Pat...
import temperanotes import pytest, bisect @pytest.fixture def idiot_temp(): temp = [1, 1.05, 1.1, 1.15, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9] # not a temperament, just a set of numbers for testing assert len(temp) == 12 # need 12 notes for the...
from app import setup app = setup()
"""Transforms.""" import functools from cvx2 import latest as cv2 import numpy as np import tensorflow as tf from tensorflow_graphics.projects.points_to_3Dobjects.utils import image as image_utils from google3.third_party.tensorflow_models.object_detection.core import preprocessor tf_data_augmentation = preprocessor LI...
"""ApacheParser is a member object of the ApacheConfigurator class.""" import copy import fnmatch import logging import os import re import subprocess import sys import six from certbot import errors from certbot_apache import constants logger = logging.getLogger(__name__) class ApacheParser(object): """Class handl...
class DummyKeyResponse(object): def __init__(self, gen=1): self.generation = gen self.name = "" def request(self, path, method, **kwargs): self.name = path.split('/')[-1] return self def json(self): return {"generation": self.generation, "name": self.n...
import copy import ddt import fixtures import microversion_parse import os from unittest import mock from oslo_utils.fixture import uuidsentinel from oslotest import base from nova.compute import provider_config from nova import exception as nova_exc class SchemaValidationMixin(base.BaseTestCase): """This class pro...
from qingcloud.cli.iaas_client.actions.base import BaseAction class DescribeRouterVxnetsAction(BaseAction): action = 'DescribeRouterVxnets' command = 'describe-router-vxnets' usage = '%(prog)s -r <router_id> [-f <conf_file>]' @classmethod def add_ext_arguments(cls, parser): parser.add_argume...
import sys from PyQt4 import QtGui from dependence_repo_manager.core.manager import RepoManager from dependence_repo_manager.core.main_window import MainWindow if __name__ == '__main__': app = QtGui.QApplication(sys.argv) manager = RepoManager() manager.config() mainWin = MainWindow(manager) mainWin...
import json from collections import OrderedDict from inspect import signature from warnings import warn import numpy as np from sklearn.base import BaseEstimator class Configuration(object): def __init__(self, name, version, params): if not isinstance(name, str): raise ValueError() if no...
import argparse import logging import utils class CtxWithLogger(object): logger = logging.getLogger('internal-ssl-certs-logger') utils.ctx = CtxWithLogger() parser = argparse.ArgumentParser() parser.add_argument('--metadata', default=utils.CERT_METADATA_FILE_PATH, help='File containing the cert ...
from measures.generic.GenericMeasure import GenericMeasure import measures.generic.Units as Units class StartedSearches(GenericMeasure): """Total number of started searches""" def __init__(self, period, simulationTime): GenericMeasure.__init__(self, r'DEBUG .*? - Peer [0-9]+ started search for parameters .*? ([0-9...
import logging class BorgSingleton: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class LoggerSetup(BorgSingleton): """Logger setup convenience class""" DEFAULT_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' def __init__(self, logger_name, log_lev...
from flask import Flask, request, render_template import os import json import time import datetime from smarthomemongo import SmartHomeDB app = Flask(__name__) smartDB = SmartHomeDB() @app.route('/') def index(): records = smartDB.getCurrentStats('raspberry') if( 'timestamp' in records.keys() ): ts = datetime.date...
clock.addListener("clockStopped", "python", "clock_stopped") def clock_stopped(): print("The clock has been stopped")
from setuptools import setup setup(name="int_methods", version="0.0.1", install_requires=["quark==0.0.1"], py_modules=['int_methods'], packages=['int_methods', 'int_methods_md'])
import logging import traceback from sis_provisioner.dao.uw_account import get_all_uw_accounts from sis_provisioner.csv import get_filepath from sis_provisioner.csv.user_writer import make_import_user_csv_files from sis_provisioner.util.log import log_exception from sis_provisioner.util.settings import get_csv_file_pat...
from itertools import * for i, s in zip(count(), repeat('over-and-over', 5)): print(i, s)
from SamplingAccuracyEvaluation import SamplingAlgorithm as SA from SamplingAccuracyEvaluation import AccuracyEvaluation as AE from SamplingAccuracyEvaluation import PrintGraph as PG from SamplingAccuracyEvaluation import StatisticalCalculation as SC import operator def populationListGenerate(filePath, target): pri...
import csv file = open('NodeCheckList.csv', 'rb') reader = csv.reader(file) NodeCheckList = list(reader) file.close() FirstRow = NodeCheckList.pop(0) FirstRow[8] = 'Frequency' for element in NodeCheckList: if element[2] != "": element[2] = int(element[2]) SortYear = sorted(NodeCheckList, key=lambda l:l[3], reverse=T...
import urllib2 from lxml import etree class Scrape_Quora: regexpNS = "http://exslt.org/regular-expressions" @staticmethod def get_name(user_name): url = 'https://www.quora.com/profile/' + user_name response = urllib2.urlopen(url) htmlparser = etree.HTMLParser() tree = etree.p...
import threading from neutron_lib.callbacks import resources from neutron_lib import constants as n_const from neutron_lib import context from neutron_lib.plugins import directory from neutron_lib import worker from oslo_log import log from neutron.db import provisioning_blocks from networking_odl.common import client ...
def rewrite_keywords(journal_like): bib = journal_like.bibjson() kwords = [k.lower() for k in bib.keywords] bib.set_keywords(kwords) return journal_like
from typing import Optional, List, Iterator, Iterable, TYPE_CHECKING from cirq.interop.quirk.cells.cell import Cell, CELL_SIZES, CellMaker if TYPE_CHECKING: import cirq class InputCell(Cell): """A modifier that provides a quantum input to gates in the same column.""" def __init__(self, qubits: Iterable['cir...
from util.typedispatch import * from . import graph as cfg from . dfs import CFGDFS class Logger(TypeDispatcher): def __init__(self): self.merges = [] @defaultdispatch def default(self, node): pass @dispatch(cfg.MultiEntryBlock) def visitMerge(self, node): self.merges.append(node) def evaluate(compiler, g): ...
''' Kurgan AI Web Application Security Analyzer. http://www.kurgan.com.br/ Author: Glaudson Ocampos - <glaudson@vortexai.com.br> Created in May, 11th 2016. ''' import requests import config import sys import warnings import validators sys.path.append('../') class Target(object): host = None method = '' head...
DOCUMENTATION = ''' --- module: ec2_ami_find version_added: 2.0 short_description: Searches for AMIs to obtain the AMI ID and other information description: - Returns list of matching AMIs with AMI ID, along with other useful information - Can search AMIs with different owners - Can search by matching tag(s), by ...
from typing import Union from ray.rllib.models.action_dist import ActionDistribution from ray.rllib.utils.annotations import override from ray.rllib.utils.exploration.exploration import TensorType from ray.rllib.utils.exploration.soft_q import SoftQ from ray.rllib.utils.framework import try_import_tf, try_import_torch ...
import tweepy import os from flask import Flask, make_response, jsonify CONSUMER_KEY = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_TOKEN'] CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET'] app = Flask(__name__) auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) api = tweepy.API(auth) @app.route(...
from guardian.shortcuts import get_perms from rest_framework import serializers as ser from rest_framework.exceptions import ValidationError from reviews.workflow import Workflows from api.actions.serializers import ReviewableCountsRelationshipField from api.base.utils import absolute_reverse, get_user_auth from api.ba...
"""GCI org proposal processing mapreduce.""" from mapreduce import context from mapreduce import operation from melange.request import links from soc.logic import org_app as org_app_logic from soc.models.site import Site from soc.models.org_app_survey import OrgAppSurvey from soc.modules.gci.models.program import GCIPr...
from __future__ import absolute_import from typing import Any from django.utils.translation import ugettext as _ from django.conf import settings from django.contrib.auth import authenticate, login, get_backends from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponseForbi...
from google.cloud import aiplatform_v1beta1 async def sample_update_model_deployment_monitoring_job(): # Create a client client = aiplatform_v1beta1.JobServiceAsyncClient() # Initialize request argument(s) model_deployment_monitoring_job = aiplatform_v1beta1.ModelDeploymentMonitoringJob() model_depl...
from trove.common import wsgi from trove.common.auth import admin_context from trove.extensions.mgmt.volume import models from trove.extensions.mgmt.volume import views from trove.openstack.common import log as logging from trove.openstack.common.gettextutils import _ LOG = logging.getLogger(__name__) class StorageCont...
"""Module to debug python programs""" import sys import traceback def getAllStacks(): code = [] for threadId, stack in sys._current_frames().iteritems(): code.append("\n# ThreadID: %s" % threadId) for filename, lineno, name, line in traceback.extract_stack(stack): code.append('File: ...
''' @auther:fangxiao ''' import apibinding.api_actions as api_actions import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.iam2_operations as iam2_ops import zstackwoodpecker.operations.affinitygro...
VERSION = '2.9.0'
"""Gluon EventHandlers for Estimators""" import os import time import warnings import numpy as np from ...metric import CompositeEvalMetric, EvalMetric from ...metric import Loss as metric_loss from .utils import _check_metrics __all__ = ['TrainBegin', 'TrainEnd', 'EpochBegin', 'EpochEnd', 'BatchBegin', 'BatchEnd', ...
import random import threading from collections import defaultdict import logging import time from typing import Any, Dict, List, Optional from ray.autoscaler.node_provider import NodeProvider from ray.autoscaler.tags import TAG_RAY_CLUSTER_NAME, TAG_RAY_NODE_NAME, \ TAG_RAY_LAUNCH_CONFIG, TAG_RAY_NODE_KIND, \ ...
"""Module containing the views for GSoC Organization Application. """ __authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] from django.conf.urls.defaults import url from soc.logic.models.org_app_survey import logic as org_app_logic from soc.views import forms from soc.views.models.org_app_survey import Or...
import unittest from mopidy_tunein import Extension class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn("[tunein]", config) self.assertIn("enabled = true", config) def test_get_config_schema(...
""" package oompa.tracking TODO: stil waffling about whether to log two-columns - "datetime {json}" or "{json-with-datetime-field}" """ import json import os from datetime import datetime class UpdateLogger: """ records updates for later replay """ def __init__(self, config): self.config = confi...
from helper import unittest, PillowTestCase, py3 from PIL import Image class TestLibPack(PillowTestCase): def pack(self): pass # not yet def test_pack(self): def pack(mode, rawmode): if len(mode) == 1: im = Image.new(mode, (1, 1), 1) else: ...
import numpy as np import tensorflow as tf __all__ = [ 'Initializer', 'Zeros', 'Ones', 'Constant', 'RandomUniform', 'RandomNormal', 'TruncatedNormal', 'deconv2d_bilinear_upsampling_initializer' ] class Initializer(object): """Initializer base class: all initializers inherit from this class. """ def ...
input = """ % Atom bug shouldn't be derived, as the body of the rule % should be false. Auxiliary atoms shouldn't be printed % out, as they are censored. d(1). d(2). d(3). bug :- 1 < #count{V : d(V)} <= 2. """ output = """ % Atom bug shouldn't be derived, as the body of the rule % should be false. Auxiliary atoms shoul...
"""Component to make instant statistics about your history.""" import datetime import logging import math import voluptuous as vol from homeassistant.components import history from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_ENTITY_ID, CONF_NAME, CONF_STATE,...
"""This utility installs an engage extension into a deployment home. """ import os import os.path import sys from optparse import OptionParser import shutil import re import logging logger = logging.getLogger(__name__) base_src_dir=os.path.abspath(os.path.dirname(__file__)) python_pkg_dir = os.path.join(base_src_dir, "...
import requests from bs4 import BeautifulSoup, UnicodeDammit import time import os import re import log import tools class Get(object): # timeout, retry_interval -> seconds def __init__(self, url='', timeout=5, retry=5, retry_interval=2, proxies={}, headers={}, download_file=None, savepath='.'): self.lo...
''' Created on 17/2/16. @author: love ''' import paho.mqtt.client as mqtt import json import ssl def on_connect(client, userdata, flags, rc): print("Connected with result code %d"%rc) client.publish("Login/HD_Login/1", json.dumps({"userName": user, "passWord": "Hello,anyone!"}),qos=0,retain=False) def on_messag...
def joke(): return 'Knock Knock. Who is there?'
""" minemeld.collectd Provides a client to collectd for storing metrics. """ import socket import logging LOG = logging.getLogger(__name__) class CollectdClient(object): """Collectd client. Args: path (str): path to the collectd unix socket """ def __init__(self, path): self.path = path ...
from osrf_pycommon.process_utils import asyncio from osrf_pycommon.process_utils.async_execute_process import async_execute_process from osrf_pycommon.process_utils import get_loop from .impl_aep_protocol import create_protocol loop = get_loop() @asyncio.coroutine def run(cmd, **kwargs): transport, protocol = yield...
r"""subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions: os.system os.spawn* Information about how the subprocess module can be used ...
import json import httplib import requests import six import pyaml from six.moves.urllib.parse import urljoin from st2actions.runners.pythonrunner import Action __all__ = [ 'PostResultAction' ] def _serialize(data): return pyaml.dump(data) def format_possible_failure_result(result): ''' Error result as ...
import pytest interactiveshell = pytest.importorskip("IPython.terminal.interactiveshell") tools = pytest.importorskip("IPython.testing.tools") @pytest.fixture(scope="session") def ipython(): config = tools.default_config() config.TerminalInteractiveShell.simple_prompt = True shell = interactiveshell.Termina...
"""Test helper functions.""" import gzip import importlib import logging import os import sys from typing import Any, Dict, List, Optional, Tuple, Union import cloudpickle import numpy as np import pytest from _pytest.outcomes import Skipped from packaging.version import Version from ..data import InferenceData, from_d...
from twisted.internet.defer import inlineCallbacks, succeed from twisted.internet import reactor from twisted.python.modules import getModule from twisted.trial import unittest from twistedcaldav.config import ConfigDict from twistedcaldav.ical import Component from txdav.caldav.datastore.scheduling.imip.inbound import...
import io from molotov.api import get_fixture _UNREADABLE = "***WARNING: Molotov can't display this body***" _BINARY = "**** Binary content ****" _FILE = "**** File content ****" _COMPRESSED = ('gzip', 'compress', 'deflate', 'identity', 'br') class BaseListener(object): async def __call__(self, event, **options): ...
""" Tests for running and managing PostgreSQL with Flocker. """ from unittest import skipUnless from uuid import uuid4 from pyrsistent import pmap, freeze, thaw from twisted.python.filepath import FilePath from twisted.trial.unittest import TestCase from flocker.control import ( Application, DockerImage, AttachedVo...
""" Provides generic deployment steps for machines post boot. """ import os class Deployment(object): """ Base class for deployment tasks. """ def run(self, node, client): """ Runs this deployment task on C{node} using the C{client} provided. @type node: L{Node} @keyword ...
from __future__ import absolute_import from hamcrest.library import * from hamcrest.core import *
"""Tests /freebase/object_hints/best_hrid resolution. /freebase/object_hints/best_hrid specifies a persistent HRID for an entity. This should be favored over the earlier MQL algorithm for choosing an HRID based on namespace traversal and various heuristics. """ __author__ = 'nix@google.com (Nick Thompson)' import json ...
"""Tests for multistep_ops.py.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow.compat.v1 as tf from trfl import sequence_ops def get_n_step_backup(reward...
"""Backend compiler related feature registration""" from __future__ import absolute_import import tvm from tvm import te from tvm.te.hybrid import script from tvm.runtime import convert from tvm import topi from tvm.topi.util import get_const_int, get_const_tuple from . import op as _reg from . import strategy from .op...
import logging import sys if (sys.version_info > (3,)): from urllib.parse import quote else: from urllib import quote import jsonpickle from cairis.core.Asset import Asset from cairis.core.ObjectSummary import ObjectSummary from cairis.core.AssetEnvironmentProperties import AssetEnvironmentProperties from cairis.co...
from muntjac.api import VerticalLayout, Link from muntjac.terminal.theme_resource import ThemeResource from muntjac.terminal.external_resource import ExternalResource class LinkCurrentWindowExample(VerticalLayout): _CAPTION = 'Open Google' _TOOLTIP = 'http://www.google.com' _ICON = ThemeResource('../sampler...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from include.dataset_fnames import generate_station_data_fname from include.feature_lists import numeric_features from xgboost import XGBRegressor def numeric_df_missing_values_summary(): for i, station_id in enumerate(sort...
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('webcore', '0003_auto_20170427_1825'), ] operations = [ migrations.RemoveField( model_name='postad', name='user', ), migra...
"""Elementwise operators""" from __future__ import absolute_import as _abs import tvm from .. import tag from ..util import get_const_int @tvm.tag_scope(tag=tag.ELEMWISE) def relu(x): """Take relu of input x. Parameters ---------- x : tvm.Tensor Input argument. Returns ------- y : tv...
""" Interface for all resource control plugins. """ from abc import ABCMeta, abstractmethod from ..plugin import DeclareFramework @DeclareFramework('provisioner') class Provisioner(object, metaclass=ABCMeta): PROVISIONER_KEY = "provisioner" PROVISIONER_IMAGE_KEY = "image" PROVISIONER_BOOTSTRAP_KEY = "provis...
import math import tensorflow as tf from .retrieval_metric import RetrievalMetric from tensorflow_similarity.types import FloatTensor, IntTensor, BoolTensor class BNDCG(RetrievalMetric): """Binary normalized discounted cumulative gain. This is normalized discounted cumulative gain where the relevancy weights ...
"""ImageNet-Sketch dataset.""" from tensorflow_datasets.image_classification.imagenet_sketch.imagenet_sketch import ImagenetSketch
""" Python provides the base64 module as a core module but this is mostly limited to encoding and decoding base64 and it's variants. It is often useful to be able to perform other operations on base64 text. This module is meant to be used in conjunction with the core base64 module. Standarized base64 is defined in RFC-...
import argparse import random import time def bin(number): return "{0:5b}".format(number).replace(' ','0') def initialize(population): return [bin(random.randint(0,31)) for x in range(0, population)] def evaluate(population): tuples = [] suma = 0 end = False for chaval in population: val...
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: row = len(grid) col = len(grid[0]) dp = [[0]*col for i in range(row)] minPath = 0 return self.findPath(grid, row-1, col-1, dp) def findPath(self, grid, i, j, dp): #print(i,j, minPath) if d...
import datetime import pecan import wsme from wsme import types as wtypes from pecan import rest class APIBase(wtypes.Base): created_at = wsme.wsattr(datetime.datetime, readonly=True) """The time in UTC at which the object is created""" updated_at = wsme.wsattr(datetime.datetime, readonly=True) """The t...
"""Formatter for ASL securityd log file.""" from plaso.formatters import interface class MacSecuritydLogFormatter(interface.ConditionalEventFormatter): """Formatter for ASL Securityd file.""" DATA_TYPE = 'mac:asl:securityd:line' FORMAT_STRING_PIECES = [ u'Sender: {sender}', u'({sender_pid})', u'...
import py4j class CapturedException(Exception): def __init__(self, desc, stackTrace): self.desc = desc self.stackTrace = stackTrace def __str__(self): return repr(self.desc) class AnalysisException(CapturedException): """ Failed to analyze a SQL query plan. """ class ParseExc...
"""Live value resolution. Live values are extracted from the known execution context. Requires activity analysis annotations. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.contrib.py2tf.pyct import anno from tensorflow.contri...
class Error(object): def __init__(self, code, msg=None, data=None): self.code = code self.msg = msg self.data = data def __str__(self): err = self.to_dict() return str(err) def to_dict(self): err = {} err['err_code'] = self.code if self.msg: ...
from cloud_provider.amazon import Amazon from template.template import CloudFormationTemplate from pprint import pprint if __name__ == "__main__": # Amazon Settings region = "eu-west-1" stack_name = 'TestStack' # Template settings template_file = '/tmp/template.txt' template_json_source_file = '...
from lxml import etree from anansi.xml import XMLMessage,gen_element,XMLError class TCCError(Exception): def __init__(self,msg): super(TCCError,self).__init__(msg) class TCCMessage(XMLMessage): def __init__(self,user,comment=""): super(TCCMessage,self).__init__(gen_element('tcc_request')) ...
"""Copyright 2008 Orbitz WorldWide 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 di...
import os import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, os.getcwd() + '/../../tools/') import wb import trf import wer def process_nbest(fread, fwrite): nEmptySentNum = 0 with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2: for a in [line.split() for line in f1]: ...