text stringlengths 3.07k 22.1k |
|---|
import numpy as np
import math
import pickle
def get_data(data, frame_nos, dataset, topic, usernum, fps, milisec, width, height, view_width, view_height):
"""
Read and return the viewport data
"""
VIEW_PATH = '../../Viewport/'
view_info = pickle.load(open(VIEW_PATH + 'ds{}/viewport_ds{}_topic{}_user... |
#All Django Imports
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
#All local imports (libs, contribs, models)
from users.models import *
#All external imports (libs, packages)
import hashlib
i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 08:38:28 2020
pyqt realtime plot tutorial
source: https://www.learnpyqt.com/courses/graphics-plotting/plotting-pyqtgraph/
@author: nlourie
"""
from PyQt5 import QtWidgets, QtCore,uic
from pyqtgraph import PlotWidget, plot,QtGui
import pyqtgra... |
import os
import re
import pickle
import numpy as np
import pandas as pd
from tqdm import tqdm
# Assign labels used in eep conversion
eep_params = dict(
age = 'Age (yrs)',
hydrogen_lum = 'L_H',
lum = 'Log L',
logg = 'Log g',
log_teff = 'Log T',
core_hydrogen_frac = 'X_core', # must be added
... |
import json
import os.path
import operator
import time
from multiprocessing import Pool
import markovify
from tqdm import tqdm
removeWords = ['c', 'tsp', 'qt', 'lb', 'pkg', 'oz', 'med', 'tbsp', 'sm']
removeWords2 = [" recipes "," recipe "," mashed "," fat ",' c. ',' c ','grams','gram','chopped','tbsps','tbsp','cups',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Makina custom grains
=====================
makina.upstart
true if using upstart
makina.lxc
true if inside an lxc container
makina.docker
true if inside a docker container
makina.devhost_num
devhost num if any
'''
import os
import copy
import subprocess... |
import gin
import torch
import logging
from sparse_causal_model_learner_rl.metrics import find_value, find_key
@gin.configurable
def AnnealerThresholdSelector(config, config_object, epoch_info, temp,
adjust_every=100,
multiplier=10, # allow the lo... |
from collections import defaultdict
import itertools
import numpy as np
import pickle
import time
import warnings
from Analysis import binomial_pgf, BranchModel, StaticModel
from simulators.fires.UrbanForest import UrbanForest
from Policies import NCTfires, UBTfires, DWTfires, RHTfires, USTfires
from Utilities import ... |
import os
import sys
import argparse
import onnx
import time
import subprocess
import numpy as np
import tempfile
from onnx import numpy_helper
from collections import OrderedDict
# Command arguments.
parser = argparse.ArgumentParser()
parser.add_argument('model_path', type=str, help="Path to the ONNX model.")
parser... |
#! /usr/bin/python3
import sys
sys.path.append('../../')
import numpy as np
import numpy.fft as npfft
import matplotlib.pyplot as plt
from matplotlib import animation
import time
from netCDF4 import MFDataset
from nephelae_simulation.mesonh_interface import MesoNHVariable
from nephelae_base.types import Position
fr... |
#!/usr/bin/env python3
import numpy as np
import numpy.random as npr
import pytest
A1 = npr.rand( 1, 1)
B1 = npr.rand( 1, 1)
C1 = npr.rand( 1, 1)
A3 = npr.rand( 3, 3)
B3 = npr.rand( 3, 3)
C3 = npr.rand( 3, 3)
A10 = npr.rand( 10, 10)
B10 = npr.rand( 10, 10)
C10... |
from firedrake import *
import numpy as np
from firedrake.petsc import PETSc
from firedrake import COMM_WORLD
try:
import matplotlib.pyplot as plt
plt.rcParams["contour.corner_mask"] = False
plt.close("all")
except:
warning("Matplotlib not imported")
nx, ny = 4, 4
Lx, Ly = 1.0, 1.0
quadrilateral = Fa... |
import random
import numpy as np
import tensorflow as tf
from recognition.utils import train_utils, googlenet_load
try:
from tensorflow.models.rnn import rnn_cell
except ImportError:
rnn_cell = tf.nn.rnn_cell
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
random.seed... |
import numpy as np
from scipy.stats import linregress as li
from math import exp
def calc_factor(field,stepsize=0.01):
"""
Function for calculation of the summed binning.
The returned result is an integral over the binning of the velocities.
It is done for the negative and positive half separately.
... |
import urllib3
import pandas as pd
import numpy as np
import zipfile
import copy
import pickle
import os
from esig import tosig
from tqdm import tqdm
from multiprocessing import Pool
from functools import partial
from os import listdir
from os.path import isfile, join
from sklearn.ensemble import RandomForestClassifier... |
#!/usr/bin/env python
# coding: utf-8
import argparse
import elitech
import datetime
from elitech.msg import (
StopButton,
ToneSet,
AlarmSetting,
TemperatureUnit,
)
from elitech.msg import _bin
import six
import os
def main():
args = parse_args()
if (args.command == 'simple-set'):
com... |
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module
'''
# ===================================
# Advanced nn.Sequential
# reform nn.Sequentials and nn.Modules
# to a single nn.Sequential
# ===================================
'''
def sequen... |
#!/usr/bin/env python3
import sys
import csv
import datetime
import math
from tabulate import tabulate
import scipy.stats as st
from tqdm import tqdm
import numpy as np
np.seterr(all='ignore')
def isfloat(val):
try:
val = float(val)
if math.isnan(val):
return False
return ... |
#!/usr/bin/env python3
from datetime import datetime, timezone, date
import os
import sys
import boto3
import logging
import json
#setup global logger
logger = logging.getLogger("SnapTool")
#set log level
LOGLEVEL = os.environ['LogLevel'].strip()
logger.setLevel(LOGLEVEL.upper())
logging.getLogger("botocore").setLeve... |
# Copyright (C) 2014, 2015 University of Vienna
# All rights reserved.
# BSD license.
# Author: <NAME> <<EMAIL>>
# Heap-based minimum-degree ordering with NO lookahead.
#
# See also min_degree.py which uses lookahead, and simple_md.py which is a
# hacked version of min_degree.py that still uses repeated linear scans... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Name: test_component
# Purpose: Test driver for module component
#
# Author: <NAME> (<EMAIL>)
#
# Copyright: (c) 2014 <NAME>
# ------------------------------------------------------------------------... |
#!/usr/bin/env python3
import os
import time
import binascii
import codecs
def swap_order(d, wsz=16, gsz=2 ):
return "".join(["".join([m[i:i+gsz] for i in range(wsz-gsz,-gsz,-gsz)]) for m in [d[i:i+wsz] for i in range(0,len(d),wsz)]])
expected_genesis_hash = "00000009c4e61bee0e8d6236f847bb1dd23f4c61ca5240b748521... |
# Author: <NAME> <<EMAIL>>
"""Module implementing the FASTA algorithm"""
import numpy as np
from math import sqrt
from scipy import linalg
import time
import logging
def _next_stepsize(deltax, deltaF, t=0):
"""A variation of spectral descent step-size selection: 'adaptive' BB method.
Reference:
-------... |
import base64
from scapy.layers.inet import *
from scapy.layers.dns import *
import dissector
class SIPStartField(StrField):
"""
field class for handling sip start field
@attention: it inherets StrField from Scapy library
"""
holds_packets = 1
name = "SIPStartField"
def getfield(self, pk... |
# -*- coding: utf-8 -*-
# Import Librairies
#
# Python
import requests
#
# User
from data_collect.mushroomObserver.api import api
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Constants
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TAXON_TABLE_NAME = 'names'
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
import numpy as np
import matplotlib.pyplot as plt
from collections import Iterable
mrkr1 = 12
mrkr1_inner = 8
fs = 18
# FUNCTION TO TURN NESTED LIST INTO 1D LIST
def flatten(lis):
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten(item):
... |
from contextlib import contextmanager
import torch
import torch.nn.functional as F
from torch.nn import Module, Parameter
from torch.nn import init
_WN_INIT_STDV = 0.05
_SMALL = 1e-10
_INIT_ENABLED = False
def is_init_enabled():
return _INIT_ENABLED
@contextmanager
def init_mode():
global _INIT_ENABLED
... |
# Copyright 2014 <NAME> <<EMAIL>>
#
# 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 datetime as dt
import re
from abc import ABC, abstractmethod
from decimal import Decimal
from typing import Any, Callable, Generator, Optional
from uuid import UUID
from aiochclient.exceptions import ChClientError
try:
import ciso8601
datetime_parse = date_parse = ciso8601.parse_datetime
... |
from wsgiref.simple_server import make_server
from nlabel.io.carenero.schema import create_session_factory, \
Text, ResultStatus, Result, Tagger, Vector, Vectors
from nlabel.io.carenero.common import ExternalKey
from nlabel.io.common import ArchiveInfo, text_hash_code
from nlabel.io.carenero.common import json_to_... |
import warnings
from dataclasses import dataclass
from typing import List, Optional
import torch
from falkon.utils.stream_utils import sync_current_stream
from falkon.mmv_ops.utils import _get_gpu_info, create_output_mat, _start_wait_processes
from falkon.options import FalkonOptions, BaseOptions
from falkon.utils i... |
import time
import datetime
from waveshare_epd import epd7in5_V2
from PIL import Image, ImageDraw, ImageFont
import calendar
import random
import os
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
fontdir = os.path.join(os.path.dirname(os.path.dirname(os.path.rea... |
import cv2 as cv
import sys
import numpy as np
import tifffile as ti
import argparse
import itertools
max_lowThreshold = 100
window_name = 'Edge Map'
title_trackbar = 'Min Threshold:'
ratio = 3
kernel_size = 3
def CannyThreshold(val):
low_threshold = val
#img_blur = cv.blur(src_gray, (3,3))
... |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... |
# Copyright 2020 The TensorFlow 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
#!/usr/bin/env python
"""
Created by howie.hu.
"""
import re
import aiohttp
import async_timeout
from bs4 import BeautifulSoup
from aiocache.serializers import PickleSerializer,JsonSerializer
from urllib.parse import urlparse, parse_qs, urljoin
from owllook.database.mongodb import MotorBase
from owllook.fetcher.de... |
import datetime
import io
import json
import jsonlines
import logging
import os
import pytz
import shutil
import sys
import tempfile
from flask import Request
from google.cloud import exceptions
from google.cloud import storage
from google.cloud import pubsub_v1
from google.api_core.exceptions import AlreadyExists
from... |
#!/usr/bin/env python3
import collections
import itertools
import json
import logging
import os
import requests
import time
import zign.api
from unittest.mock import MagicMock
ALL_ORGANIZATION_MEMBERS_TEAM = 'All Organization Members'
github_base_url = "https://api.github.com/"
logger = logging.getLogger('app')
s... |
from collections import namedtuple
from itertools import groupby
import itertools
from django.db.models import Q
from casexml.apps.case.const import UNOWNED_EXTENSION_OWNER_ID, CASE_INDEX_EXTENSION
from casexml.apps.case.signals import cases_received
from casexml.apps.case.util import validate_phone_datetime, prune_pr... |
import modeli as modeli
from bottle import *
from datetime import datetime
from collections import defaultdict
import hashlib
glavniMenuAktivniGumb=""
glavniMenuTemplate = '''<li><a {gumbRezervacija} href="/izbiraDestinacije" >Rezervacija leta</a></li>
<li><a {gumbReferencna} href="/referencna">Informacije o r... |
from collections import deque, namedtuple
from random import randint
import pyxel
Point = namedtuple("Point", ["x", "y"])
BACKGRD_COL = 3
WIDTH = 200
HEIGHT = 200
UP = Point(0, -3)
DOWN = Point(0, 3)
RIGHT = Point(3, 0)
LEFT = Point(-3, 0)
START = Point(125, 125)
class Cat:
def __init__(self):
self.cat ... |
import os
import time
import csv
import json
import re
import twint
from cleantext import clean
from textblob import TextBlob
from google.cloud import translate_v2
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"C:\\Users\\ht_ma\\env\\service-account-file.json" # Key needed
translate_client_0 = translate... |
"""The base class for many SciUnit objects."""
import sys
PLATFORM = sys.platform
PYTHON_MAJOR_VERSION = sys.version_info.major
if PYTHON_MAJOR_VERSION < 3: # Python 2
raise Exception('Only Python 3 is supported')
import json, git, pickle, hashlib
import numpy as np
import pandas as pd
from pathlib import Path... |
import dataclasses
import datetime
import json
import os
import tempfile
from core.excel.directions import DirectionsExcel
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.files import File
from django.shortcuts import ... |
# Copyright (c) 2020, Xilinx
# 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 follow... |
"""Test weighted path counting methods."""
# pylint: disable=redefined-outer-name,too-few-public-methods
# pylint: disable=too-many-branches
import pytest
from pytest import approx
import numpy as np
import pandas as pd
from pathcensus.definitions import PathDefinitionsWeighted
from pathcensus import PathCensus
@pyte... |
from .embed import Embed
from .file import Attachment
from .member import GuildMember, User
from .slash import SlashCommandOptionChoice, AnyOption
from .commands import MessageButton, MessageSelectMenu, MessageTextInput, MessageSelectMenuOption
from typing import Optional, List, Union
class BaseInteraction:
def __... |
import argparse
import multiprocessing
import random
import time
import torch.optim as optim
from auto_LiRPA.eps_scheduler import LinearScheduler, AdaptiveScheduler, SmoothedScheduler, FixedScheduler
from auto_LiRPA.perturbations import *
from auto_LiRPA.utils import MultiAverageMeter
from torch.nn import CrossEntropy... |
import subprocess
import secrets
import getpass
import os
import requests
import urllib.parse
import time
from google.colab import files, drive, auth
from google.cloud import storage
import glob
def connect(LOG_DIR = '/log/fit'):
print('It may take a few seconds for processing. Please wait.')
root_password = s... |
""" Provide function to load a wasm module into the current process.
Note that for this to work, we require compiled wasm code and a runtime.
The wasm runtime contains the following:
- Implement function like sqrt, floor, bit rotations etc..
"""
import os
import abc
import shelve
import io
import struct
import logg... |
# Copyright 2020 <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, softw... |
from _satoshitx import *
import struct
#https://bitcoincore.org/en/segwit_wallet_dev/
class SWitnessTransaction(STransaction):
def __init__(version,flag,ins,outs,witness,locktime):
super(SWitnessTransaction,self).__init__(version,ins,outs,locktime)
self.flag=flag
self.witness=witness
def serialize(self):
tx... |
# script for daily update
from bs4 import BeautifulSoup
# from urllib.request import urlopen
import requests
import csv
import time
from datetime import datetime, timedelta
import os
from pathlib import Path
from dashboard.models import Case, Country, District, State, Zone
def run():
scrapeStateStats()
def scrapeC... |
from pytest import raises
from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec
def test_list_path_access():
assert glom(list(range(10)), Path(1)) == 1
def test_path():
_obj = object()
target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}}
assert glom(target, Path('a', 'b.b... |
from pygame import *
from random import randint
import json
#fonts and captions
font.init()
font1 = font.SysFont('Comic Sans', 60)
win = font1.render('Dam you actually poggers', True, (255, 255, 255))
lose = font1.render('Yeah you suck, you lost', True, (180, 0, 0))
font2 = font.SysFont('Comic Sans', 36)
ammo_lose ... |
# -*- coding: utf-8 -*-
import json
import math
import random
import argparse
import networkx as nx
class Node:
def __init__ (self, nodeNumber, nodeType):
self.nodeNumber = nodeNumber
self.nodeType = nodeType
def add_vm (self, vm):
if not hasattr(self,'vms'):
self.vms = []
self.vms.append(vm)
class VM:... |
from PyQt5.QtCore import QTimer, QTime
from PyQt5 import QtGui, QtWidgets
import time
import random
import os
import datetime
import requests
import sqlite3 as sql
import database_impl as db
from date_tools import dt
def datetime_diff(old_datetime, new_datetime, dates_are_strings=True):
"""
String dates shoul... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 26 20:17:06 2014
@author: stuart
"""
import os
import tempfile
import datetime
import astropy.table
import astropy.time
import astropy.units as u
import pytest
from sunpy.time import parse_time
from sunpy.net.jsoc import JSOCClient, JSOCResponse
from sunpy.net.vso.vso im... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 14:15:38 2019
@author: Satish
"""
# doing the ortho-correction on the processed data from matchedFilter
import os
import numpy as np
import spectral as spy
import spectral.io.envi as envi
import spectral.algorithms as algo
from spectral.algorith... |
# k3d.py
#
# Copyright 2020 <NAME>
#
# 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 distributed in ... |
import itertools
import Partitioning
class Algorithm( object ):
def __init__( self, linv, variant, init, repart, contwith, before, after, updates ):
self.linv = linv
self.variant = variant
if init:
#assert( len(init) == 1 )
self.init = init[0]
else:
... |
# Copyright (c) 2021, MITRE Engenuity. Approved for public release.
# See LICENSE for complete terms.
import argparse
import json
import pathlib
import numpy
import requests
from src.create_mappings import get_sheets, get_sheet_by_name
def get_argparse():
desc = "ATT&CK to VERIS Mappings Validator"
argpars... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB 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... |
from utils import *
import torch
import sys
import numpy as np
import time
import torchvision
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as datasets
def validate_pgd(val_loader, model, criterion, K, step, configs, logger, save_image=False, HE=False):
... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from conditional import db
from conditional.models import models, old_models as zoo
import flask_migrate
# pylint: skip-file
old_engine = None
zoo_session = None
# Takes in param of SqlAlchemy Database Connection String
def... |
import torch
import numpy as np
import time
import datetime
import random
from Kfold import KFold
from split_data import DataManager
from transformers import BertTokenizer
from transformers import BertTokenizer
from torch.utils.data import TensorDataset, random_split
from torch.utils.data import DataLoader, RandomSamp... |
#!/usr/bin/env python
# pylint: disable=invalid-name
""" Web-based proxy to a Kerberos KDC for Webathena. """
import base64
import json
import os
import select
import socket
import dns.resolver
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1.error im... |
# encoding: 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/.
#
# Author: <NAME> (<EMAIL>)
#
from __future__ import absolute_import, division, unicode_literals
fr... |
import time
from os import system
from django.http import HttpResponse
from django.template import Context, loader
from django.views.decorators.csrf import csrf_exempt # Pour des formulaires POST libres
from jla_utils.utils import Fichier
from .models import ElementDialogue
class Tunnel:
def __init__(self, long... |
""" This Script contain the different function used in the framework
part1. Data processing
part2. Prediction and analisys
part3. Plotting
"""
import numpy as np
import librosa
import matplotlib.pyplot as plt
from sklearn import metrics
import os
import pickle
import time
import struct
""" Data processing """
def g... |
import os
import tarfile
import time
import pickle
import numpy as np
from Bio.Seq import Seq
from scipy.special import expit
from scipy.special import logit
import torch
import torch.nn.functional as F
""" Get directories for model and seengenes """
module_dir = os.path.dirname(os.path.realpath(__file__))
model_dir ... |
#!/usr/bin/env python3
# system imports
import argparse
import sys
# obspy imports
from obspy.clients.fdsn import Client
from obspy import read, read_inventory, UTCDateTime
from scipy import signal
from obspy.signal.cross_correlation import correlate, xcorr_max
from obspy.clients.fdsn.header import FDSNNoDataExceptio... |
"""Main entrypoint for the repobee CLI application.
.. module:: main
:synopsis: Main entrypoint for the repobee CLI application.
.. moduleauthor:: <NAME>
"""
import argparse
import contextlib
import io
import logging
import os
import pathlib
import sys
from typing import List, Optional, Union, Mapping
from types... |
from __future__ import print_function
from django.shortcuts import render
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth import get_user_model
import os
from django.core.mail import send_mail
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.st... |
from django.utils import timezone
from django.utils.translation import ugettext
from mediane.algorithms.enumeration import get_name_from
from mediane.algorithms.lri.BioConsert import BioConsert
from mediane.algorithms.lri.ExactAlgorithm import ExactAlgorithm
from mediane.algorithms.misc.borda_count import BordaCount
f... |
import tensorflow as tf
from typing import List
from ..utils.tf_utils import gen_CNN
from ...utils import MODEL
from ..utils.pointnet import pointnet2_utils
class Pointnet2MSG(tf.keras.layers.Layer):
def __init__(
self,
in_channels=6,
use_xyz=True,
SA_config={
... |
from avatar2 import *
import sys
import os
import logging
import serial
import time
import argparse
import pyudev
import struct
import ctypes
from random import randint
# For profiling
import pstats
logging.basicConfig(filename='/tmp/inception-tests.log', level=logging.INFO)
# ************************************... |
from hlt.positionals import Position, Direction
from hlt import constants
import random
import logging
# Import my stuff
import helpers
def navigate_old(ship, destination, game_map):
curr_pos = ship.position
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
if ship.halite_amount >=... |
import os
import sys
import torch
from torch import nn
from torch.nn import functional as F, init
from src.utils import bernoulli_log_pdf
from src.objectives.elbo import \
log_bernoulli_marginal_estimate_sets
class Statistician(nn.Module):
def __init__(self, c_dim, z_dim, hidden_dim_statistic=3, hidden_dim=40... |
from time import time
import rclpy
from rclpy.node import Node
import json
from std_msgs.msg import String, Float32, Int8, Int16
import sailbot.autonomous.p2p as p2p
from collections import deque
class ControlSystem(Node): # Gathers data from some nodes and distributes it to others
def __init__(self):
s... |
import os
import tempfile
import shutil
import argparse
import networkx as nx
from tqdm import tqdm
from joblib import Parallel, delayed
from collections import defaultdict, Counter
import math
import numpy as np
from .isvalid import *
from .__init__ import __version__
from .cdhit import run_cdhit
from .clean_network... |
#!/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import numpy.linalg as nl
import scipy.linalg as sl
import scipy.stats as ss
import time
aca = np.ascontiguousarray
def nul(n):
return np.zeros((n, n))
def iuc(x, y):
"""
Checks if pair of generalized EVs x,y is inside the unit circle. Here for ... |
import collections
import logging
from event_model import DocumentRouter, RunRouter
import numpy
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
import matplotlib
from qtpy.QtWidgets import ( # noqa
QLabel,
QWidget,
QVB... |
# Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from numpy.testing import assert_almost_equal
from mmpose.models import build_loss
from mmpose.models.utils.geometry import batch_rodrigues
def test_mesh_loss():
"""test mesh loss."""
loss_cfg = dict(
type='MeshLoss',
... |
#!/usr/bin/env python
##############################################################
# preparation of srtm data for use in gamma
# module of software pyroSAR
# <NAME> 2014-18
##############################################################
"""
The following tasks are performed by executing this script:
-reading of a par... |
# Programmer friendly subprocess wrapper.
#
# Author: <NAME> <<EMAIL>>
# Last Change: March 2, 2020
# URL: https://executor.readthedocs.io
"""
Portable process control functionality for the `executor` package.
The :mod:`executor.process` module defines the :class:`ControllableProcess`
abstract base class which enable... |
from logging import basicConfig, getLogger, INFO
from connect_to_ledger import create_qldb_driver
from amazon.ion.simpleion import dumps, loads
logger = getLogger(__name__)
basicConfig(level=INFO)
from constants import Constants
from register_person import get_scentityid_from_personid,get_scentity_contact
from sampled... |
# utils/test_kronecker.py
"""Tests for rom_operator_inference.utils._kronecker."""
import pytest
import numpy as np
import rom_operator_inference as opinf
# Index generation for fast self-product kronecker evaluation =================
def test_kron2c_indices(n_tests=100):
"""Test utils._kronecker.kron2c_indices... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 12:48:08 2020
@author: smith
"""
import spacy
from gensim.test.utils import common_texts, get_tmpfile
from gensim.models import Word2Vec
from gensim.models.phrases import Phrases, Phraser
import os
import multiprocessing
import csv
import re
impo... |
""" Adapt Server
This module contains all the functionality necessary to
setup an Adapt Server node (not really).
Example
-------
python3 adapt_server.py -v ingest -s testfile.txt
"""
import filesystem
from filesystem import FSOperationError
import sys
import os
import argparse
import logging
from general import... |
import torch
import torch.nn as nn
import os
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from .modules import WavePool, WaveUnpool, ImagePool, NLayerDiscriminator
from utils.metrics import compute_dice_metric
from utils.losses import DiceLoss
import numpy as np
class WaveEncoder(nn.Mod... |
import cv2
import numpy as np
import imutils
from collections import defaultdict
# mouse callback function
def define_points(target_img):
corners = []
refPt = []
def draw_circle(event,x,y,flags,param):
global refPt
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(param,(x,y),5,(... |
import argparse
import configparser
import os
import pathlib
import platform
import random
import subprocess as sp
import sys
import typing
import warnings
if platform.system() == 'Windows':
import winsound
try:
from IPython.core import magic
IPYTHON_INSTALLED = True
except ImportError:
IPYTHON_INSTAL... |
"""Defines various classes and definitions that provide assistance for
unit testing Actors in an ActorSystem."""
import unittest
import pytest
import logging
import time
from thespian.actors import ActorSystem
def simpleActorTestLogging():
"""This function returns a logging dictionary that can be passed as
... |
import logging as log
import numpy as np
import h5py
import humblerl as hrl
from humblerl import Callback, Interpreter
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Normal
from torch.utils.data import Dataset
from common_utils import get_model_path_if_exists
from third... |
import os
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib import rcParams
params = {
# 'text.latex.preamble': ['\\usepackage{gensymb}'],
# 'text.usetex': True,
'font.family': 'Helvetica',
'lines.solid_capstyle'... |
from aiplayer import *
from player import *
from gameclasses import *
def setup(countries, countryMap):
print("Setup started!")
#Initialise boni
NA.countries = countries[0:9]
SA.countries = countries[9:13]
AF.countries = countries[13:19]
EU.countries = countries[19:26]
AU.countries = countr... |
import os
import numpy as np
import urllib
from absl import flags
import tensorflow as tf
import tensorflow_probability as tfp
tfb = tfp.bijectors
tfd = tfp.distributions
flags.DEFINE_float(
"learning_rate", default=0.001, help="Initial learning rate.")
flags.DEFINE_integer(
"epochs", default=100, help="Numb... |
from math import sqrt
from math import atan2
from math import asin
beta = 0.1
sampleFreq = 10.0
#Fastest implementation in python for invsqrt
def invsqrt(number):
return number ** -0.5
def update_IMU( gx, gy, gz, ax, ay, az, q0, q1, q2, q3):
gx = gx * 0.0174533
gy = gy * 0.0174533
gz = gz * 0.017453... |
from collections import defaultdict
import io
import hashlib
from datetime import date, datetime
from pyexcel_xls import get_data as xls_get
import pandas
import magic
from contextlib import closing
import csv
from django.db import connection
from io import StringIO
import uuid
from psycopg2.errors import UniqueViolati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.