text
stringlengths
3.07k
22.1k
# -*- coding: utf-8 -*- ''' © 2012-2013 eBay Software Foundation Authored by: <NAME> Licensed under CDDL 1.0 ''' import sys import lxml import copy import datetime from collections import defaultdict import json from ebaysdk.utils import get_dom_tree, python_2_unicode_compatible from ebaysdk import log @python_2_un...
import math def sram_profiling( trace_file=None, word_sz_bytes=4, # word size in bytes block_sz_bytes=16, # in byte for bank row bank=8, min_addr_word=0, max_addr_word=100000, access_buf=True ): """ this code takes non-stalling sram trace and reorganizes the trace to meet the ba...
from django.shortcuts import render,redirect,get_object_or_404 from .models import * from .forms import ContactForm from django.contrib import messages from django.http import HttpResponse,JsonResponse from django.contrib.auth.models import User from django.template.loader import render_to_string from django.db.models...
#!/usr/bin/env python # # MediaHouse libs resource unpacker/packer # # Authors: painter # Version: 1.0.0.5 # License: GPL v3 # # History: # 1.0.5 2020-07-30 Added RAW mode. # 1.0.4 2020-07-29 Implimented both version support. # 1.0.3 2020-07-29 Implimented WAV converter. # 1.0.2 2020-07-29 Implimented BMP converter...
import time import functools from django.conf import settings from django.utils.module_loading import import_string from django.db import connections from django.template import Template from django.core import cache from django.core.cache import CacheHandler from django.middleware import cache as middleware_cache fr...
# Copyright L.P.Klyne 2013 # Licenced under 3 clause BSD licence # # Counters # # Class to handle counters # # <NAME>, <NAME> 12th July 2010, changed to add 'set' action # # import logging from EventLib.Event import Event, makeEvent from EventLib.EventAgent import EventAgent from EventLib.EventHandler import Ev...
import json from torch.nn import Module, Linear, Dropout, Embedding, ModuleList, Sequential, LogSoftmax import torch from torch.optim import Adam, SGD from torch.utils.data import DataLoader import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter import math ADAM_ = Adam SGD_ = S...
""" Modification of Bert unsupervised training using a dataset that produces word and sentence masking on the fly (allows us to effectively use this as a regularizer) """ import tensorflow as tf import bert.modeling as modeling import bert.optimization as optimization def get_next_sentence_output(bert_config, inpu...
import multiprocessing import os import pandas as pd import sys import random import pytest as pt from brainex.database import genexengine as gxdb from brainex.utils import gxe_utils as gutils class TestGenex_database: num_cores = multiprocessing.cpu_count() def test_python_version(self): assert sys....
from utils.args import is_existing_file, is_valid_folder from utils.timer import timer import pandas as pd from spacy.matcher import PhraseMatcher import spacy from nltk.tokenize import RegexpTokenizer from pdfminer.high_level import extract_text, extract_text_to_fp from pdfminer.converter import TextConverter from pdf...
import logging import tensorflow as tf from .abstract_adapter import AbstractAlbertAdapter class AlbertAdapterForTensorFlow(AbstractAlbertAdapter): """Albert adapter for tensorflow""" def __init__( self, tf_albert_prefix="bert", tf_mlm_prefix="cls/predictions", tf_nsp_prefix...
# Copyright 2000 by <NAME> (Cayte). # Copyright 2016 by <NAME>. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. # # The original SeqGui was written by <NAME> (Cayte) in 2000 usi...
""" Mention Encoder Training. """ import argparse import logging import os import random import sys import tempfile import numpy as np import torch import transformers from tqdm import tqdm from meercat.models import MentionEncoderConfig, MentionEncoderModel import meercat.utils as utils logger = logging.getLogger(...
import requests, json, sys, smtplib from datetime import datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from tabulate import tabulate configuration = { 'smtp_host': '', 'sender': '', 'recipients': '', 'project_name': '', 'it...
# 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 ag...
import os import pytest import torch import ignite.distributed as idist from ignite.exceptions import NotComputableError from ignite.metrics import TopKCategoricalAccuracy def test_zero_div(): acc = TopKCategoricalAccuracy(2) with pytest.raises( NotComputableError, match=r"TopKCategoricalAccuracy mu...
import datetime import math import os import re import urllib from caselawclient.Client import ( RESULTS_PER_PAGE, MarklogicAPIError, MarklogicResourceNotFoundError, api_client, ) from django.conf import settings from django.http import Http404, HttpResponse from django.template import loader from djan...
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
import datetime import json from bson import json_util import utils.redis_utils import proxy_modules.utils class color: reset = "\u001b[0m" @staticmethod def red(text): return "\033[1;31;40m" + str(text) + color.reset @staticmethod def green(text): return "\033[1;...
# Import external modules from google.appengine.ext import ndb import json import logging import os import webapp2 # Import app modules from configuration import const as conf import httpServer import linkKey import proposal import reason import requestForProposals import user import text class SubmitNewReason(webap...
# ext/declarative/extensions.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php # mypy: ignore-errors """Public API functions and helpers for declar...
""" This module contains marshmallo schema definitions for loaded files. """ import collections from marshmallow import Schema, fields, ValidationError, pre_load, post_dump from mhdata.util import group_fields, ungroup_fields from mhdata import cfg from .cfields import ValidatedStr, ExcelBool class BaseSchema(Schem...
# Copyright 2021 solo-learn development team. # 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, publ...
import argparse import os import logging import shutil from dataclasses import dataclass from functools import partial from typing import Callable import sys import json import optuna import numpy as np import tensorflow as tf import transformers from sklearn.model_selection import train_test_split from tensorflow.ker...
# Utilities for dealing with survey data import pandas as pd # The below mapping works only with Corona dataset. Adjust them to your own need. PHQ2_MAP = { 'Little interest or pleasure in doing things.' : 'PHQ2_1', 'Feeling down; depressed or hopeless.' : 'PHQ2_2', } PSQI_MAP = { 'Currently; is your slee...
from rpython.jit.metainterp.test.support import LLJitMixin from rpython.rlib.jit import JitDriver from rpython.rtyper.test.test_llinterp import interpret from topaz.utils.ordereddict import OrderedDict class Runner(object): def __init__(self): self.functions = [] def func(self, f): self.func...
import os import os.path as op from copy import deepcopy from collections import defaultdict import logging import re import numpy as np import nibabel as nib from nipype.interfaces.base import ( TraitedSpec, traits, BaseInterface, BaseInterfaceInputSpec, File, Directory, isdefined) from banana.exceptions impor...
# -*- coding: utf-8 -*- """ Tools for drawing Python class inherit and MRO graphs with graphviz. Copyright (c) 2017-2018 <NAME> <<EMAIL>> Released under the MIT licence. """ # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Soft...
"""Support for Yamaha Receivers.""" from __future__ import annotations import logging import requests import rxv import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_MUSIC, SUPPORT_NE...
import matplotlib.pyplot as plt from data import waiting_time as rd fig = plt.figure() ax1 = fig.add_subplot(461) ax2 = fig.add_subplot(462) ax3 = fig.add_subplot(463) ax4 = fig.add_subplot(464) ax5 = fig.add_subplot(465) ax6 = fig.add_subplot(466) ax7 = fig.add_subplot(467) ax8 = fig.add_subplot(468) ax9 = fig.add_su...
import torch from torch.utils.data import DataLoader from torchvision import transforms import matplotlib.pyplot as plt import unet import numpy as np import dataset from PIL import Image import nibabel as nib from scipy import ndimage import os import csv import json from tqdm import tqdm import collections from evalu...
# Copyright 2014 NEC Corporation. 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 l...
import json import os import random import subprocess import sys from flask import Flask, Blueprint, render_template, request, redirect, jsonify, current_app from ..helpers import normalize_xpubs, convert_xpub_prefix, which from hwilib import commands as hwilib_commands from hwilib import base58 from .specter_hwi imp...
# Python modules import os import struct # 3rd party modules import pydicom import numpy as np from scipy.spatial.transform import Rotation # Our modules import vespa.analysis.fileio.raw_reader as raw_reader import vespa.common.util.config as util_config import vespa.common.util.misc as util_misc from vespa.analysis....
# Lint as: python2, python3 # pylint: disable=g-bad-file-header # Copyright 2019 DeepMind Technologies Limited. 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 # # htt...
""" Script used to create the quick index """ import re import os from pathlib import Path titles = { 'arcade_types.py': ['Arcade Data Types', 'arcade_types.rst'], 'application.py': ['Window and View', 'window.rst'], 'buffered_draw_commands.py': ['Drawing - Batch', 'drawing_batch.rst'], 'context.py': [...
"""Script to check the configuration file.""" import argparse import logging import os from collections import OrderedDict, namedtuple from glob import glob from platform import system from unittest.mock import patch import attr from typing import Dict, List, Sequence import voluptuous as vol from homeassistant impo...
import os import math import torch from torch import nn from torch.nn import functional as F # from repnet import repnet_deep, Bottleneck import sys sys.path.append(os.getcwd()) from tools.utils import print_log from torch.utils import model_zoo class Bottleneck(nn.Module): expansion = 4 def __init__(self, i...
""" This file holds models for comparison with RMDN. """ from keras.models import Model from keras.layers import Input, Convolution3D, MaxPooling3D, Flatten, Dropout from keras.layers import LSTM, Dense, TimeDistributedDense, Reshape, merge, Activation, Lambda from keras.utils.data_utils import get_file import keras.b...
#!/usr/bin/python3 # # Copyright 2018 The Sphinxd Authors. # # 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...
# python -m kg.freebase.inverted_index \ # --input freebase_name_subset.txt \ # --index_path /tuna1/indexes/kg-index/ \ # --index_file freebase_inverted_index.pkl import argparse import logging import os import datetime import gzip import spacy import unicodedata import json from sqlitedict import SqliteDict from mult...
import torch from ND_Crossentropy import CrossentropyND, TopKLoss from torch import nn from scipy.ndimage import distance_transform_edt import numpy as np def softmax_helper(x): # copy from: https://github.com/MIC-DKFZ/nnUNet/blob/master/nnunet/utilities/nd_softmax.py rpt = [1 for _ in range(len(x.size()))] ...
# Copyright 2018 <NAME> # # 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, soft...
#!/usr/bin/env python """ IceProd module for ``MuonGun`` simulations """ from icecube.simprod.util import ReadI3Summary, WriteI3Summary from icecube.simprod.util import CombineHits, DrivingTime, SetGPUEnvironmentVariables import os.path from icecube.simprod.util import simprodtray, arguments from icecube.simprod.util...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Perform functional tests to verify backward compatibility.""" import os import shutil import subprocess import pytest from pymongo import MongoClient import orion.core.io.experiment_builder as experiment_builder from orion.client import create_experiment from orion.cor...
############################################################################### # # Copyright (c) 2010 The MadGraph5_aMC@NLO Development team and Contributors # # This file is a part of the MadGraph5_aMC@NLO project, an application which # automatically generates Feynman diagrams and matrix elements for arbitrary # hi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2022 F4PGA Authors # # 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 # # Unl...
# # 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 # distributed under t...
""" Middleware for Proxito. This is used to take the request and map the host to the proper project slug. Additional processing is done to get the project from the URL in the ``views.py`` as well. """ import logging import re import sys from urllib.parse import urlparse from django.conf import settings from django.s...
# -*- coding: utf-8 -*- # Copyright © 2018 Red Hat 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 l...
## Imports import src.queries as q import plotly.express as px import plotly.graph_objects as go ## Styling margins = dict(l=1, b=10, r=1, t=7) fig_template = 'plotly_white' fig_bckg_col = 'rgb(248, 249, 250)' def missing_values_plot(continent_code='All', country_code='All'): """Takes a continent code and country...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ###...
''' Created on Oct, 2019 @author: albertgo ''' import logging import torch import numpy as np from abc import ABCMeta from abc import abstractmethod from typing import List, ClassVar, Sequence from tOpt.unit_conversion import Units from tOpt.coordinates_batch import SameSizeCoordsBatch from cddlib.chem.mol import Ba...
# coding: utf-8 # Python Machine Learning, PyTorch Edition by <NAME> (https://sebastianraschka.com), <NAME> # (https://www.mlexample.com/) & <NAME> (http://vahidmirjalili.com), Packt Publishing Ltd. 2021 # # Code Repository: # # Code License: MIT License (https://github.com/ LICENSE.txt) #############################...
import json import numpy as np import pandas as pd import re from Levenshtein import distance as word_dist from disjoint_set import DisjointSet pd.set_option("display.max_rows", 999) not_characters = [ "also", "not", "someone", "random", "no one", "everyone", "anybody", "anyone", "...
from typing import Optional, Union, List from ..arch.t5 import T5Configuration, T5 import cupy import numpy as np from ..utils.sampler import GenerateSampler import logging logger = logging.getLogger(__name__) SPAN_TOKEN = "<span>" class CPM2Configuration(T5Configuration): MODEL_NAME = "cpm2.1" class CPM2(T5): ...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np # In[2]: from torch.utils.data import Dataset, DataLoader from torchvision import transforms import torch # In[3]: from gensim.corpora.dictionary import Dictionary from gensim.utils import tokenize # In[4]: from pytorch...
import argparse from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import SGD from torch.optim.lr_scheduler import StepLR from torch.utils.data import DataLoader from torchvision.datasets import CIFAR10 from torchvision.transforms import ToTensor, Compose, Rand...
""" Copyright (c) 2019 Intel Corporation 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 writin...
# 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...
#!/usr/bin/env python # coding: utf-8 from PIL import Image import base64 import time import streamlit as st from datetime import datetime import folium from streamlit_folium import folium_static import ee import urllib, io, os from skimage import filters import numpy as np import pandas as pd import matplotlib.pyplo...
import asyncio import urllib.parse from asgiref.compatibility import guarantee_single_callable from ..bridge import bridge from .exceptions import Disconnect from .request import Request from .response import Response from .socket import Socket from .stream import SendFile # Jackie to ASGI async def get_request_b...
"""Utilities related to reading water cluster networks from disk""" from typing import Dict from ase import data import tensorflow as tf import networkx as nx import numpy as np def infer_water_cluster_bonds(atoms): """ Infers the covalent and hydrogen bonds between oxygen and hydrogen atoms in a water clus...
import hashlib class Mention: def __init__(self, doc_name, sent_num, start, end, words): self.doc_name = doc_name self.sent_num = sent_num self.start = start self.end = end self.words = words self.gold_parse_is_set = False self.gold_parse = None sel...
#!/usr/bin/python # ***************************************************************************** # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The A...
import io import csv import pickle import hashlib import argparse import numpy as np from tqdm import tqdm import tensorflow as tf import sentencepiece as spm import tensorflow_hub as hub from annoy import AnnoyIndex def parse_arguments(arguments=None): """Parse the command line arguments.""" parser = argpars...
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['pre...
#!/usr/bin/env pytest ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test OGR GMT driver functionality. # Author: <NAME> <<EMAIL>> # ############################################################################### # Copyright (c) 200...
#! /usr/bin/env python import os import numpy as np import astropy.io.fits as fits from . import noise_simulation as ng def add_dark_current(ramp, seed, gain, darksignal): """ Adds dark current to the input signal Parameters ---------- ramp: sequence The array of ramp images seed: i...
#!/usr/bin/env python3 import time import random import argparse from rowhammer_tester.scripts.utils import ( memfill, memcheck, memwrite, DRAMAddressConverter, litex_server, RemoteClient, get_litedram_settings, get_generated_defs, execute_payload) from rowhammer_tester.scripts.playbook.lib import (generate_p...
from __future__ import print_function import glob from itertools import chain import os import random import zipfile import argparse import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from linformer impo...
import operator from datetime import datetime from typing import Optional from dateutil.tz import gettz from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models import F, Func from django.utils import timezone from django.utils.timezone import localtime from config.cons...
#-*- coding:utf-8 -*- # Author:<NAME> # Datetime: Jan-10th 2021 19:10 # Project: GCR Fraud_detection_on_DGL Solution """ This is the entry point of SageMaker inference endpoint, it fulfills: 1. Receive request and parse out the heterogeneous graph and target node 2. But a DGL heterogeneous graph 3. Use...
# Code from - https://github.com/Cartucho/mAP import glob import json import os import shutil import operator import sys import argparse import math import matplotlib.pyplot as plt import numpy as np def log_average_miss_rate(prec, rec, num_images): """ log-average miss rate: Calculated by ...
# -*- coding: utf-8 -*- """Terrain types and management.""" # Part of Clockwork MUD Server (https://github.com/whutch/cwmud) # :copyright: (c) 2008 - 2017 <NAME> # :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) from os.path import dirname, exists, join from ...core.attributes import Unset fro...
# -*- coding: utf-8 -*- """ Ephemeris calculations using SunPy coordinate frames """ import numpy as np from astropy.coordinates import (SkyCoord, get_body_barycentric, ICRS, HeliocentricEclipticIAU76) from astropy.coordinates.representation import CartesianRepresentation from astropy....
from mpmath.libmp import (fzero, from_int, from_rational, fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub, mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin) from sympy.core.numbers import igcd from .residue_ntheory import (_sqrt_mod_prime_power, legendre_symbol, jacobi_symbol, is_...
# -*- coding: utf-8 -*- # MIT License # Copyright (c) 2021 Brokenwind # 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, ...
import torch import torch.nn as nn import torch.nn.functional as F import functools from .SurfaceClassifier import conv1_1, period_loss # from .DepthNormalizer import DepthNormalizer from ..net_util import * # from iPERCore.models.networks.criterions import VGGLoss from lib.model.Models import NestedUNet import numpy a...
from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np import scipy import scipy.stats # BCES fitting # =============== def bces(y1,y1err,y2,y2err,cerr): """ Does the entire regression calculation for 4 slopes: OLS(Y|X), OLS(X|Y), bisector, ...
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
from __future__ import annotations import argparse import atexit import dataclasses import io import json import os import platform import shutil import site import subprocess import sys import urllib.request from pathlib import Path from tempfile import TemporaryDirectory from typing import Sequence from pip import ...
import numpy as np import utills import plot import time import cv2 import os confid = 0.5 thresh = 0.5 mouse_pts = [] encodingImg = 0 class VideoCamera(object): def get_frame(self): success, FrameImage = self.video.read() ret, jpeg = encodingImg return jpeg.tobytes() def personPoint(p1,...
#!/usr/bin/env python3 import math from sympy import * zbb32 = None data32 = dict() data64 = dict() with open("synth.out", "r") as f: for line in f: line = line.split() if "32" in line[0]: data32[line[0].replace("_xlen32", "").replace("32", "").split(".")[-1]] = int(line[1]) // 4 ...
""" (C) Copyright 2021 IBM Corp. 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...
#!/usr/bin/env python3 # Copyright 2021 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...
import numpy as np import torch from torch import nn import torch.nn.functional as F # padding functionalities for batching from torch.nn.utils.rnn import pack_padded_sequence as unpack from torch.nn.utils.rnn import pad_packed_sequence as pack from utils import getlinear class Encoder(nn.Module): """Encoder clas...
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class WeightedMCEloss(nn.Module): def __init__(self ): super(WeightedMCEloss, self).__init__() def forward(self, y_pred, y_true, weight ): n, ch, h, w = y_pred.s...
from __future__ import print_function import os os.environ['KERAS_BACKEND'] = 'tensorflow' os.environ['CUDA_VISIBLE_DEVICES'] = '0' import numpy as np import pandas as pd import params from utils import get_data, get_best_history from utils import get_data_generator, get_data_generator_test from utils im...
from decimal import Decimal, getcontext import os getcontext().prec = 10 def line(): print() print("-=" * 30) print() def header(msg): line() print(f"{msg:^60}") line() def showMenu(): header("MENU PRINCIPAL") print("""[1] Calcular Frete [2] Calcular Preço de Venda [Com Frete Gráti...
r"""Computes the partition map for a segmentation. For every labeled voxel of the input volume, computes the fraction of identically labeled voxels within a neighborhood of radius `lom_radius`, and then quantizes that number according to `thresholds`. Sample invocation: python compute_partitions.py \ --input_...
################################################################################ # If not stated otherwise in this file or this component's Licenses.txt file the # following copyright and licenses apply: # # Copyright 2017 Liberty Global B.V. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may...
#! /usr/bin/env python3 # -*- coding: UTF-8 -*- #--------------------------------------------------------------------------------------------------- import sys, os #--------------------------------------------------------------------------------------------------- def ENDC () : return '\033[0m' #-----------------...
# This file is part of me-types-mapper. # # # Copyright © 2021 Blue Brain Project/EPFL # # # This program is free software: you can redistribute it and/or modify # it under the terms of the APACHE-2 License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
import struct import threading import uuid import lmdb import plyvel from dredis.path import Path from dredis.utils import FLOAT_CODEC NUMBER_OF_REDIS_DATABASES = 16 DEFAULT_REDIS_DB = '0' UUID_LENGTH_IN_BYTES = 16 # len(uuid.uuid4().bytes) == 16 class KeyCodec(object): STRING_TYPE = 1 SET_TYPE = 2 S...
# # Note: this code is not part of Pensieve. # # It serves as a comparison for another line of RL approaches, # which utilize Q learning in the basic tabular form. # # More details can be found in the following papers. # - Design of a Q-Learning based client quality selection algorithm for HTTP Adaptive Video Stream...
#!/usr/bin/env python3 # # Copyright (c) 2021, Arm Limited and affiliates. # SPDX-License-Identifier: Apache-2.0 # # 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...
import numpy as np import pandas as pd import requests from io import BytesIO from datetime import datetime import os import random from back.image_manager import TextImage dow = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"] sf_pairs = ["900-1030", "1040-1210", "1240-1410", "1420-1550", "1620-1750", "1800-1930"] start_d...
import logging import os from common.errors import MissingInputError TEMPLATES_DIR = os.path.realpath((os.path.join(os.path.dirname(__file__), "../../common/templates"))) ANSIBLE_ROOT = os.path.realpath((os.path.join(os.path.dirname(__file__), "../../../ansible"))) RUN_PLAYBOOK = os.path.realpath(os.path.join(os.path....
# -*- coding: utf-8 -*- # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # You can only use this computer program if you have closed # a license agreement with MPG or you get the right to use the computer # program from someone who is...