text stringlengths 3.07k 22.1k |
|---|
import logging
from enum import Enum, auto
from time import sleep
from threading import Thread
from typing import Union, List, Tuple, Callable, Optional
from inverter_wrapper import wrapper_instance as inverter
from inverterd import InverterError
_logger = logging.getLogger(__name__)
class BatteryPowerDirection(Enu... |
import unittest
import numpy as np
import pytest
from sympl import (
Prognostic, ensure_no_shared_keys, SharedKeyError, DataArray,
combine_dimensions, set_direction_names, Implicit, Diagnostic,
TendencyInDiagnosticsWrapper)
from sympl._core.util import (
update_dict_by_adding_another, get_component_ali... |
""" script for training a DCGAN on for given dataset """
import torch as th
import argparse
import numpy as np
from torch.backends import cudnn
from torchvision.datasets import CIFAR10
# define the device for the training script
device = th.device("cuda" if th.cuda.is_available() else "cpu")
# enable fast training
... |
# -*- coding: utf-8 -*-
###############################################################################
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#################... |
import sys, os
from os.path import join as pjoin
import io
import shutil
import math
from math import cos, sin, floor
import numpy as np
import scipy.io as sio
from raytrace import spottrace, beamtrace
from rotation import inv_rotbeam, rot_around_axis_rhs
from ct2mat import lookup_materials
import log
logger = log.ge... |
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
import numpy as np
# valid_mem_access_dict: key is block_id, value is a tuple of
# (block type, memory addr, block_size, access time interval)
def print_valid_mem_access_info(valid_mem_access_dict):
for k in valid_mem_access... |
"""Functions ported from tidyverse-tibble"""
from ..core.backends.pandas import DataFrame, Series, RangeIndex
from ..core.backends.pandas.api.types import is_scalar
from pipda import Context, register_verb
from ..core.utils import logger, regcall
from ..core.broadcast import broadcast_to
from ..core.tibble import (
... |
import re
import logging
import datetime
import random
from peewee import fn
from scrapy import Spider, Request
from scrapy.exceptions import CloseSpider
from crawler.intermedia import Movie
from crawler.items import MovieItem, Movie404Item
logger = logging.getLogger('MovieSpider')
class MovieSpider(Spider):
"... |
import os
from uliweb import settings, url_for
from uliweb.utils import files
from uliweb.utils.common import import_attr, application_path, log
import random
import time
import six
from uliweb.utils._compat import import_, string_types
unquote = import_('urllib.parse', 'unquote')
__all__ = ['save_file',... |
'''
Container classes for MIDI Patterns and Tracks
TODO: integer multiplication should extend a track/pattern, as with lists
TODO: respect pattern format, ignore header track when performing vectorized
operations
TODO: see if getitem makes weirdness happen with slicing
TODO: should tracks care if they have rel... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
"""
Contains class Features that provides basic functionality for the analysis of
segmented images.
# Author: <NAME> (Max Planck Institute for Biochemistry)
# $Id$
"""
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import object
from past.builtins import basestring
__ve... |
import copy
import sys
import math
from collections import defaultdict, deque
import numpy as np
from sklearn.metrics import cohen_kappa_score
from skmultiflow.drift_detection.adwin import ADWIN
from skmultiflow.trees.arf_hoeffding_tree import ARFHoeffdingTree
from LRU_state import LRU_state
from state_graph import L... |
import enum
from argparse import ArgumentParser
from collections import defaultdict
from pathlib import Path
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch as th
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import Binarizer, OrdinalEncoder
from torch._uti... |
#! /usr/bin/env python
import sys
import copy
import rospy
import time
import numpy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
from math import pi
from std_msgs.msg import String, Int8, Bool
from moveit_commander.conversions import pose_to_list
from geometry_msgs.msg import Pose
from sensor... |
from gevent.queue import Queue
import gevent.pool
import sys
import json
import requests
import uuid
import time
from .utils import LcApiException
_CLOUD_KEEP_ALIVES = 60
_TIMEOUT_SEC = ( _CLOUD_KEEP_ALIVES * 2 ) + 1
class Spout( object ):
'''Listener object to receive data (Events, Detects or Audit) from a lima... |
# Redirect output to a HTML file and view it in your browser
import math
from dataclasses import dataclass
from ovld import has_attribute
from hrepr import H, Hrepr, hrepr
@dataclass
class Point:
x: int
y: int
class Color:
def __init__(self, r, g, b):
self.r = r
self.g = g
sel... |
#!/usr/bin/env python
#
#
from pprint import pprint, pformat
from decimal import Decimal
import requests
from requests.exceptions import RequestException
import json
import base64
import hmac
import hashlib
import time
import logging
logger = logging.getLogger('bitfinex_api')
logger.setLevel(logging.DEBUG)
def mai... |
import argparse
import os
import sys
import time
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
import utils
from ... |
import unittest
import build_utils as bu
import datetime
def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
if loader.testMethodPrefix != 'test':
test_cases = loader.testMethodPrefix.split(',')
for i in range(len(test_cases)):
test_cases[i] = __name__ + '.' + ''.j... |
import Pyro4
from node.libs import utils
import time
from node.libs.publication import Publication
from node.libs.subscription import Subscription, dict_to_class
import threading
from threading import Thread
from termcolor import colored
from node.libs.botlogging import botlogging
from ordered_set import OrderedSet
SE... |
''' trello.py
Contains the TrelloBoard and TrelloCard classes
plus methods related to Trello.
'''
import urllib.request, json, re, datetime
import utils
# A Trello board contains the identifier, a name, and an indicators
# whether the board closed.
class TrelloBoard:
# The constructor.
def __init__(self, id... |
# References:
# 1. https://hdbscan.readthedocs.io/en/latest/performance_and_scalability.html
from cluster_losses import *
from cluster_metrics import *
from corpus_estimation import *
from sklearn.decomposition import TruncatedSVD, PCA, NMF, SparsePCA, FastICA
from sklearn.preprocessing import MinMaxScaler
... |
# The original architecture
import torch
import torch.nn as nn
# ====================================================== Resnet50 ======================================================
## Refer to: torchvision.models.resnet50
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution wit... |
#!/usr/bin/env python3
"""Applies changes from mkdocs-material to the current directory.
The upstream mkdocs-material revision on which the current directory is based is
assumed to be stored in the MKDOCS_MATERIAL_MERGE_BASE file.
This script computes the differences between that revision and the current
master branc... |
# pylint: skip-file
import datetime
import os
import re
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import requests
from dms_daemon import CONFIG
def notice_list():
for root, _, files in os.walk("/data/marble/nemweb/MARKET_NOTICES/"):
for f in files... |
import datetime
import logging
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from torch.autograd import Variable
from torch.optim import SGD
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torchvision import transfo... |
import sys
sys.path.append('../../pySuStaIn/')
sys.path.append('../evaluation/')
import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
import pickle
from pathlib import Path
import sklearn.model_selection
import pandas as pd
import pylab
# import the simulation functions from pySuStaIn needed to ... |
import json
import re
import os
import random
import math
from typing import Tuple, List, Dict, Any, NewType, Union
import numpy as np
from constants import FB_REACTIONS
import utils
DATA_UTIL_DIR = os.path.dirname(__file__)
DEFAULT_COMMENT_COUNT = 0
CONFESSION_NUMBER_INDEX = 0
CONFESSION_TEXT_INDEX = 1
CONFESSION_... |
import tensorflow as tf
from horror.data.input import EMBEDDING_SIZE
from horror.data.utils import CLASSES
from horror.utils import DictWrapper
class Features(DictWrapper):
def __init__(self):
self.id = None
self.text = None
self.text_length = None
class Labels(DictWrapper):
def __i... |
"""Alarm Functions.
The following functions give you access to view and interact with the
Alarm system in Ignition.
"""
from __future__ import print_function
__all__ = [
"acknowledge",
"cancel",
"createRoster",
"getRosters",
"getShelvedPaths",
"listPipelines",
"queryJournal",
"querySt... |
import requests
import sys
import textwrap
import shutil
from googlesearch import search as sea
searchterm = sys.argv[1]
metric = sys.argv[2]
def search(searchterm, metric):
Collection = {}
base_link = "https://services.nvd.nist.gov/rest/json/cves/1.0?keyword="
link = base_link + searchterm
response =... |
#!/usr/bin/env python2.7
'''A tool for determining the UVIT FUV and NUV filters.
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.or... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 01:19:57 2018
@author: farzeen
"""# -*- coding: utf-8 -*-
"""
Created on Wed Sep 21 01:36:58 2016
@author: likui
"""
from CDhitMIL import *
from amyloids import *
from customized import *
import numpy as np
import pickle
from sklearn.externals impor... |
#<NAME> and <NAME>
#CSCI 466
#PA3
#November 2, 2018
import queue
import threading
## wrapper class for a queue of packets
class Interface:
## @param maxsize - the maximum size of the queue storing packets
def __init__(self, maxsize=0):
self.queue = queue.Queue(maxsize);
self.mtu... |
'''
The MIT License (MIT)
Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
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 ... |
"""Solve mazes."""
# MIT License
#
# Copyright (c) 2022 <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, ... |
"""
Video class. Properties:
- length: Return a Duration object representing the video duration.
Based on raw duration fields `duration` and `duration_time_base`, we have: ::
duration = (number of seconds) * duration_time_base
So: ::
(number of seconds) = duration / duration_time_base
"""
from typing i... |
import os
import glob
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data_utils
from torch.autograd import Variable
from sklearn import svm, preprocessing
from sklearn.model_selection import train_test_split, KFold
from sklearn.metrics import classifi... |
from collections import OrderedDict
import gym
import numpy as np
from robogym.robot.shadow_hand.hand_forward_kinematics import (
FINGERTIP_SITE_NAMES,
REFERENCE_SITE_NAMES,
)
from robogym.utils.sensor_utils import check_occlusion, occlusion_markers_exist
from robogym.wrappers import randomizations
class Ra... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions for scraping a single listing with beautifulsoup."""
# pylint: disable=invalid-name,broad-except
import os
import numpy as np
import pandas as pd
from src.utils import regex_get_num_from_str
def get_price_from_listings_page(soup):
"""Get l... |
"""oas_dataservice module for mapping a openapi-specification to dcat rdf.
This module contains methods for mapping an openAPI specification to rdf
dcat:DataService according to the
`dcat-ap-no v.2 standard <https://doc.difi.no/review/dcat-ap-no/#klasse-dataset>`__
Example:
>>> import yaml
>>> import requests... |
from flask import Flask, render_template, request
import requests as req
import speech_recognition as sr
from commands.command import run_command
from docker.python_on_docker import python_on_docker
from docker.httpd_on_docker import httpd_on_docker
from hadoop.hadoop_cluster import create_hadoop_cluster
from kubernet... |
from collections import defaultdict
from copy import deepcopy
from datetime import date, datetime
import pickle
import re
import os
from mintamazontagger import category
from mintamazontagger.currency import micro_usd_to_usd_string
from mintamazontagger.currency import parse_usd_as_micro_usd
from mintamazontagger.curr... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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, or (at your option) any later version.
#
# This program is distrib... |
from functools import total_ordering
TANK_DAMAGE = 10
BIG_FORT_DAMAGE = 10
SMALL_FORT_DAMAGE = 5
BIG_FORT_REWARD = 70
SMALL_FORT_REWARD = 50
BIG_CITY_PENALTY = 150
SMALL_CITY_PENALTY = 120
def eval_state(state):
from scaii.env.sky_rts.env.scenarios.city_attack import UnitType, Actions
enemy_tank = None
... |
import datetime
from unittest.mock import patch
from django.core.validators import ValidationError
from django.db import models
from django.test import TestCase
import pytest
from mep.accounts.models import Account, Borrow
from mep.accounts.partial_date import DatePrecision, DatePrecisionField, \
PartialDate, Par... |
import argparse
import os
import numpy as np
import pandas as pd
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from pytorch_pretrained_bert import BertModel
from torchvision import transforms
from torch.optim import RMSprop
from utils.text_p... |
# Copyright (c) 2017-2018 <NAME>
#
# SPDX-License-Identifier: BSD-3-Clause
# The BSD-3-Clause license for this file can be found in the LICENSE file included with this distribution
# or at https://spdx.org/licenses/BSD-3-Clause.html#licenseText
import os
import uboot
from .base import DatSegBase, get_full_path
from vo... |
import logging
import urllib
from uuid import UUID
from django.db import transaction
from django.db.models import F
from django.utils import timezone
from rest_framework import status
from rest_framework.exceptions import APIException
from django.conf import settings
from api.audit_trail import service as audit_trail... |
#! /usr/bin/env python
import collections
import math
import random
import processing
import vector
################################################################################
# QVGA Resolution
WIDTH = 320
HEIGHT = 240
################################################################################
class Demo(... |
from datetime import time
import pandas as pd
import numpy as np
from pydsstools.heclib.dss import HecDss
from pydsstools.core import TimeSeriesContainer, HecTime
import altair as alt
from altair import datum
from altair_saver import save
import os
alt.data_transformers.disable_max_rows()
alt.renderers.enable('altair_v... |
""" image / camera intrinsics functions
wip. options built to match various projects
"""
import numpy as np
import torch
from .utils import ObjDict
# pylint: disable=no-member
def undistorted_rays(xy, xy0, ks, ps):
rad = torch.sum(xy**2, axis=-1, keepdims=True)
dist = 1.0 + rad * (ks[0] + rad * (ks[1] + ks[2... |
import gym
import gym_tool_use
import numpy as np
import random
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from torch.optim import Adam
from tqdm import tqdm
from collections import deque, namedtuple
from ddqn_agent import DQN
from ICModule import ICM
#seed
np.random.seed(7)
random.seed(7)
if ... |
# -*- coding: utf-8 -*-
from unittest.mock import Mock, patch
import pytest
from jaffle.variables import VariablesNamespace
NOT_FOUND = VariablesNamespace._NOT_FOUND
def test_init():
vn = VariablesNamespace()
assert vn._variables == {}
assert vn._keep_undefined_vars is False
vn = VariablesNamespa... |
from random import choice, randrange
from custom_graphics import draw_dashed_line
from map_lanker import LankerCar
from map_i80 import I80, colours
from traffic_gym import Simulator
import pygame
import pandas as pd
import numpy as np
import pdb, random
import bisect
import pdb, pickle, os
# Conversion LANE_W from re... |
import pickle
with open("deepmind_assets/language_perceiver_io_bytes.pickle", "rb") as f:
params = pickle.loads(f.read())
from perceiver_io.perceiver_im import PerceiverLM
#from data import MNISTDataModule
import torch.nn as nn
import torch
import torchvision
import torchvision.transforms as transforms
from sklearn... |
# ============================================================================
# Author: <NAME>
# ----------------------------------------------------------------------------
# Contains LS-PrePost macros used in completing thesis
# ============================================================================
impo... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... |
import re
import bz2
import xml.etree.ElementTree as ET
from difflib import SequenceMatcher, Match
import sys
import json
from collections import defaultdict
import mwparserfromhell
from piecewise import dochunk, DoChunkCache
import os
def normalizeWord(word):
if '|' in word:
return word.split('|')[-1]
... |
# Distributed under the Apache License, Version 2.0.
# See accompanying NOTICE file for details.
import sys
import numpy as np
from pyproj import Geod
from shapely.geometry import Point
_wgs84_geod = Geod(ellps='WGS84')
class Detection(object):
__slots__ = ['frame_number',
'tracking_plane_loc_x'... |
import logging
import random
from sys import maxsize
class Model:
""" This is the base class for the ABM model.
You inherit this class to again access to all of the ECS functionality """
__slots__ = ['environment', 'systemManager', 'random', 'logger']
def __init__(self, seed: int = None, logger=None... |
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# 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, di... |
class DBXRef:
def __init__(self, dbname, dbid, reftype = None, negate = 0):
self.dbname = dbname
self.dbid = dbid
self.reftype = reftype
self.negate = negate
def __str__(self):
if self.reftype is None:
reftype = ""
else:
reftype = self.ref... |
from decimal import Decimal
import datetime
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext as _
from django.core.exceptions import ValidationError
from oscar.apps.offer.managers import ActiveOfferManager
SITE, VOUCHER, USER, SESSION = ("Site", "... |
#!/bin/env python
"""
Copyright 2019 Trustees of Indiana University
This file is distributed under the Apache 2 License
Programmed by <NAME> (<EMAIL>)
-------
This will detect the perforations in a frame image and
determine the top edge of the upper perf, the
bottom edge of the lower perf, and the right edge of
bot... |
import re
from bs4 import BeautifulSoup
from sentence_transformers import SentenceTransformer
# import pandas as pd
from collections import Counter
class TextualExtractor:
"""
Extract textual features from the html content of a webpage
"""
xlmr = None
def __init__(self, device='cpu'):
if ... |
from __future__ import annotations
import json
import logging
from typing import Any, Dict, Literal, Optional
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound
from django.shortcut... |
# 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, ... |
"""
Script is a duplicate of
https://github.com/pytorch/pytorch/blob/v1.1.0/torch/utils/data/dataloader.py
Except this dataloader makes use of datasets that takes in list for __getitem__
"""
import torch.utils.data
import torch.multiprocessing as multiprocessing
from torch.utils.data import SequentialSampler, RandomSa... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
######################################################################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
# ===================================================
# @author <NAME>
# @email <EMAIL>
# @author <NAME>
# @email <EMAIL>
#
# Copyright (C) 2019 <NAME>, <NAME>
# All rights reserved. (Apache License 2.0)
# ===================================================
from __future__ import print_function
from __fu... |
import math
import random
import time
from collections import defaultdict, Counter
from typing import Tuple, List, Union
import numpy as np
import torch
from agents.belief_agent import BeliefBasedAgent
from agents.models.model_based_models import ApprenticeModel
from agents.models.multitask_models import MultitaskApp... |
"""
monodromy/backend/lrs.py
Communication interface for `lrs`, a package for convex hull problems.
More information about `lrs`: http://cgm.cs.mcgill.ca/~avis/C/lrs.html
"""
from copy import copy
from fractions import Fraction
from functools import reduce
import math # for gcd
from operator import itemgetter
from... |
import torch
from torch import nn
import dgl
import dgl.function as fn
import torch.nn.functional as F
from neuralkg.model import ConvE
class CompGCN(nn.Module):
"""`Composition-based multi-relational graph convolutional networks`_ (CompGCN),
which jointly embeds both nodes and relations in a relational ... |
#!/usr/bin/env python3
from sys import argv,version_info,stderr
from getpass import getpass
import urllib3,logging,json
from io import BytesIO
from zipfile import ZipFile
from lxml import etree
from urllib3._collections import HTTPHeaderDict
assert version_info >= (3,)
VERSION=(0,1,1)
class SecurityCenterAPI:
def ... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Download class for gammapy download CLI."""
import hashlib
import json
import logging
import sys
import yaml
import multiprocessing
from urllib.request import urlretrieve, urlopen
from pathlib import Path
from .. import version
log = logging.getLogger(... |
import json
import sys
from typing import List
import pandas as pd
import argparse
from sklearn.model_selection import train_test_split
import logthis
from preprocessing import preprocess_file
from util.utils import BASE_CATEGORIES, getCategories
from Evaluation.evaluation import Evaluator
from Evaluation.prediction i... |
""" Vagrant utilities. """
import collections
import pathlib
import subprocess
import asmr.fs
import asmr.process
import asmr.logging
import asmr.decorators
#:::: Logging
#::::::::::::
log = asmr.logging.get_logger('asmr::vagrant')
#::::Constants
#:::::::::::::
DEFAULT_VM_NAME = "asmr.dev"
mountpoint_file = asmr.... |
import zipfile
import os
import re
import json
import argparse
from lib import utils
from slugify import slugify
def main(args):
input_dir = args.input
output_dir = args.output
utils.ensure_exists(output_dir)
for name in os.listdir(os.path.join(input_dir, 'meta')):
meta = utils.read_meta(os.p... |
#!/usr/bin/env python
"""
IAM Scan library
Copyright 2020-2021 Leboncoin
Licensed under the Apache License, Version 2.0
Written by <NAME> (<EMAIL>)
"""
# Standard library imports
import logging
# Third party library imports
import boto3
from .asset_type_iam import IAM
# Debug
# from pdb import set_trace as st
LOG... |
#!/usr/bin/env python3
# Name: HackerRankInit.py
# Description: Downloads a challenge description and its testcases
# from hackerrank.com website to a proper location, depending
# on the challenge's category.
# Options: None
# Created on: 20.03.2020
# Last modified: 21... |
from .. import context
from lyrebird import application
from lyrebird.log import get_logger
from lyrebird import utils
from lyrebird.mock.blueprints.apis.bandwidth import config
from urllib.parse import urlparse, unquote
import uuid
import time
import gzip
import json
import urllib
import binascii
import ipaddress
lo... |
import os, sys
import gc
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from utils.kcnet_utils import Netpara, debugPrint... |
import os
import numpy as np
import random
import matplotlib.pyplot as plt
import lmdb
import pickle
import platform
np.random.seed(np.random.randint(1<<30))
num_frames = 20
seq_length = 20
image_size = 64
batch_size = 1
num_digits = 1
step_length = 0.1
digit_size = 28
frame_size = image_size ** 2
def create_reverse_... |
import torch
import torch.nn as nn
import numpy as np
import os
import glob
from opts import parse_opts
from cfg import parse_cfg
from torch.utils.data import Dataset
from torchvision import transforms
from scipy.io import loadmat
from model import YOWO
from utils import *
from eval_results import *
opt = parse_opts()... |
"""HTML comparison functions."""
from functools import partial, update_wrapper
from typing import Callable, List
import re
from abstract_comparisons import lev_similarity
from comparison_types import html_arg_dict, BadResult
from bs4 import BeautifulSoup, element
def html_similarity(html_arg: html_arg_dict) -> Bad... |
"""
Script used to test the adaptive interpolation and
the evaluation of said interpolant
This is now faster than default bessel approximation!
"""
from __future__ import absolute_import
from nose.tools import *
import time
import numpy as np
import numpy.linalg as la
import scipy.special as spec
import ... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... |
# -*- coding: utf-8 -*-
#
import codecs
try:
from abstractRenderer import AbstractRenderer
from books import bookKeyForIdValue
except:
from .abstractRenderer import AbstractRenderer
from .books import bookKeyForIdValue
#
# Renders as set of web pages
#
class DummyFile(object):
def close(self):... |
import copy
import numpy
import six
from .trait import Trait
def definition(traits=()):
"""
Required decorator for custom struct classes.
"""
if isinstance(traits, Trait):
traits = (traits,)
else:
for trait in traits:
assert isinstance(trait, Trait), 'Illegal trait: %s' %... |
# coding:utf-8
import pyaudio
import wave
import json
import signal
import sys
import os
import time
# from src.data.SSLDataPreprocessor import wavToGCCOffsets
from tensorflow import keras
import numpy as np
model_path = "../../models/ssl_model_CB313_10_10_3.h5"
RECORD_RATE = 16000
RECORD_CHANNELS_DEFAULT = 1
RECORD_... |
import numpy as np, re, pickle
from random import shuffle
def init_weight(size1, size2=0, mean = 0, sigma = 0.1):
if size2 == 0:
return np.random.normal(mean, sigma, (size1, 1))
return np.random.normal(mean, sigma, (size1, size2))
def get_n_feature(line1, line2):
nfeat = [0,0,0]
p = re.compil... |
import importlib
import logging
import time
import os
import random
import shutil
import gym
import numpy as np
from scipy.spatial.transform import Rotation
from examples import default_argument_parser
from smarts.core.agent import AgentSpec, Agent
from smarts.core.agent_interface import AgentInterface, AgentType
fro... |
from typing import Dict, List, Tuple
from ...util import *
from ..nucc import *
from ..xfbin import *
from .br_nucc import *
class BrXfbin(BrStruct):
def __br_read__(self, br: BinaryReader):
self.header: BrNuccHeader = br.read_struct(BrNuccHeader)
self.chunkTable: BrChunkTable = br.read_struct(Br... |
import argparse
import builtins
import os
import os.path as osp
import time
import mmcv
import numpy as np
import torch
from got10k.datasets import GOT10k
from got10k.experiments import ExperimentOTB
from mmcv import Config, DictAction
from mmcv.runner import set_random_seed
from siamfc import TrackerSiamFC, default_c... |
# Problem Set 4B
# Name: <NAME>
# Collaborators: None
# Time Spent: 02:30
import string
from copy import deepcopy
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strin... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import PIL.Image as Image
from selenium import webdriver
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.common.exceptions import (WebDriverException,
NoSuchElementExce... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'subtitlesui.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
import os
import sys
from datetime import timedelta
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt... |
import sys
import os
if __name__ == "__main__":
sys.path.append(os.getcwd())
import argparse
import yaml
import albumentations as albu
import numpy as np
import torch
from torchvision import transforms
import random
from src.misc.important_dirs import get_important_dirs
from src.experiment_configs.composite_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.