text
stringlengths
2
999k
"""Support for WLED.""" from __future__ import annotations from datetime import timedelta import logging from wled import WLED, Device as WLEDDevice, WLEDConnectionError, WLEDError from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN fr...
####################################################################### import leiap import pandas as pd ####################################################################### def test_clean_datetimes_return_df(): pts = leiap.get_points_simple() df = leiap.clean_datetimes(pts) assert isinstance(df, pd.D...
from ..config import pg, username, debug, reddit, donotreply from ..RedditPoller.RedditPoller import RedditPoller, CommentWrapper from ..RedditPoller.Retry import retry from geopy.point import Point from geopy.distance import distance from sty import fg from random import randrange from halo import Halo import re impor...
"""Muscle modeling and simulation.""" from __future__ import division, print_function import numpy as np from scipy.integrate import ode import warnings import configparser __author__ = 'Marcos Duarte, https://github.com/demotu/BMC' __version__ = 'muscles.py v.1 2015/03/01' class Thelen2003(): """ Thelen (2003...
"""Unit test for node harvest. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import shutil import sys import tempfile import unittest import tarfile import mock from treadmill import postmortem from ...
# Copyright 2014 # The Cloudscaling Group, Inc. # # 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 ...
#!/usr/bin/env python3 ############################################################################## # Project: arrayfunc # Purpose: Generate the unit tests for compress. # Language: Python 3.5 # Date: 11-Jun-2014 # ############################################################################### # # Copyright 2...
import numpy as np import tensorflow as tf class Critic: def __init__(self, sess, state_size, action_size, param_size, num_outputs): #TODO : add batch normalization self.l1_size = 256 self.l2_size = 128 self.l3_size = 64 self.l4_size = 32 self.learning_rate = 0...
from . import resource from botocore.exceptions import ClientError class Elb(resource.Resource): METRICS = { "Latency": "レイテンシー", "RequestCount": "リクエストカウント", "HealthyHostCount": "正常EC2数", "UnHealthyHostCount": "危険EC2数", "HTTPCode_ELB_4XX": "HTTPレスポンスコード(4xx)", ...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 OpenAPI spec version: v1.13.5 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import kube...
class Reader: def __init__(self, checker, size: int): self.checker = checker self.size = size def read(self, path: str): f = open(path, 'rb') data = [0] * self.size for i in range(self.size): data[i] = [0] * self.size col = 0 row = 0 ...
""" WSGI config for phleeb project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTIN...
"""config utilities for yml file.""" import logging import os import yaml class LoaderMeta(type): """Constructor for supporting `!include`.""" def __new__(mcs, __name__, __bases__, __dict__): """Add include constructer to class.""" # register the include constructor on the class cls =...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright [2017] Tatarnikov Viktor [viktor@tatarnikov.org] # # 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/licen...
""" Tests lightgbm->onnxmltools->hb conversion for lightgbm models. """ import unittest import warnings import sys import os import pickle import numpy as np from onnxconverter_common.data_types import FloatTensorType from hummingbird.ml import convert from hummingbird.ml import constants from hummingbird.ml._utils i...
#导入模块 import socket import random #创建实例 sk=socket.socket() #定义绑定的IP和port ip_port=("127.0.0.1"3334,) #绑定监听 sk.bind(ip_port) #最大连接数 sk.listen(5) #不断循环,不断接受数据 while True: #提升信息 print("正在进行等待接受数据......") #接受数据 conn, address=sk.accept() #定义信息 msg="连接成功!" #返回信息 #python3.x以上,网络数据的发送和接受都是byte类型 #如果发送的数据是str型则需要进行编码 ...
import sockets.routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( sockets.routing.websocket_urlpatterns ) ) })
from .schema import * from .api import * from ...datasets import ( list_datasets, load_dataset ) from .. import expr from .display import VegaLite, renderers from .data import ( pipe, curry, limit_rows, sample, to_json, to_csv, to_values, default_data_transformer, data_transformers )
"""Very simple example using a pair of Lennard-Jones particles. Requires the package `openmmtools` which can be installed from anaconda: `conda install -c omnia openmmtools` Openmmtools just provides a ready-made system for the lennard jones particles. This script is broken up into several parts: 1. Importing the p...
#!/usr/bin/env python # vim:et:ts=2:sw=2 import cgi, datetime, email.utils, json, re, time, urllib2 CONFIG_FILE = 'rssplus.config.json' URL = 'https://www.googleapis.com/plus/v1/people/%s/activities/public?key=%s' def error(msg): print('') print(msg + '.') exit(0) def convertUtf8(data): if isinstance(data, ...
from itertools import combinations_with_replacement as comb, product, combinations def must_consistent(part): must = [] for i in range(len(part)): must += list(comb(part[i], 2)) must += [(j, i) for i, j in must if i != j] return must def cannot_consistent(part): cannot = [] for i, ...
# Copyright 2019-2022 Huawei Technologies Co., Ltd # # 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 agre...
# A helper file to remove checkpoints until we figure out a solution from glob import glob from shutil import rmtree chkpoints = glob('./**/.ipynb_checkpoints', recursive=True) for ichk in chkpoints: rmtree(ichk)
#!/usr/bin/env python3 from distutils.core import setup setup(name='torsocks', version='1.0', description='a tool for using Tor hidden services.', author='kralverde', author_email='electrum.raven@gmail.com', url='https://github.com/kralverde/torsocks', packages=['torsocks'], )
from enum import unique from os import WEXITED from re import T from threading import current_thread try: import gstgva from gstgva.util import libgst, gst_buffer_data import gi gi.require_version('Gst', '1.0') from gi.repository import Gst from db_query import DBQuery from db_common import...
import re from maya import cmds import pyblish.api import pype.api import pype.hosts.maya.action def len_flattened(components): """Return the length of the list as if it was flattened. Maya will return consecutive components as a single entry when requesting with `maya.cmds.ls` without the `flatten` ...
#!/usr/bin/env python import urllib2 import sys, os PDB_PATH = "http://www.rcsb.org/pdb/files/%s" def help(): ''' Print help and exit. ''' print('Usage: %s <directory>' % sys.argv[0]) print('Parameters:') print('\t<directory> pointing to a path with \'list\' file of PDB structure names') print('Ex...
import inspect from sanic import Sanic from sanic.blueprints import Blueprint from sanic.response import json, text from sanic.utils import sanic_endpoint_test from sanic.exceptions import NotFound, ServerError, InvalidUsage # ------------------------------------------------------------ # # GET # ------------------...
# Generated by Django 2.0.6 on 2018-06-23 12:32 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UserModel', fields=[ ('id', models.AutoFiel...
import numpy as np import pandas as pd from math import isclose div_series = pd.read_csv("data/divisions.csv",index_col=0,squeeze=True) div_series.name = None teams = sorted(list(div_series.index)) tol = .0001 reverse_dict = {'Win':'Loss','Loss':'Win', 'Tie':'Tie'} def get_outcome(row): s = row["Points_scored"...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __a...
>>> import random >>> random.random() # Returns a floating-point number in 0.8545672259166788 # the range (0,1) >>> random.randrange(1,6) # Returns an integer in the 4 # range [1, 6) >>> random.uniform(1, 3) # Returns a floating-point number 1.290486289287417 # in the range [1, 3...
import torch import torchvision import torch.nn.functional as F from torch import nn, optim from torchvision import transforms, datasets import matplotlib.pyplot as plt import numpy as np import copy from scipy.special import expit # Training Options #=================================================================...
# Copyright (c) 2021 PaddlePaddle 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/LICENSE-2.0 # # Unless required by appli...
# -*- coding: utf-8 -*- import inspect from numbers import Number import numpy as np from ..constants import neutron_mass, hbar from ..crystal import Sample from ..energy import Energy from .exceptions import AnalyzerError, MonochromatorError, ScatteringTriangleError class _Dummy(object): r"""Empty class for co...
import os import pickle import random from datetime import datetime from app import db import numpy as np from random import randint from matplotlib import pyplot as plt from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.multioutput import MultiOutputClassifier from sklearn....
import time import numpy as np from ._helper_functions import estimate_error, get_observation_mask, update_log_prob_mask def iteration(con, obs_mask, obs_data_mask, obs_data, likelihood, resol_ctrl, acq, log_posterior, recon, log_weight_samples, num_obs, options): prob = np.exp(log_posterior) ...
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2010 Doug Hellmann. All rights reserved. # """Blank lines in the input cause mis-matches. """ #end_pymotw_header def double_space(lines): """Prints a list of lines double-spaced. >>> double_space(['Line one.', 'Line two.']) Line one. Line two...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() user_orm_label = ...
# -*- coding: utf-8 -*- from .filter_chat_id import FilterChatId
# Generated by Django 2.1.5 on 2020-04-29 20:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0004_auto_20200429_2208'), ] operations = [ migrations.AddField( model_name='spectatedcoordinates', name='gam...
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. import logging import unittest from collections import OrderedDict from copy import deepcopy import mxnet as mx import numpy as np from hypothesis import given, strategies as st from hypothesis.extra import numpy as hpnp from mxnet import nd fr...
# Code Listing #3 """ Maximum subarray problem - version #3 """ def max_subarray(sequence): """ Find sub-sequence in sequence having maximum sum """ # Trackers for max sum and max sub-array max_sum, max_sub = 0, [] for i in range(len(sequence)): for j in range(i+1, len(sequence)): ...
from __future__ import absolute_import import logging from django.shortcuts import render_to_response, render, get_object_or_404, redirect from django.template import RequestContext from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirec...
# Copyright 2018 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
from cocoa.web.main.utils import Messages as BaseMessages class Messages(BaseMessages): ChatCompleted = "Congratulations, you successfully completed the task!" ChatIncomplete = "Sorry, you weren't able to complete the task." Redirect = "Sorry, that chat did not meet our acceptance criteria."
import onnx from onnx import helper from onnx import TensorProto from enum import Enum def GenerateModel3(model_name, has_cast): nodes = [ # LayerNorm subgraph helper.make_node("Shape", ["input_ids"], ["shape1_out"], "shape1"), helper.make_node("Gather", ["shape1_out", "indices_0"], ["gather0_out...
# Copyright 2017 Google Inc. 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/LICENSE-2.0 # # Unless required by applicable law or a...
import logging import time import traceback import stopit from .errors import TimeoutError logger = logging.getLogger(__name__) def jsonify_error(error): error_type = error.__class__.__name__ message = str(error) return {'error': {'type': error_type, 'message': message}} def timeout(func, *args, sec...
from keras.preprocessing import image from tqdm import tqdm def path_to_tensor(img_path): img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) return np.expand_dims(x, axis=0) def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqd...
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Run regression test suite. This module calls down into individual test cases via subprocess. It will f...
from .constants import Constants version = Constants.MLOPS_CURRENT_VERSION __version__ = Constants.MLOPS_CURRENT_VERSION # TODO: switch to following #project_name = Constants.OFFICIAL_NAME # For now until name change project_name = Constants.OFFICIAL_NAME symlink_name = "mlops" from .versions import Versions from ...
from django.shortcuts import render from rest_framework import viewsets from rest_framework import (generics,permissions,renderers,) from commoninfo.permissions import IsOwnerOrReadOnly,CustomDjangoModelPermissions from facilities.models import StgHealthFacility from indicators.models import FactDataIndicator from hea...
# -*- coding: utf-8 -*- from functools import partial import torch from torchtext.data import Field, RawField from onmt.inputters.dataset_base import DatasetBase class TextDataset(DatasetBase): """ Build `Example` objects, `Field` objects, and filter_pred function from text corpus. Args: fi...
# coding: utf-8 """ Thola REST API for Thola. For more information look at our Github : https://github.com/inexio/thola # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest impor...
""" :author: Maikel Punie <maikel.punie@gmail.com> """ import json import velbus COMMAND_CODE = 0xbe class CounterStatusMessage(velbus.Message): """ send by: VMB7IN received by: """ def __init__(self, address=None): velbus.Message.__init__(self) self.channel = 0 self.puls...
from selenium.webdriver.common.by import By import time class ContactHelper: def __init__(self, app): self.app = app def open_contact_form(self): wd = self.app.wd wd.find_element(By.LINK_TEXT, "add new").click() def create_contact(self, contact): wd = self.app.wd ...
''' app.forms ~~~~~~~~~ Forms we need to use when posting datas in our website. flask_wtf.Form is still useable, but FlaskForm is suggested. ''' from flask_wtf import FlaskForm from wtforms import StringField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length from flask_babel import get...
from __future__ import print_function import numpy as np import time import pickle from pprint import pprint import openmdao.api as om from N3ref import N3, viewer prob = om.Problem() des_vars = prob.model.add_subsystem('des_vars', om.IndepVarComp(), promotes=["*"]) des_vars.add_output('inlet:ram_recovery', 0.99...
""" Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. For example: Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true. Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1,...
# 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 # d...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the co...
#!/usr/bin/env python import imp import os import setuptools requirements = { 'stylecheck': [ 'hacking', 'autopep8', ], 'test': [ 'numpy', 'pytest', ], 'travis': [ '-r stylecheck', '-r test', 'pytest-timeout', 'pytest-cov', ], ...
import numpy as np from time import time from collections import deque, namedtuple ''' frame_blobs() defines blobs: contiguous areas of positive or negative deviation of gradient. Gradient is estimated as |dx| + |dy|, then selectively and more precisely as hypot(dx, dy), from cross-comparison among adjacen...
# tests.cloud.core.__init__ is python-3.6 source file # MIT License # # Copyright (c) 2021 Handle. # # 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 restriction, including without ...
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com> # # 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 restriction, including without limitation ...
# -*- coding: utf-8 -*- """ Root system data for type F """ # **************************************************************************** # Copyright (C) 2008-2009 Daniel Bump # Copyright (C) 2008-2009 Justin Walker # Copyright (C) 2008-2009 Nicolas M. Thiery <nthiery at users.sf.net>, # # Distribut...
from http import HTTPStatus from typing import Optional, Type from marshmallow import Schema from {{cookiecutter.project_slug}}.lib.schemas.response import ( CreatedSchema, ForbiddenSchema, InternalServerErrorSchema, NotFoundSchema, OKSchema, UnauthorizedSchema ) class OperationSpec: def __init__( ...
"""An AdaNet estimator implementation which can run on TPU. Copyright 2018 The AdaNet 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 https://www.apache.org/licen...
# -*- coding: utf-8 -*- import time def test_minimum(app): app.group.open_group_editor() time.sleep(1) app.group.close_group_editor()
#!/usr/bin/env python import json import networkx as nx import matplotlib.pyplot as plt from graphviz import Source, render import sys if len(sys.argv) == 2: f = open(sys.argv[1]) json_data = "".join(f.readlines()) else: # Read from stdin json_data = "".join(sys.stdin.readlines()) python_data = json.l...
import imaplib from imbox.imap import ImapTransport from imbox.messages import Messages import logging from imbox.vendors import GmailMessages, hostname_vendorname_dict, name_authentication_string_dict logger = logging.getLogger(__name__) class Imbox: authentication_error_message = None def __init__(sel...
# coding=utf-8 """ This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import ...
from typing import Optional, Union import numpy as np from scipy import ndimage from reconstruction.data.chunks import ChunkGrid, Chunk from reconstruction.data.faces import ChunkFace bool_t = Union[bool, np.bool8] def dilate(image: ChunkGrid[bool_t], steps=1, structure: Optional[np.ndarray] = None, mask: ChunkGri...
from functools import lru_cache from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.orm.properties import ColumnProperty from .db import db class CRUDable(object): @classmethod def create(cls, fields): instance = db.add(cls()) instance.set_fields(fields) return...
""" When a PipelineExecuteResult (in JSON format) contains a result_uri list, read each of the files in that list and embed its results into the JSON Example: - If you see a file uri: { ... "progressInfo": "COMPLETED", "pipelineId": "pipeline_1", "pipelineInfo": { "predictResul...
#---------------------------------------------- #--- Author : Ahmet Ozlu #--- Mail : ahmetozlu93@gmail.com #--- Date : 27th January 2018 #---------------------------------------------- """A set of functions that are used for visualization. These functions often receive an image, perform so...
"""Exceptions for WordCounter""" class AccessLocalURI(PermissionError): """ User requested Local URI * Local file (file:///etc/resolv.conf.d/resolv.conf) * Intranet URI (https://cluster.local/dashboard) """ class NotAllowedScheme(AccessLocalURI): """ User requested not expected proto...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # ########################################################################## # # Note: this file is mostly copied from ...
import tkinter as tk from Bia import * from datetime import datetime def render(page: Page): FPS = 15 buffer = Queue() handle = HandleEvent(buffer) camera = Vision() camera.start() t = Timer(1/FPS, handle.timer) t.start() parent = page.parent() WIDTH, HEIGHT = parent.shape() ...
""" LFW dataloading """ import argparse import time import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms import glob import os import pandas as pd from torchvision.utils import make_grid import matplotlib.pyplot as plt import torchvi...
"""Start the clustering.""" # pylint: disable=C0103 from time import time import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import silhouette_samples from clustering.kmedoids import pam_npass from clustering.metrics import (dissimilarity_matrix, _dissimilarity_matrix, ...
import os import argparse from azureml.core import Workspace from azureml.core.environment import Environment from azureml.core.model import Model, InferenceConfig import shutil from ml_service.util.env_variables import Env e = Env() # Get Azure machine learning workspace ws = Workspace.get( name=e.workspace_name...
from selenium import webdriver class Scrap: def __init__(self, driver): self.driver = driver self.url = 'https://minecraft.gamepedia.com/Java_Edition_version_history' self.tables = 'wikitable' #class def navigate(self): self.driver.get(self.url) def get_tables(self): ...
import datetime from unittest import TestCase from module.analysis_util import the_closest_sprint_start_date, compose_search_jql_uri, get_last_sprint_duration class AnalysisUtilTest(TestCase): def setUp(self): pass @staticmethod def test_write_down(): # rows = ["testA1|testA2", "testB1|t...
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 30, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 12);
from __future__ import unicode_literals import frappe def execute(): if frappe.db.count("File", filters={"attached_to_doctype": "Prepared Report", "is_private": 0}) > 10000: frappe.db.auto_commit_on_many_writes = True files = frappe.get_all("File", fields=["name", "attached_to_name"], filters={"attached_to_docty...
import time import math from algosdk.logic import get_application_address from algosdk.future.transaction import LogicSigAccount, LogicSigTransaction, OnComplete, StateSchema, ApplicationCreateTxn, \ ApplicationOptInTxn, ApplicationNoOpTxn, OnComplete from .config import PoolStatus, Network, get_validator_index, g...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ##...
import numpy as np import h5py import os import torch import pdb from torch.utils.data import Dataset class TorchDataLoader(Dataset): """Class minibatches from data on disk in HDF5 format""" def __init__(self, args, region_dim, phrase_dim, plh, split): """Constructor Arguments: ...
import os import sys import tensorflow as tf import configparser FLAGS = tf.app.flags.FLAGS ## Configuration File Parse CONFIG_DIR = './config.ini' if len(sys.argv)>1 and sys.argv[1][-4:]=='.ini': CONFIG_DIR = sys.argv[1] CFP = configparser.ConfigParser() CFP.read(CONFIG_DIR) ARGS = CFP['Default'] ''' [Default] ...
# Copyright 2016 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/LICENSE-2.0 # # Unless required by applicable ...
import json from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch import pytest import numpy as np from metaspace.sm_annotation_utils import ( IsotopeImages, SMDataset, GraphQLClient, SMInstance, MolecularDB, ) from metaspace.tests.utils import sm, my_ds_...
""" GoalFunctionResult class ==================================== """ from abc import ABC, abstractmethod import torch class GoalFunctionResultStatus: SUCCEEDED = 0 SEARCHING = 1 # In process of searching for a success MAXIMIZING = 2 SKIPPED = 3 class GoalFunctionResult(ABC): """Represents ...
# Copyright (c) 2012 OpenStack Foundation. # 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/LICENSE-2.0 # # Unless...
# Copyright The PyTorch Lightning team. # # 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 i...
import keras import gin @gin.configurable def ResNet50(input_shape=None, pooling=None, classes=3): """Instantiates the ResNet50 architecture.""" img_input = keras.layers.Input(shape=input_shape) x = keras.layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(img_input) x = keras.layers.Conv2D(...
from __future__ import annotations import pytest from httpx import BasicAuth, Headers from pgrest import Client @pytest.fixture async def postgrest_client(): async with Client("https://example.com") as client: yield client class TestConstructor: @pytest.mark.asyncio def test_simple(self, postg...
# # PySNMP MIB module ROOMALERT24E-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ROOMALERT24E-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:49:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...