text
stringlengths
3.07k
12.6k
""" Translate an element, which is described by the YAML method file and a descriptor file, into a target function. Procedure: 1. When analyzing a YAML file, parse the call to the method-element, to get: - list of inputs, - list of outputs 2. Parse the YAML of that element, to know the name of the inputs and outputs...
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np import time import cv2 from real.camera import Camera from robot import Robot from subprocess import Popen, PIPE def get_camera_to_robot_transformation(camera): color_img, depth_img = camera.get_data() cv2.imwrite("real/temp.jpg", color...
# Header starts here. from sympy.physics.units import * from sympy import * # Rounding: import decimal from decimal import Decimal as DX from copy import deepcopy def iso_round(obj, pv, rounding=decimal.ROUND_HALF_EVEN): import sympy """ Rounding acc. to DIN EN ISO 80000-1:2013-08 place value = Rundest...
import importlib.metadata import logging import os import shutil from typing import Dict, Any, List import click from sqlalchemy import text from dbd.log.dbd_exception import DbdException from dbd.config.dbd_profile import DbdProfile from dbd.config.dbd_project import DbdProject from dbd.executors.model_executor impo...
from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout import tensorflow.keras as keras import os import cv2 import numpy as np from sklearn.model_selection import train_test_split def data_prep(path, img_rows, img_cols, color): """ A function to preprocess ...
from collections import namedtuple from dagster import check from dagster.config.config_type import ConfigType, ConfigTypeKind from dagster.config.field import Field from dagster.core.serdes import whitelist_for_serdes @whitelist_for_serdes class NonGenericTypeRefMeta(namedtuple('_NonGenericTypeRefMeta', 'key')): ...
import torch import torch.nn.functional as F import os.path as osp import json from torch_geometric.utils import precision, recall from torch_geometric.utils import f1_score, accuracy from torch.utils.tensorboard import SummaryWriter def train_epoch_classifier(model, train_loader, len_train, optimizer, device): m...
""" NODE model definition and experiment setup. Neural Oblivious Decision Ensembles for Deep Learning on Tabular Data https://arxiv.org/abs/1909.06312 Model details: https://pytorch-tabular.readthedocs.io/en/latest/models/#nodemodel """ import logging import os.path import shutil from sklearn.metrics import classif...
import re import argparse import os import sys import logging import traceback import pysatl class EtsiTs101955(object): COMMENT_MARKER = "REM" COMMAND_MARKER = "CMD" RESET_MARKER = "RST" INIT_MARKER = "INI" OFF_MARKER = "OFF" def __init__(self, cmdHandler): self._cmdHandler = cmdHandl...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import functools import torch.nn as nn from torch.nn import init import torch.functional as F from torch.autograd import Variable print('ok') def weights_init_normal(m): classname = m.__class__....
# Copyright 2020 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 applica...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import mojo_lexer import unittest # Try to load the ply module, if not, then assume it is in the third_party # directory. try: # Disable lint check which ...
""" This is the script containing the calibration module, basically calculating homography matrix. This code and data is released under the Creative Commons Attribution-NonCommercial 4.0 International license (CC BY-NC.) In a nutshell: # The license is only for non-commercial use (commercial licenses can be obtain...
from tkinter import * from tax_profiler import TaxProfile from tkinter import messagebox as mb class Example(Frame, TaxProfile): def __init__(self, parent): TaxProfile.__init__(self) Frame.__init__(self, parent, background="lightblue") parent.minsize(width=500, height=200) parent.m...
from __future__ import print_function import numpy as np import pandas as pd from sklearn import metrics class Options(object): """Options used by the model.""" def __init__(self): # Model options. # Embedding dimension. self.embedding_size = 32 # The initial learning rate. ...
# 2022 eCTF # Bootloader Interface Emulator # <NAME> # # (c) 2022 The MITRE Corporation # # This source file is part of an example system for MITRE's 2022 Embedded System # CTF (eCTF). This code is being provided only for educational purposes for the # 2022 MITRE eCTF competition, and may not meet MITRE standards for q...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import sys import shutil import onnx import onnxruntime import json from google.protobuf.json_format import MessageToJson import predict_pb2 import onnx_ml_pb2 # Current models only have one input and one output...
import json from datetime import datetime import time from functools import reduce import boto3 from celery import shared_task from celery.bin.control import inspect from django.conf import settings from comic.container_exec.backends.k8s import K8sJob from comic.eyra.models import Job, Submission, DataFile, JobInput ...
from . import scrip as t class misc(): ''' The class misc has miscellaneous methods of termuxa-pi available. Available methods are : battery, brightness, vibrate, contactlist, torch, downloadFile ''' def __init__(self): pass def battery(self): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------....
from __future__ import print_function import numpy as np import argparse import glob import os import errno import math import cv2 from random import shuffle from shutil import copyfile parser = argparse.ArgumentParser( description="create training/test/validation sets from video list" ) parser.add_argument("--vi...
# Built-in import os from glob import glob # Libs import numpy as np from tqdm import tqdm from natsort import natsorted # Own modules from data import data_utils from mrs_utils import misc_utils, process_block # Settings DS_NAME = 'spca' def get_images(data_dir, valid_percent=0.5, split=False): rgb_files = na...
"""Solution of the exercises of Optimization of compute bound Python code""" import math import cmath import numpy as np import numexpr as ne import numba as nb # Needed here since it is used as global variables # Maximum strain at surface e0 = 0.01 # Width of the strain profile below the surface w = 5.0 # Python: C...
from typing import Optional import napari import napari.layers import numpy as np from napari.utils.geometry import project_point_onto_plane def point_in_bounding_box(point: np.ndarray, bounding_box: np.ndarray) -> bool: """Determine whether an nD point is inside an nD bounding box. Parameters ---------...
import ipywidgets as widgets from traitlets import Unicode, Int, validate import os import json from datetime import datetime,timedelta from IPython.display import Javascript from IPython.display import HTML from cognipy.ontology import Ontology from IPython.display import clear_output _JS_initialized = False def _In...
# -*- coding: utf-8 -*- import sys import numpy as np import torch from torch.autograd import Variable from pytorch2keras.converter import pytorch_to_keras import torchvision import os.path as osp import os os.environ['KERAS_BACKEND'] = 'tensorflow' from keras import backend as K K.clear_session() K.set_image_dim_or...
# -*- coding: utf-8 -*- """.. moduleauthor:: <NAME>""" import abc from copy import copy from dataclasses import dataclass from multiprocessing.managers import SharedMemoryManager from multiprocessing.shared_memory import SharedMemory from typing import Tuple, List, Optional, final, TypeVar, Generic from torch.utils.da...
import unittest from kleat.hexamer.search import plus_search, minus_search, search from kleat.hexamer.hexamer import extract_seq class TestSearchHexamer(unittest.TestCase): def test_plus_search(self): self.assertEqual(plus_search('GGGAATAAAG', 9), ('AATAAA', 16, 3)) self.assertEqual(plus_search('...
# Lint as: python3 # Copyright 2020 Google LLC. 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 ...
from typing import Dict from numba import njit import numpy as np import matplotlib.pyplot as plt plt.rcParams['image.cmap'] = 'binary' def read_parameters(filename: str) -> Dict[str, float]: """Read parameters from a file to a dictionary and return it.""" parameters = {} with open(filename, "r") as file:...
from typing import List, Tuple import numpy as np import pymeshfix import trimesh.voxel.creation from skimage.measure import marching_cubes from trimesh import Trimesh from trimesh.smoothing import filter_taubin from ..types import BinaryImage, LabelImage def _round_to_pitch(coordinate: np.ndarray, pitch: float) ->...
from random import randint from typing import Callable, List, Optional class Coin: """Simulates a coin.""" def __init__(self) -> None: self.__head = False self.__toss_count = 0 self.__head_count = 0 def toss(self) -> None: """Toss a coin.""" r = randint(1, 2) ...
## @file # This file is used to define the FMMT dependent external tool management class. # # Copyright (c) 2021-, Intel Corporation. All rights reserved.<BR> # SPDX-License-Identifier: BSD-2-Clause-Patent ## import glob import logging import os import shutil import sys import tempfile import uuid from edk2basetools.FM...
import logging from http import cookiejar as http_cookiejar from http.cookiejar import http2time # type: ignore from typing import Any # noqa from typing import Dict # noqa from urllib.parse import parse_qs from urllib.parse import urlsplit from urllib.parse import urlunsplit from oic.exception import UnSupported f...
import decimal import hashlib import json import requests import tempfile import uuid import os from tqdm import tqdm from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor def sha256_for_file(f, buf_size=65536): pos = f.tell() dgst = hashlib.sha256() while True: data = f.read(bu...
import os from argparse import ArgumentParser from pathlib import Path from general_utils import split_hparams_string, split_int_set_str # from tacotron.app.eval_checkpoints import eval_checkpoints from tacotron.app import (DEFAULT_MAX_DECODER_STEPS, continue_train, infer, plot_embeddings, t...
# coding=<utf-8> import requests import re import socket import base64 import psutil import pywifi from pywifi import const import subprocess import os import time def get_host_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0...
""" 2018 (c) piteren some little methods (but frequently used) for Python """ from collections import OrderedDict import csv import inspect import json import os import pickle import random import shutil import string import time from typing import List, Callable, Any, Optional # prepares function parameters...
# Copyright 2020 <NAME> # # 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 the # rights to use, copy, modify, merge, publish, distribute...
from graph_peak_caller.multiplegraphscallpeaks import MultipleGraphsCallpeaks from graph_peak_caller.intervals import Intervals from graph_peak_caller import Configuration from graph_peak_caller.reporter import Reporter from offsetbasedgraph import GraphWithReversals as Graph, \ DirectedInterval, IntervalCollection...
import json import time import datetime import string import calendar from helpers import get_cpu_temp, check_login, password_hash import web import gv # Gain access to ospi's settings from urls import urls # Gain access to ospi's URL list from webpages import ProtectedPage, WebPage ############## ## N...
#!/usr/bin/env python3 """Simulation of Shor's algorithm for integer factorization.""" import cmath import math import numpy as np import random class QuMem: """Representation of the memory of the quantum computer.""" def __init__(self, t, n): """Initialize the memory. For Shor's algorithm we have t...
import os import shutil import tensorflow as tf from tensorflow import keras from logs import logDecorator as lD import jsonref import numpy as np import pickle import warnings from tqdm import tqdm from modules.data import getData config = jsonref.load(open('../config/config.json')) logBase = config['logg...
import json from configserver import ConfigServer, get_postgres_db from configserver.errors import InvalidRouteUUIDError from flask.testing import FlaskClient import pytest from peewee import SqliteDatabase import logging from uuid import uuid4 import functools from typing import Iterable @pytest.fixture(autouse=True...
#!/usr/bin/python3 # coding=utf-8 # 环境准备:pip install opencv_contrib_python # 输入话题:tianbot_mini/image_raw/compressed # 输出话题:roi import sys import os import rospy import sensor_msgs.msg from cv_bridge import CvBridge import cv2 import numpy as np from sensor_msgs.msg import RegionOfInterest as ROI from sensor_msgs.msg ...
def _doxygen_archive_impl(ctx): """Generate a .tar.gz archive containing documentation using Doxygen. Args: name: label for the generated rule. The archive will be "%{name}.tar.gz". doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir ...
# Fichier main de gestion des ressources du robot from micropython import const from machine import * from DRV8833 import * from BME280 import * import pycom import time import os # Variables globales pour moteurs et pont en H DRV8833_Sleep_pin = "P20" # Pin SLEEP DRV8833_AIN1 = "P22" # Entrée PWM moteu...
import random from collections import deque import networkx as nx from lib import puzzle def draw_grid(grid): min_y, max_y = 0, 0 min_x, max_x = 0, 0 for y, x in grid: if y < min_y: min_y = y if y > max_y: max_y = y if x < min_x: min_x = x ...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from dataclasses import dataclass from pants.backend.codegen.thrift.apache.subsystem import ApacheThriftSubsystem from pants.backend.code...
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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 ...
# -*- coding:utf-8 -*- import random import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from app.api.util.web_request import WebRequest, USER_AGENT_PC, USER_AGENT_MOBILE class SpiderWebDriver(object): def __init__(sel...
import boto3 from datetime import datetime, date import re import string import pandas as pd from spellchecker import SpellChecker import uuid import psycopg2 from psycopg2 import sql import sys sys.path.append('.') from rule_processing import postgresql def queryTable(conn, table): cmd = """ SELECT * FROM ...
import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.decomposition import IncrementalPCA as _IncrementalPCA from ..count_matrix.zarr import dataset_to_array def _normalize_per_cell(matrix, cell_sum): print('normalize per cell to CPM') if cell_sum is None: ...
import os from argparse import ArgumentParser from glob import glob import cv2 import numpy as np import torch import torchvision import matplotlib as mpl import matplotlib.pyplot as plt from PIL import Image from fiery.trainer import TrainingModule from fiery.utils.network import NormalizeInverse from fiery.utils.in...
import asyncio import discord from discord.ext import commands, tasks import os import random import dotenv import difflib import configparser ### version = '4.0.0' ### bot = commands.Bot(command_prefix = '!', owner_id = 272446903940153345, intents = discord.Intents.all()) bot.remove_command('help') co...
""" Base classes and utilities for all Xena Manager (Xena) objects. :author: <EMAIL> """ import time import re import logging from collections import OrderedDict from trafficgenerator.tgn_utils import TgnError from trafficgenerator.tgn_object import TgnObject, TgnObjectsDict logger = logging.getLogger(__name__) c...
# -*- coding: utf-8 -*- import click import logging from pathlib import Path import pandas as pd import re import string from nltk.corpus import stopwords def brand_preprocess(row, trim_len=2): """ This function creates a brand name column by parsing out the product column of data. It trims the words based on tri...
# coding=utf-8 # Author: <NAME> <<EMAIL>> import numpy as np import re class KeelAttribute: """ A class that represent an attribute of keel dataset format. """ TYPE_REAL, TYPE_INTEGER, TYPE_NOMINAL = ("real", "integer", "nominal") def __init__(self, attribute_name, attribute_type, attribute_rang...
import sys import os import json import csv from time import strftime from datetime import timedelta, date, datetime from flask import Blueprint, render_template, redirect, request, url_for, flash import server.configuration as cfg from server.postalservice import checkTemp from server.helpers import LoginRequired, p...
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # # All rights reserved. #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are # #met: # ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import xml.etree.ElementTree as ET tree = ET.parse(sys.argv[1]) old_doc = tree.getroot() tree = ET.parse(sys.argv[2]) new_doc = tree.getroot() f = file(sys.argv[3], "wb") tab = 0 old_classes = {} def write_string(_f, text, newline=True): for t in rang...
### #Various nose tests. If you want to adapt this for your own use, be aware that the start/end block list has a very specific formatting. ### import get_freebusy import arrow from operator import itemgetter from pymongo import MongoClient import secrets.admin_secrets import secrets.client_secrets MONGO_CLI...
import stomasimulator.geom.geom_utils as geom class AttributeCalculator(object): """ Abstraction for calculations performed on XPLT state data """ def __init__(self, prefix, reference_data, dimensionality, lambda_fn=None): self.prefix = '' if prefix is None else prefix self.reference_data = r...
import docker, os, platform, requests, shutil, subprocess, sys from .infrastructure import * # Runs a command without displaying its output and returns the exit code def _runSilent(command): result = SubprocessUtils.capture(command, check=False) return result.returncode # Performs setup for Linux hosts def _setupLi...
import sys import time from tia.trad.tools.io.follow import followMonitor import tia.configuration as conf from tia.trad.tools.errf import eReport import ujson as json import matplotlib.pyplot as plt import math import collections import logging from tia.trad.tools.ipc.processLogger import PROCESS_NAME LOGGER_NAME = P...
#!/usr/bin/env python3 # do not hesitate to debug import pdb # python computation modules and visualization import numpy as np import sympy as sy import scipy as sp import matplotlib.pyplot as plt from sympy import Q as syQ sy.init_printing(use_latex=True,forecolor="White") def Lyapunov_stability_test_linear(ev): ...
from __future__ import print_function import time import sys import os import shutil import csv import boto3 from awsglue.utils import getResolvedOptions import pyspark from pyspark.sql import SparkSession from pyspark.ml import Pipeline from pyspark.ml.feature import StringIndexer, VectorIndexer, OneHotEncoder, Vec...
from dataclasses import dataclass from datetime import datetime, timedelta import json import os.path from dateutil.parser import parse import pytz import redis from redis.lock import LockError import requests from . import settings from .logger import logger UNCACHED_HEADERS = ( 'Age', 'Cache-Control', ...
"""Author: Trinity Core Team MIT License Copyright (c) 2018 Trinity 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 the rights to use,...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import Path import pytest from pants.option.custom_types import ( DictValueComponent, ListValueComponent, UnsetBool, dict_with_files_option, dir_option, ...
from turtle import Turtle, Screen from random import choice from time import sleep from queue import SimpleQueue w: int w, h = (853, 480) wn = Screen() wn.screensize(w, h) wn.bgcolor("#d3d3d3") Room_state = {"Clean": "#FFFFFF", "Dirty": "#b5651d"} cleaned = 0 def filler(t, color, delay=0, vacclean = ...
import asyncio import pytest import re import uuid from aiohttp.test_utils import teardown_test_loop from aioredis import create_redis from arq import ArqRedis, Worker from atoolbox.db import prepare_database from atoolbox.db.helpers import DummyPgPool from atoolbox.test_utils import DummyServer, create_dummy_server fr...
""" imutils/big/make_shards.py Generate one or more webdataset-compatible tar archive shards from an image classification dataset. Based on script: https://github.com/tmbdev-archive/webdataset-examples/blob/7f56e9a8b978254c06aa0a98572a1331968b0eb3/makeshards.py Added on: Sunday March 6th, 2022 Example usage: pytho...
#!/usr/bin/python3 #### A tool for blocking all verified users on Twitter. ## You may want to create a (public or private) Twitter list named 'exceptions' and add verified users to it. ## This 'exceptions' list that you create on Twitter is for verified accounts that you like and do not want to block. #### Import dep...
### Data Preprocessing ## 1. Json to Transcript ## 2. Aligner ## 3. Text Replace from jamo import h2j import json import os, re, tqdm import unicodedata from tqdm import tqdm import hparams as hp name = hp.dataset first_dir = os.getcwd() transcript = name + '_transcript.txt' dict_name = name + '_k...
# Copyright 2019 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 applica...
from abc import ABCMeta, abstractmethod, abstractproperty from datetime import datetime, date class Item(metaclass=ABCMeta): def __init__(self, code, name, quantity, cost, offer): self.item_code=code self.item_name=name self.quantity_on_hand=quantity self.cost_price=cost sel...
# -*- coding: utf-8 -*- # # Copyright 2017 - Swiss Data Science Center (SDSC) # A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and # Eidgenössische Technische Hochschule Zürich (ETHZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
__all__ = [ 'Terminated', 'Unavailable', 'client', 'server', ] import logging import time import curio import nanomsg as nn from garage import asyncs from garage.assertions import ASSERT from garage.asyncs import futures from garage.asyncs import queues LOG = logging.getLogger(__name__) class Te...
# Based on spec_tests.py from # https://github.com/commonmark/commonmark-spec/blob/master/test/spec_tests.py # and # https://github.com/github/cmark-gfm/blob/master/test/spec_tests.py import sys import os import os.path import re import md4c import md4c.domparser import pytest from normalize import normalize_html ex...
"""Assimp-based analyzer.""" from __future__ import absolute_import import os import logging import subprocess import pyassimp from damn_at import ( mimetypes, MetaDataType, MetaDataValue, FileId, FileDescription, AssetDescription, AssetId ) from damn_at.pluginmanager import IAnalyzer from...
''' File: ebook_fix.py Created: 2021-03-06 15:46:09 Modified: 2021-03-06 15:46:14 Author: mcxiaoke (<EMAIL>) License: Apache License 2.0 ''' import sys import os from pprint import pprint from types import new_class from mobi import Mobi from ebooklib import epub import argparse from multiprocessing.dummy import Pool f...
# Copyright 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 agreed to...
import numpy as np from copy import copy from .utils.thresholdcurator import ThresholdCurator from .quality_metric import QualityMetric import spiketoolkit as st import spikemetrics.metrics as metrics from spikemetrics.utils import printProgressBar from collections import OrderedDict from sklearn.neighbors import Neare...
from __future__ import print_function import numpy as np from copy import copy import torch import torch.nn.functional as F from torch.autograd import Variable import torch.nn as nn def apply_var(v, k): if isinstance(v, Variable) and v.requires_grad: v.register_hook(inves(k)) def apply_dict(dic): fo...
# Code apapted from https://github.com/mseitzer/pytorch-fid """Calculates the Frechet Inception Distance (FID) to evalulate GANs The FID metric calculates the distance between two distributions of images. Typically, we have summary statistics (mean & covariance matrix) of one of these distributions, while the 2nd dist...
# Copyright 2020 Toyota Research Institute. All rights reserved. # Adapted from Pytorch-Lightning # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/loggers/wandb.py from argparse import Namespace from collections import OrderedDict import numpy as np import torch.nn as nn import w...
import sys import numpy as np import torch from monai import transforms, data from ..data import DataModule, ReadImaged, Renamed, Inferer ################################### # Transform ################################### def wmh_train_transform( spacing=(1.0, 1.0, 1.0), spatial_size=(128, 128, 128), num_patc...
from math import log2 import torch from torch import nn, einsum import torch.nn.functional as F from einops import rearrange from x_transformers import Encoder, Decoder # helpers def exists(val): return val is not None def masked_mean(t, mask, dim = 1): t = t.masked_fill(~mask[:, :, None], 0.) return t....
""" Climate Platform Device for Wiser Smart https://github.com/tomtomfx/wiserSmartForHA <EMAIL> """ import asyncio import logging import voluptuous as vol from functools import partial from ruamel.yaml import YAML as yaml from homeassistant.components.climate import ClimateEntity from homeassistant.core import cal...
import os from functools import partial from multiprocessing import Pool from typing import Any, Callable, Dict, List, Optional import numpy as np import pandas as pd from tqdm import tqdm from src.dataset.utils.waveform_preprocessings import preprocess_strain def id_2_path( image_id: str, is_train: bool = ...
#!/usr/bin/env python3 import os import boto3 import botocore.exceptions import argparse import yaml from nephele2 import NepheleError mand_vars = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'] perm_error = """\n\nIt seems you have not set up your AWS correctly. Should you be running this with Awssume? Or have profile...
# -*- coding: utf-8 -*- """ Created on Sat Feb 27 18:16:24 2015 @author: <NAME> A raíz del cambio previsto: DESCONEXIÓN DE LA WEB PÚBLICA CLÁSICA DE E·SIOS La Web pública clásica de e·sios (http://www.esios.ree.es) será desconectada el día 29 de marzo de 2016. Continuaremos ofreciendo servicio en la nueva Web del Op...
""" Defines models """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence from torch.nn.utils.rnn import pad_packed_sequence def init_weights(m): if type(m) == nn.Linear or ...
#!/usr/bin/env python ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test some MITAB specific translation issues. # Author: <NAME>, <even dot rouault at mines dash paris dot org> # ###################################################...
# -*- coding: utf-8 -*- # # Copyright (C) 2016 <NAME> <<EMAIL>> # Copyright (C) 2016 Rackspace US, Inc. # # 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...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# -*- test-case-name: vumi.tests.test_worker -*- """Basic tools for workers that handle TransportMessages.""" import time import os import socket from twisted.internet.defer import ( inlineCallbacks, succeed, maybeDeferred, gatherResults) from twisted.python import log from vumi.service import Worker from vumi....
#!/usr/bin/env python3 """ Copyright 2018 Couchbase, 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 ...
import os import sys import shutil import glob import time import multiprocessing as mp if len(sys.argv)!=4: print("Usage: ") print("python extract_features_WORLD.py <path_to_wav_dir> <path_to_feat_dir> <sampling rate>") sys.exit(1) # top currently directory current_dir = os.getcwd() # input audio direct...