text stringlengths 3.07k 22.1k |
|---|
import os
import argparse
from configparser import ConfigParser
import time
import sys
import logging
import shutil
import pandas as pd
import numpy as np
import Metrics
parser = argparse.ArgumentParser()
parser.add_argument('--seq_len', type=int, default=6, help='sequence length of values, which should be even nums (... |
# Copyright (c) 2016-2020, <NAME>
# 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 conditions and the fol... |
#!/usr/bin/env python
# coding: utf-8
# ## Explore sample intersection between TCGA data types
#
# As we add more data types to our classification experiments, we've been filtering to only the set of samples that have data for each included data type. We want to know more about how many samples and which/how many can... |
import numpy as np
import random
import json
import os
import copy
import progressbar
params = {'step': 10, # step은 한번 sample을 뽑고 몇 frame 이동 후에 뽑을지 결정합니다.
'interval': 30, # interval은 sample을 최대 몇 frame 연속으로 이어 붙일지를 결정합니다.
'threshold': 30, # sample을 만들 때 투기 pose가 threshold값 이상이라면 sample도 투... |
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
from utils.train_util import generate_length_mask
class BaseDecoder(nn.Module):
"""
Take word/audio embeddings and output the next word probs
Base decoder, cannot be called directly
All decoders should inherit from this class
... |
#!~/envs/udacity_python3_mongodb
"""
Your task is to wrangle the data and transform the shape of the data
into the model we mentioned earlier. The output should be a list of dictionaries
that look like this:
{
"id": "2406124091",
"type: "node",
"visible":"true",
"created": {
"version":"2",
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#****************************************************************************************************************************************************
# Copyright 2017 NXP
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifi... |
import pytest
from number_parser import parse, parse_number, parse_fraction
from number_parser.parser import LanguageData, parse_ordinal
@pytest.mark.parametrize(
"test_input,expected,lang",
[
# empty / not-a-number
('', None, None),
('example of sentence', None, None),
# numer... |
import pandas as pd
import numpy as np
import os
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.tree import DecisionTreeClassifier
from corel... |
import sys
import psycopg2
import psycopg2.extras
import logging
import requests
import os
import dateutil
import chardet
from benedict import benedict
import traceback
psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)
token = f'Bearer {os.getenv("BUILDKITE_API_TOKEN")}'
def connect():
return psy... |
import types
import weakref
# To restore the old-style class behavior that __getattr__ also affects special
# methods.
class _MetaAttrProxy(type):
def __init__(self, name, bases, dct):
self._proxied_classes = weakref.WeakSet({type, object})
self._add_proxy_attr('__repr__')
def _add_proxy_attr... |
from __future__ import annotations
import copy
from typing import Callable, ClassVar, List, Optional, TypeVar
from typing_extensions import TypedDict
from ..configuration_support import Step, Configuration
from ..lib.ci_exception import SilentAbortException, StepException, CriticalCiException
from ..lib.gravity import... |
import logging
import time
import os
import re
from subprocess import Popen, PIPE
from datetime import date
from telegram import ReplyKeyboardRemove
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup,ReplyKeyb... |
'''
Description: Implements a Python dict, which allows for searching in
roughly O(1) time. There is chaining however, so
search times may be slightly decreased from O(1)
Author: <NAME>
Version: 0.9.9
C-level work - done
Implement __len__()
Implement _... |
"""
Unsupervised MoE Variational AutoEncoder (VAE)
==============================================
Credit: <NAME>
Based on:
- https://towardsdatascience.com/mixture-of-variational-autoencoders-
a-fusion-between-moe-and-vae-22c0901a6675
The Variational Autoencoder (VAE) is a neural networks that try to learn the
s... |
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from exporter.base import Exporter
from exporter.registry import exporter_registry
from .models import *
class CommonModelExporter(Exporter):
RENDU = _('rendu')
def __init__(self, queryset=None):
su... |
from argparse import ArgumentParser
import json
import scipy.io as sio
import sys
import os
import pandas as pd
import numpy as np
def parse_options():
parser = ArgumentParser()
#parser.add_argument("-a", "--all", required=False, default=False,
# action="store_true",
# ... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from builtins import range
from past.utils import old_div
from MeshTools import *
from FemTools import *
import numpy
def getEdgeNodesInPhysicalSpace(p0,p1,order):
"""
get Lagrange nodes for P^{order} assuming paramet... |
from mock import patch
from flexmock import flexmock
from sportsreference import utils
class SeasonStarts:
def __init__(self, league, month, expected_year):
self.league = league
self.month = month
self.expected_year = expected_year
class MockDateTime:
def __init__(self, month, year):... |
# -*- coding: utf-8 -*-
# _predictSNR.py
# Module providing predictSNR
# Copyright 2013 <NAME>
# This file is part of python-deltasigma.
#
# python-deltasigma is a 1:1 Python replacement of Richard Schreier's
# MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily based.
# The delta sigma toolbox is (c... |
# coding: utf-8
# Copyright (c) Henniggroup.
# Distributed under the terms of the MIT License.
from __future__ import division, print_function, unicode_literals, \
absolute_import
"""
The instrument module:
defines the inputset and the job
"""
import os
import shutil
import subprocess
import logging
from pymatg... |
from account.models import Report, User, Referee, Reporter
from league.models import Match, MatchImage
from django import forms
import datetime
import itertools
# Forms
class UpdateUserForm(forms.ModelForm):
class Meta:
model = User
fields = [
"first_name",
"last_name",
... |
# -*- coding: utf-8 -*-
import abc
import datetime
import sys
# Python 2/3 compatible `range` function
if sys.version_info < (3, 0):
range_func = xrange
else:
range_func = range
# Helper functions to convert between timestamps and datetimeobjects
timestamp_to_time = lambda t: datetime.datetime.fromtimestamp(t... |
import argparse
parser = argparse.ArgumentParser('Augmented CycleGAN')
parser.add_argument('--test', action='store_true', default=False, help='Train or test')
parser.add_argument('--latent_dim', type=int, default=16, help='Latent dimension')
parser.add_argument('--n_gen_filters', type=int, default=32, help='Number of ... |
from pathlib import Path
from pcbnewTransition import pcbnew, isV6
import json
import tempfile
import os
import subprocess
from pcbnewTransition.transition import isV6
from wand.api import library
from wand.color import Color
from wand.image import Image
from lxml import etree
from pcbdraw.pcbdraw import svg2ki
from... |
#!/usr/bin/env python3
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
import _init_paths
import argparse
import os, sys
import subprocess
from transforms3d.quaternions import mat2quat, ... |
import numpy as np
import json
from easyric.io import shp, json, geotiff
#################
# basic wrapper #
#################
def external_internal_calc(param, points, image_name, distort_correct=True):
"""
params
p4d: the Pix4D configure class
points: the nx3 xyz numpy matrix
... |
#!/usr/bin/env python3
import multiprocessing
from callgraphGen import gen_callgraphs, split_quoted
from genHalsteadMetrics import gen_halstead_metrics
import sys
import getopt
import os
import subprocess
import networkit as nk
from networkit.graphio import GraphWriter
from networkx import *
import ne... |
import math
#define the record data type of Companies
class Comp():
def __init__ (self):
self.name = ""
self.address = 0
self.payment = 0
self.type = 0
self.workTime = 0
#define the record data type of Users
class User():
def __init__ (self):
self.name = ... |
from functools import partial
from observ import reactive
import pytest
try:
from PySide6 import QtCore, QtGui, QtWidgets
except ImportError:
pytest.skip(
"skip test for PySide6 renderer when not available", allow_module_level=True
)
from collagraph import Collagraph, create_element as h, EventLo... |
"""
The util module contains a group of functions to process
model outputs
"""
import sys
import numpy as np
__all__ = ['dolp', 'dolp_l', \
'geometry_index', \
'radiance2bt', \
'scattering_angle']
###############################################################################
# Priv... |
# Copyright 2018 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 ... |
##
# @file global_swap.py
# @author <NAME>
# @date Jan 2019
# @brief detailed placement using global swap
#
import math
import torch
from torch import nn
from torch.autograd import Function
import dreamplace.ops.global_swap.global_swap_cpp as global_swap_cpp
import dreamplace.ops.global_swap.global_swap_concur... |
import os
import torch, torch.nn
import torch.optim as optim
from torch.autograd import Variable
from Logging import Log
from collections import OrderedDict
from utils import SaveNet
import configparser
from . import CustomLoss
#------------------------------------------------------------------------------------------... |
import networkx as nx
import stateTransitionDiagram as std
import argparse
import math
import StringIO
def ato_write_gml(graph, fileName, labelGraphics):
def writeDict(gml, key, label, contents, space, labelGraphics=None):
gml.write("{1}{0} [\n".format(key, space))
for subKey in contents:
... |
import os
import json
import logging
from typing import Union, List, Dict
from argparse import Namespace
from ..exceptions import CrawlinoFormatError, CrawlinoValueError
from crawlino.exceptions import CrawlinoMainCrawlerNotFound, \
CrawlinoMainCrawlerDuplicated
log = logging.getLogger("crawlino")
ALLOWED_CONFI... |
from __future__ import annotations
import os
import time
from abc import ABC, abstractmethod
from collections import Counter
from logging import Logger, getLogger
from typing import Any, Optional
import imblearn
import joblib
import lightgbm as lgb
import MeCab
import numpy as np
import pandas as pd
import tensorflow... |
import os
import sys
import re
import numpy as np
import pandas as pd
from collections import defaultdict
import requests
import json
import time
class AccountError(RuntimeError):
def __init__(self, account: str, message: str):
self.account = account
self.message = message
class NetworkError(Run... |
"""Visualization of pipeline nodes"""
import functools
import json
import flask
from mara_page import _, bootstrap, html, response, acl
from . import views, last_runs, dependency_graph, run_time_chart
from .. import pipelines, config
@views.blueprint.route('/<path:path>')
@views.blueprint.route('', defaults={'path... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
#!/usr/bin/env python
import os
import sys
import time
import traceback
import simplejson as jsmod
from datetime import datetime
from subprocess import Popen, PIPE
import logging
from logging.handlers import RotatingFileHandler
from constants import (
CLUSTER_INFO_FILE,
BACKUP_DIR,
LOG_DIR,
LOG_FILE,
... |
"""File utilities.
If a file descriptor is given for the parameter ``file`` it will be closed
after reading from/writing to the file.
For a list of supported encodings see
:ref:`Standard Encodings in module codecs <python:standard-encodings>`.
The default encoding is platform dependant.
For a list of error handlers ... |
# coding: utf-8
# 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 ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License... |
# -*- coding: utf-8 -*-
"""Tests for the canonicalization algorithm."""
import itertools as itt
import unittest
from typing import Sequence
from y0.dsl import A, B, C, D, Expression, One, P, Product, R, Sum, Variable, W, X, Y, Z
from y0.mutate import canonical_expr_equal, canonicalize
class TestCanonicalize(unitte... |
import pytest
import torch
from nequip.data import AtomicDataDict
from nequip.train import Loss
# all the config to test init
# only the last one will be used to test the loss and mae
dicts = (
{AtomicDataDict.TOTAL_ENERGY_KEY: (3.0, "MSELoss")},
{AtomicDataDict.TOTAL_ENERGY_KEY: "MSELoss"},
[AtomicDataDic... |
#!/usr/bin/python3
import argparse
import os, sys
import re
import gzip
import errno
from Bio import SeqIO
import pisces
import tempfile
import shutil
from urllib.request import urlretrieve
def pattern_to_regex(pattern):
pattern = pattern.replace('-','')
pattern = re.sub('\[([^[]*)>([^]]*)\]', '([\g<1>\g<2>]|... |
import pygame
import random
from main_objects.spaceship import Spaceship
from main_objects.evil_ship import EvilShip
from main_objects.friend_ship import friend_ship
from main_objects.asteroid.asteroid import Asteroid
from ConstantVars import Colors, Constants, GenFunctions
from Utilities import EyeGazeInstance
from Ut... |
import re
from nltk.tokenize import sent_tokenize
from lxml import html
from bs4 import BeautifulSoup
import itertools
def get_timeline(timeline_section):
timeline = []
if len(timeline_section) == 1:
timeline_blocks = timeline_section[0]
for a in timeline_blocks.xpath(".//ul/li"):
... |
# coding=utf-8
"""Provides RecurrentEventSet class."""
import datetime
import itertools as it
from collections import deque
import json
from six import string_types, integer_types
from six.moves import reduce # pylint: disable=redefined-builtin
from tempo.recurrentevent import RecurrentEvent
from tempo.sparseinterva... |
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import logging
import attr
import re
from requests import Session, Response
from random import choice
from bs4 import BeautifulSoup as bs
from six.moves.urllib_parse import urlparse, parse_qs
from six.moves import input
from ..models import User, Faceb... |
import random
import os
import discord
import aiohttp
import time
from dotenv import load_dotenv
from discord.ext import commands, tasks
from discord_together import DiscordTogether
bot = commands.Bot(command_prefix ='>', help_command=None, case_insensitive=True)
load_dotenv()
TOKEN = os.getenv("UNSEEBOT_... |
import os
from copy import deepcopy
from tqdm import tqdm
import torch
import torch.utils.data as data
from tree import Tree
from vocab import Vocab
import Constants
import utils
# Dataset class for SICK dataset
class SICKDataset(data.Dataset):
def __init__(self, path, vocab, num_classes):
super(SICKDatase... |
import json
import logging
import re
import socket
from urllib.parse import parse_qs, urlparse
from .proxy2 import ProxyRequestHandler
from .request import Request, Response
from .utils import is_list_alike
log = logging.getLogger(__name__)
ADMIN_PATH = 'http://seleniumwire'
class AdminMixin:
"""Mixin class th... |
import contextlib
import copy
import io
import itertools
import json
import logging
import os
import pickle
from collections import OrderedDict
import numpy as np
import pycocotools.mask as mask_util
import torch
from fvcore.common.file_io import PathManager
from pycocotools.coco import COCO
from pycocotools.cocoeval ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import namedtuple
from contextlib import contextmanager
import functools
import logging
import re
from pyramid.interfaces import IRoutesMapper
import jsonschema.exceptions
import simplejson
from pyramid_swagger.exceptions import RequestV... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
# This class can be imported into examples cripts to easily interact
# with a Spack Monitor interface. You can customize t... |
import collections
import random
import numpy as np
from config import Config
class ExperienceReplay(object):
""" Represents the experience replay memory that can be randomly sampled. """
def __init__(self, input_shape, num_actions, memory_size=100):
"""
Create a new instance of experience re... |
# -*- coding: utf-8 -*-
# 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 writing,... |
import re
import sys
var={}
operators = ['+', '-', '*', '/']
code = ""
class CompoundStatement:
def __init__(self, code_base, local_var=None):
self.string = code_base
self.list = code_base.split('\n')
# self.list.remove(' ')
#print(self.list)
while(1):
try:
... |
import uuid
import time
import sys
import select
from multiprocessing import Process, Queue, Value
import queue, threading
# import msvcrt
from pylsl import StreamInfo, StreamOutlet
import hackeeg
from hackeeg import ads1299
from hackeeg.driver import SPEEDS, GAINS, Status
DEFAULT_NUMBER_OF_SAMPLES_TO_CAPTURE = 5000... |
import json
import sys
import NamedPipes
import CCXTException
import asyncio
import cfscrape
import ccxt.async_support as ccxt
import os
from concurrent.futures import ThreadPoolExecutor
def run(corofn, *args):
loop = asyncio.new_event_loop()
try:
coro = corofn(*args)
... |
import random
from collections import Counter
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import Dataset
from base import BaseDataLoader
from data_loader import EcalDataIO
import os
import h5py
# ------------------------------------------------- DATALOADERS ----------------------... |
# -*- python -*-
"""
Either extracts an gzipped tar archive containing SNOPT source code located at
SNOPT_PATH or if SNOPT_PATH is "git", clones a remote git repository
containing SNOPT source code, checks out the specified branch, commit, or tag
and makes the targets available for binding.
If either branch or tag ar... |
"""Galaxy morphology module.
This module provides facilities to sample the sizes and ellipticities of
galaxies.
"""
__all__ = [
'angular_size',
'beta_ellipticity',
'early_type_lognormal_size',
'late_type_lognormal_size',
'linear_lognormal_size',
'ryden04_ellipticity',
]
import numpy as np
fr... |
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import sys
import codecs
import re
import numpy as np
# for linuxOS
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
def import_init() :
# アクセスするURL
url = "http://www.nikkei.com/markets/kabu/nidxprice/?StockIndex=N500"
html ... |
#!/usr/bin/env python
"""
Classes which define the individuals of a population with
its characteristic genes, generation, crossover and
mutation processes.
"""
from __future__ import annotations
import math
import pprint
import random
import multiprocessing as mp
from abc import ABC, abstractmethod
from tempfile impor... |
import github
import todoist
import requests
import datetime
import logging
import os
import json
import yaml
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
from typing import Dict
# TargetProcess specific logic
def getTargetprocessTasks(cfg:Dict) -> Dict[str, Dict]:
t... |
import io
import re
import csv
from bs4 import BeautifulSoup
from datetime import datetime
from holdings.dto import base
################################## Class Definitions #########################################
class ClassContract():
def __init__(self, ID, name, ticker = None):
self.ID = ID
... |
import json
from io import StringIO
import random
import webbrowser
import tempfile
import os
_HERE = os.path.dirname(os.path.abspath(__file__))
_TEST_FILEPATH = os.path.join(_HERE, 'examples', 'test.json')
_CSS_DEFAULTPATH = os.path.join(_HERE, 'style.css')
class HTML_Writer:
def __init__(self, cs... |
import torch.nn as nn
import torch
import numpy as np
import octree_handler
import depoco.architectures.original_kp_blocks as o_kp_conv
##################################################
############ NETWORK BLOCKS Dictionary############
##################################################
def printNan(bla: torch.tens... |
#!/usr/bin/env python
from io import BytesIO
import six
from sebastian.core import OFFSET_64, MIDI_PITCH, DURATION_64
def write_chars(out, chars):
out.write(chars.encode('ascii'))
def write_byte(out, b):
out.write(six.int2byte(b))
def write_ushort(out, s):
write_byte(out, (s >> 8) % 256)
write_b... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Copyright 2020 Google LLC
#
# 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, ... |
# __init__.py
#
# Copyright(c) <NAME> <<EMAIL>>
# Licensed under MIT
# Version 1.0.0
import os
import cv2
from multiprocessing.pool import ThreadPool
from collections import deque
# list of available background subtraction methods
SUBTRACTION_METHODS = ['absdiff', 'mog', 'mog2', 'knn']
# task to emulate threads
clas... |
import pandas as pd
import math, os, sys
"""
Usage: ./cd_spectra_mpl.py <file_or_folder>
Plots either a single CD spectrum or a folder of spectra.
"""
def parse_ascii(filename):
start = 0
xunits = None
yunits = None
y2units = None
enzyme_conc = None
with open(filename, 'r') as f:
pri... |
import serial
import time
import numpy as np
import cv2
import math
def get_chessboard(scale):
cols = 10
rows = 8
chessboard = np.zeros((rows, cols), np.uint8)
for x in range(0, cols):
for y in range(0, rows):
if x % 2 == y % 2:
chessboard[y, x] = 220
return cv... |
###############################################################################
# dominions #
#-----------------------------------------------------------------------------#
# #
... |
# Copyright (c) 2019, The Emergent Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from leabra import go, gi, giv, etable, etview, params
import pandas as pd
# ApplyParams applies params.Sheet to cls
def ApplyParams(cls, sheet, setMs... |
import json
import jsonpickle
import logging
import os
import havocbot.exceptions as exceptions
from havocbot.singletonmixin import Singleton
from havocbot.user import User, StasherClass
logger = logging.getLogger(__name__)
class Stasher(Singleton):
def __init__(self):
self.filename = None
self.d... |
import cv2
import numpy as np
from numba import jit
from math import fabs
delay = 20
def cleanImage(bin_img):
'''
Clean binary image
:param bin_img: binary image from background subtraction
:return: binary image cleaned
'''
n = 3
iter = 4 #3
iter_2 = 4
kernel = np.o... |
import torch
import numpy as np
class ParameterMasker(object):
"""
Adapted from Neural network distiller https://github.com/NervanaSystems/distiller
A ParameterMasker can mask a parameter tensor or a gradients tensor.
It is used when pruning DNN weights.
"""
def __init__(self, param_name):
... |
# Test cases for SCS
# Copyright (c) 2021, <NAME> <<EMAIL>>
# Copyright (c) 2021, The Linux Foundation
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import struct
import time
import hostapd
from utils import *
def register_scs_req(hapd):
type = 0x00d0
... |
# -*- coding: utf-8 -*-
'''
本脚本基于refinedet模型检测样本,并保存XML标签.
'''
import cv2
import argparse
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import skimage.io as io
# Make sure that caffe is on the python path:
caffe_root = './'
os.chdir(caffe_root)
sys.path.insert(0, os.path.join(caffe_root, 'pyth... |
global1 = 34
#print(global1)
def cambiar_global(val1):
'''Cambiar una variable global
Esta función debe asignarle a la variable global `global1` el valor que se
le pasa como único argumento posicional.
'''
global global1
global1 = val1
return global1
pass
cambiar_global(2)
def anio_b... |
""" HIERARCHY MODULE
Contains methods for managing the hierarchy of our library.
NOTE: The new API was added rather late, so isn't fully implemented.
There are plenty of cases where this could fail to do what a user wants.
However, the hierarchy should always stay in a valid state.
KNOWN LIMITATI... |
# Using the Keras functional API, constructs a network that functions as our
# prescriptor. For num_days days and NB_ACTION NPIs per day, we have
# num_days*NB_ACTION trainable weights, each representing the value of a
# specific NPI.
#
# Note: NB_ACTION here should be 12, the number of NPIs per day. NB_LOOKBACK_DAY... |
"""
Defines the functionality for prioritized sampling, the replay-buffer, min-max normalization, and parameter scheduling.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import typing
import numpy as np
from utils import DotDict
from utils.game_utils import GameState
@dataclass
cla... |
import json
import pandas as pd
import time
import numpy as np
pd.set_option('display.max_colwidth', -1)
##GENERAL
import time
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random
from collections import Counter
import csv
import re
import concurrent.futures
##SPACY
import spacy
nlp = s... |
import json
import os
import string
import time
import uuid
from enum import Enum
import azure.cognitiveservices.speech as speechsdk
import boto3
import inflect
import pvcheetah
import pvleopard
import requests
import soundfile
from deepspeech import Model
from google.cloud import speech
from ibm_cloud_sdk_core.authen... |
"""Tests for kalman"""
from copy import copy, deepcopy
import numpy as np
import pybayes as pb
from support import PbTestCase, stochastic
class TestKalmanFilter(PbTestCase):
"""Tests for kalman filter"""
def setUp(self):
# synthetic parameters. May be completely mathematically invalid
self... |
import os
import mxnet as mx
import lprnet_concat
from ctc_metrics import CtcMetrics,CtcMetrics2
import lstm
import logging
import numpy as np
import cv2
import math
class LPRIter(mx.io.DataIter):
def __init__(self, path_imgrec="", batch_size=128, data_shape=(3, 94, 24), path_imglist="",
label_wi... |
"""
Provides usable args and kwargs from inspect.getcallargs.
For Python 3.3 and above, this module is unnecessary and can be achieved using
features from PEP 362:
http://www.python.org/dev/peps/pep-0362/
For example, to override a parameter of some function:
>>> import inspect
>>> def func(a, b=1, c=2,... |
import os
import pickle
import pprint
import sys
from ego4d.utils import logging
import numpy as np
import pytorch_lightning
import torch
from ego4d.tasks.long_term_anticipation import MultiTaskClassificationTask, LongTermAnticipationTask
from ego4d.utils.c2_model_loading import get_name_convert_func
from ego4d.util... |
#!/usr/bin/env python3
import os
import sys
from subprocess import Popen, PIPE
import fcntl
import socket
def is_connected():
REMOTE_SERVER = {
"www.google.com": 80, # Google site
"8.8.8.8": 53, # Google dns server
"1.1.1.1": 53, # Clo... |
import numpy as np
import tensorflow as tf
import cv2
import time
import os, random, re, pickle
import imgaug as ia
from imgaug import augmenters as iaa
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [ atoi(c) for c in re.split('(\d+)', text) ]
# https://stackoverf... |
import os
import sys
import fnmatch
from pathlib import Path
from typing import Iterable
from collections import Counter
try:
import ctypes
except:
pass
from count_files.settings import TERM_WIDTH
from count_files.utils.file_handlers import get_file_extension
class BaseOS(object):
"""Superclass to work w... |
from __future__ import annotations
from inspect import signature
from typing import Dict, List, Optional, Tuple, Type, Union
from warnings import warn
from sanic.config import Config
from sanic.errorpages import (
DEFAULT_FORMAT,
BaseRenderer,
HTMLRenderer,
exception_response,
)
from sanic.exceptions ... |
'''Module for additional computations required by the model'''
from numpy import (arange, array, atleast_2d, concatenate, copy, cumprod, diag,
int64, ix_, ones, prod, where, zeros)
from numpy import sum as nsum
from scipy.sparse import csc_matrix as sparse
from scipy.special import binom
def within_household_s... |
import argparse
import os
import cv2
import json
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2
import mlflow
import utils
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, required=True, help='path of ex config')
parser.add_argument('--view_result', action='store_true', he... |
import matplotlib.pyplot as plt
from data_analysis.parallel_statistics.generate_parallel_speedup_md import *
relative_data_root_dir_path = '../..'
vldbj_mcap_tag = 'MCAP'
def get_name_dict():
with open('data_names.json') as ifs:
return eval(''.join(ifs.readlines()))
def draw_figures():
data_set_ls... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.