text stringlengths 3.07k 12.6k |
|---|
import torch
from torch import nn
from torch import optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from .datasets import RuleReasoningDataset, CWA, RuleReasoningDatasetOnlyCWA, RuleReasoningDatasetOnlyNotCWA
from .module.backward_chaining_inference import BackwardChainingInference
from .module.uti... |
"""
Usage:
rebiased_finetuning_lm.py [--train_path=TRAIN_PATH] [--encoder=ENCODER] [--debias=DEBIAS] [--rebias=REBIAS]
[--n_epochs=N_EPOCHS] [--out_dir=OUT_DIR] [--device=DEVICE] [--wandb]
Options:
-h --help show this help message and exit
--train_path=TRAIN_PATH input directory
--e... |
import configparser
import inspect
import os
import autopycli.arguments as cliargs
from autopycli import ArgumentsError
from autopycli import Configuration
from autopycli import Environment
ARG_PARSER = cliargs.ArgumentParser
class ArgparserNamespace:
pass
class RuntimeConfig:
"""Carry the application's c... |
from functools import lru_cache
import docker
import requests
from kubetools.dev.process_util import run_process
from kubetools.exceptions import KubeDevError
from kubetools.log import logger
from .config import (
create_compose_config,
dockerise_label,
get_all_containers,
get_compose_filename,
g... |
import sys
import traceback
from functools import lru_cache
from importlib import import_module
from django.apps import apps
from django.apps.config import MODELS_MODULE_NAME
from django.conf import settings
from django.core.exceptions import AppRegistryNotReady
from django.utils.module_loading import import_string
f... |
"""
mpiece.renderer
~~~~~~~~~~~~~~~~~~~~~~~~~
Renderer Classes.
:license: BSD, see LICENSE for details.
:author: <NAME> <<EMAIL>>
"""
class Renderer(object):
"""
Base renderer class.
All renderer classes should be subclasses of this class.
This class and their subclass are used in the ``mpiece.markdown... |
# <NAME>
# June 2020
# Langevin equation 3D bulk for a free particule with inertia.
import numpy as np
import matplotlib.pyplot as plt
from OverdampedLangevin3D import Langevin3D
class InertialLangevin3D(Langevin3D):
def __init__(self, dt, Nt, R, rho, eta=0.001, T=300, x0=(0, 0, 0)):
"""
:param... |
# Copyright 2020 Dakewe Biotech Corporation. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
from ..spec import *
from ..utilities import get_data_path
DATAPATH = get_data_path()
def test_find_bin_edges():
assert np.allclose(find_bin_edges([1, 2.1, 3.3, 4.6]),
[0.45, 1.55, 2.7, 3.95, 5.25])
def test_make_wa_scale():
wa = make_wa_scale(40, 1, 5)
assert np.allclose(wa, ... |
#!/usr/bin/python3
"""
Move file(s) to new location while leaving a symbolic link at the old location to the new location.
Reads in a file with two or three tab-delimited columns.
In two-column mode:
* First column is current location of file and future location of link to new file
* Second column is new location of ... |
from audioop import add
import hashlib
import binascii
import rsa
from datetime import datetime
from os.path import exists
from sys import argv
# gets the hash of a file; from https://stackoverflow.com/a/44873382
def hashFile(filename):
h = hashlib.sha256()
with open(filename, 'rb', buffering=0) as f:
... |
import common
import numpy as np
import util
def fit_phis(adj, superclusters, supervars, method, iterations, parallel):
if method == 'debug':
# Bypass cache when debugging.
return _fit_phis(adj, superclusters, supervars, method, iterations, parallel)
key = (hash(adj.tobytes()), iterations)
if key not in ... |
import random
# playables
class wizard (object):
hp = 100
stregth = 12
defence = 12
magic = 30
class warrior (object):
hp = 100
stregth = 30
defence = 18
magic = 10
class elf (object):
hp = 100
stregth = 20
defence = 18
magic = 18
# enemies
class goblin (object):
name = "Goblin"
hp = 6... |
"""
This code was originally extracted from pysmb and was adapted for asyncio.
Copyright (C) 2001-2015 <NAME> <miketeo (a) miketeo.net>
Copyright (C) 2015- Delve Labs inc. <<EMAIL>>
This software is provided 'as-is', without any express or implied warranty.
In no event will the author be held liable for any dama... |
import argparse
import sys
from appdirs import user_cache_dir, user_config_dir
from colorama import Fore, init as colorama_init
from os import path
from .cache import Cache
from .generator import Generator
from .config import Config
CONFIG_PATH_FLAG = '--config-path'
CACHE_PATH_FLAG = '--cache-path'
PROFILE_FLAG = '--... |
import nltk
import pickle
import argparse
from collections import Counter
import sys
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import os, sys
import pickle
import numpy as np
import nltk
import argparse
import torch
import numpy as np
import torch.nn as nn
from nltk.transl... |
import numpy as np
from data.bbox import crop_to_bbox
from typing import List
import cv2
import matplotlib.pyplot as plt
def k_means_image(image: np.ndarray, mask_bbox, mask_value=1, clusters=3):
[x, y, w, h] = mask_convention_setter(mask_bbox, invert=True)
mask_image = image[y:y + h, x:x + w].copy()
mask... |
"""
Fashion MNIST Classification using CNN (Pytorch)
Author: <NAME>, <EMAIL>
"""
# Import Files
import numpy as np
import torch
import matplotlib.pyplot as plt
from torchvision import datasets, transforms
from torch import nn
from torch import optim
import torch.nn.functional as F
from collections import OrderedDict
... |
import os
import numpy as np
from sklearn import datasets
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import seaborn as sb
import matplotlib.pyplot as plt
from model import GCN
def get_knn_graph(data, k):
n_sampl... |
#!/usr/bin/env python
# encoding: utf-8
import pyqms
import unittest
M = pyqms.UnimodMapper()
UNIMODMAPPER_FUNCTIONS = [
M.name2mass,
M.name2composition,
M.name2id,
M.id2mass,
M.id2composition,
M.id2name,
M.mass2name_list,
M.mass2id_list,
M.mass2composition_list,
M.appMass2id_... |
import webbrowser
import argparse
import time
import sys
import os
SORT_OPTS = [
"name",
"set",
"tix",
"usd",
"eur",
"cmc",
"pow",
"tou",
"rarity",
"color",
"edhrec"
]
CATALOG_OPTS = [
"card-names",
"word-bank",
"creature-types",
"planeswalker-types",
"l... |
"""
OMEN API endpoint definition.
## noteworthy URLs:
- The OpenAPI descriptor is exposed as `/omen/api/1.0/openapi.json`.
- The API itself lives under `/omen/api/1.0/`.
- A visual instance of Swagger UI is available under `/omen/api/1.0/ui`.
"""
# pylint: disable=no-self-use,too-many-instance-attributes
import logg... |
#!/usr/bin/env python
# Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import io
import logging
import re
import zipfile
import babelfish
import bs4
import charade
import requests
from . import Provider
from .. import __version__
from ..cache import region
from ..exceptions import InvalidSubtitle, ProviderNotAvailable, Provid... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# MIT License
# 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,... |
"""Module defining elastic document builder."""
from __future__ import annotations
from itertools import chain
import numpy as np
from maggma.builders import Builder
from maggma.core import Store
from pydash import get
from pymatgen.analysis.elasticity import Deformation, Stress
from atomate2 import SETTINGS
from a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Photo Sort GUI
Usage:
photo_sort_gui.py <input> ...
"""
import os
from tkinter import *
import tkinter as tk
import tkinter.filedialog
from tkinter.messagebox import askyesno
from docopt import docopt
import photo_sort
from enums import Mode, Encode
__author__ =... |
"""
Module containing classes used to systematically generate clean Lumerical script code
"""
import datetime
from typing import List, Dict, Any, Union
class LumericalCodeGenerator:
""" This is the base class that encapsulates the generation of lumerical .lsf code """
def __init__(self, config=None):
... |
import os
from itertools import product
import numpy as np
import pandas as pd
import socket
from .composition_encoding import get_comp_list
from .base import get_energybins, check_output_dir
from .data_functions import ratio_error
def unfolded_counts_dist(unfolding_df, iteration=-1, num_groups=4):
"""
Conv... |
# Copyright 2020 getcarrier.io
#
# 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... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... |
from socket import *
import threading, time, json
from .data import add_data_keys
# Define valid data types to document API and so calling application can be aware if needed
VALID_DATA_TYPES = ('evt_precip', 'evt_strike', 'rapid_wind', 'obs_air', 'obs_sky', 'obs_st', 'device_status',
'hub_status')
... |
#!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
# -*- coding: utf-8 -*-
"""
conftest
--------
Contains pytest fixtures which are globally available throughout the suite.
"""
import logging
import os
import shutil
import pytest
from cookiecutter import utils
USER_CONFIG = u"""
cookiecutters_dir: "{cookiecutters_dir}"
replay_dir: "{replay_dir}"
"""
def backup... |
#!/usr/bin/env python
# <NAME> (Tunstill) Copyright (c) 2020
# Email: <EMAIL>
from __future__ import absolute_import, division, print_function
import yaml
import pathlib
from topic_store import get_package_root
__all__ = ["load_yaml_file", "ScenarioFileParser", "resolve_scenario_yaml"]
def load_yaml_file(file... |
#!/usr/bin/env python
import glob
import logging
import subprocess
import multiprocessing
from flask.ext.script import Server
from flask.ext.script import Manager
from sqlalchemy import text as sqla_text
from webservices.env import env
from webservices.rest import app, db
from webservices.config import SQL_CONFIG, c... |
################################################################################
#
# Speedtest Python Plugin
#
# Author: Xorfor
#
################################################################################
"""
<plugin key="xfr_speedtest" name="Speedtest" author="Xorfor" version="1.3.0" wikilink="https://github.com... |
# -*- coding: utf-8 -*-
"""
Functionality to update one PyScaffold version to another
"""
import os
from functools import reduce
from os.path import exists as path_exists
from os.path import join as join_path
from pkg_resources import parse_version
from . import __version__ as pyscaffold_version
from .contrib.configu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import anndata
import numpy as np
import pandas as pd
import scipy
import wot.tmap
def trajectory_similarity_score(p1, p2):
return 1.0 - 0.5 * np.sum(np.abs(p1 - p2))
def trajectory_similarities(trajectory_ds):
"""
Computes the similarity for all pairs of ... |
"""Common helpers for greeneye_monitor tests."""
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, MagicMock
from homeassistant.components.greeneye_monitor import (
CONF_CHANNELS,
CONF_COUNTED_QUANTITY,
CONF_COUNTED_QUANTITY_PER_PULSE,
CONF_MONITORS,
CO... |
import unittest
from unittest.mock import patch
from mongoengine import connect, disconnect
from google.protobuf.json_format import MessageToDict
from google.protobuf.empty_pb2 import Empty
from spaceone.core.unittest.result import print_message
from spaceone.core.unittest.runner import RichTestRunner
from spaceone.co... |
# Copyright (c) 2018 PaddlePaddle 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 app... |
#!/usr/bin/env python
##
# Builds the data files in the expected format from IV33.dat.txt
#
# from >> easting(Km) northing(Km) depth(Km) vp(km/s)
#
# to >> /** P-wave velocity in km/s per second */
# double vp;
# depth is in increment of 1000m,
#
#The columns of the file are: x (km) y (km) z (km) vp (km/s), w... |
import numpy as np
from scipy import stats
import lib_detect as lib
def calculate_fdr_threshold_vector(chrom, cfg, **kwargs):
'''
Compute vector of FDR-controlling detection thresholds by region.
Parameters
----------
- chrom : int
Index of chromosome to analyze
- cfg ... |
"""
Copyright 2017-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... |
from concurrent.futures import ThreadPoolExecutor
from typing import NamedTuple, Callable, Union, List, Dict
import numpy as np
from keras import optimizers
from kerl.common.agent import MultiAgent, EpisodeSample
from kerl.common.multi_gym_env import MultiGymEnv
from kerl.wm.networks import WorldModelVAE, WorldEnvMod... |
# coding: utf-8
"""
Tests for IPython.config.application.Application
Authors:
* <NAME>
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file C... |
from dagster_pandas.data_frame import create_dagster_pandas_dataframe_type
from dagster_pandas.validation import PandasColumn
from numpy import mean, median, ndarray
from pandas import Timestamp
from dagster import DagsterType, EventMetadataEntry, TypeCheck
def compute_trip_dataframe_event_metadata(dataframe):
r... |
"""
:Authors: - <NAME>
"""
import ply.lex as lex
import ply.yacc as yacc
from .symbol import Terminal, Nonterminal
from .cfg import CFG
from grasp.recipes import smart_ropen
from grasp.cfg.rule import NewCFGProduction as CFGProduction
_EXAMPLE_GRAMMAR_ = """
[S] ||| '<s>' [X] '<s>' ||| 1.0
[X] ||| [X] [X] ||| 0.5
[... |
from collections import defaultdict
import ipywidgets as ipw
from jinja2 import Template
from progressivis.core import JSONEncoderNp
import progressivis.core.aio as aio
from .control_panel import ControlPanel
from .sensitive_html import SensitiveHTML
from .utils import wait_for_change, wait_for_click, update_widget
fro... |
"""
Copyright (C) 2013-2019 Calliope contributors listed in AUTHORS.
Licensed under the Apache 2.0 License (see LICENSE file).
"""
import logging
import numpy as np
import pandas as pd
import xarray as xr
from calliope.core.util.tools import memoize
from calliope import exceptions
logger = logging.getLogger(__name... |
#!/usr/bin/env python
#based off this gist https://gist.github.com/benallard/8042835
#modified it a little so it worked for my needs. (mainly encoding issues and bigger file chunks)
import os
import xml.parsers.expat
from xml.sax.saxutils import escape
from optparse import OptionParser
from math import log10
# How ... |
# Copyright (C) 2019-2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
from collections import OrderedDict
import logging as log
import os
import os.path as osp
from datumaro.components.annotation import AnnotationType
from datumaro.components.converter import Converter
from datumaro.components.dataset import I... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
"""
File: GdbParallelDataRemover.py
This is an enhencement of `GdbDataRemover` by parallelization to speedup data remover, but
here may be some fails about lock timeout due to update relation data in concurrent, it's OK
to run it or `GdbDataRemover` again
Authors:
<NAME>
2019/8/22 - initial release
""... |
# @version: 1.0 date: 05/06/2015 by <NAME>
# @author: <EMAIL>, <EMAIL>, <EMAIL>
# @copyright: EPFL-IC-LCAV 2015
'''Collection of spectral estimation methods.
**This module is deprecated.** It is replaced by the methods of :py:obj:`pyroomacoustics.realtime`
'''
from __future__ import division
import sys, warnings
im... |
import sys
import threading as th
from _tkinter import TclError
from io import StringIO
from tkinter import Tk, Canvas, Button, Entry, Label
from tkinter import END, WORD, INSERT, NW
from tkinter.scrolledtext import ScrolledText
import modi
from modi.modi import MODI
from modi.util.msgutil import parse_message
import ... |
import unittest
from HARK.datasets import load_SCF_wealth_weights
from HARK.datasets.cpi.us.CPITools import cpi_deflator
from HARK.datasets.SCF.WealthIncomeDist.SCFDistTools import income_wealth_dists_from_scf
class test_load_SCF_wealth_weights(unittest.TestCase):
def setUp(self):
self.SCF_wealth, self.SC... |
import torch
from torch import nn
import math
import torch.utils.model_zoo as model_zoo
from torch.utils.checkpoint import checkpoint
import torchvision.transforms
from PIL import Image
class MyNet(nn.Module):
def __init__(self, cfg):
super(MyNet, self).__init__()
block = Bottleneck
layer... |
#!/usr/bin/env python
import json
import math
import psycopg2
import requests
import pandas as pd
from tqdm import tqdm
from point import Point
conn = psycopg2.connect(dbname="gis", host="/var/run/postgresql/")
cur = conn.cursor()
def getNodes(size='large', dec_limit=15):
if size=='large':
cur.execute(""... |
'''
PLTW Lesson 1.2.5
@authors: <NAME>
'''
#####-Imports-#####
#Import Turtle library for drawing and display functions
import turtle as trtl
#####-Setup-#####
#Create a turtle object to draw the board
board_drawer = trtl.Turtle()
#Create a turtle object to draw the labels on the board
label_drawer = trtl.Turtle()
... |
import requests
from bs4 import BeautifulSoup
import threading
import json
import time
import os
import re
def BetterTime(timestr):
"将各种格式的时间字符串规范化"
if '今天' in timestr or '前' in timestr:
localtime = time.localtime()
year = str(localtime.tm_year)
month = str(localtime.tm_mon)
da... |
"""Representation of ISYEntity Types."""
from pyisy.constants import (
COMMAND_FRIENDLY_NAME,
EMPTY_TIME,
EVENT_PROPS_IGNORED,
ISY_VALUE_UNKNOWN,
PROTO_GROUP,
PROTO_ZWAVE,
)
from pyisy.helpers import NodeProperty
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN
from homeassis... |
import hdfs
from airflow import configuration
from airflow import settings
from airflow.hooks.base_hook import BaseHook
from airflow.plugins_manager import AirflowPlugin
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
from airflow.utils.log.logging... |
#!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
MAX_PERCENT = 100
PERCENT_DENOMINATION = 10
class Category:
width_of_ledger = 30
def __init__(self, title : str) -> None: #to define your own attributes for this category
self.title = title #eg of a constructor Category("Food")
self.currentAmount : float = 0
self.ledger : list = []
... |
# 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 applica... |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... |
# -*- coding: utf-8 -*-
#MIT License
#Copyright (c) 2017 <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, mod... |
# Copyright 2017 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 applicab... |
r"""
Orientations
This module implements several methods to compute orientations of undirected
graphs subject to specific constraints (e.g., acyclic, strongly connected,
etc.). It also implements some iterators over all these orientations.
**This module contains the following methods**
.. csv-table::
:class: con... |
# coding=utf-8
# Copyright 2020 The Trax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import collections
import datetime
import json
from io import BytesIO
import lat_lon_parser
import pandas as pd
import requests
from shapely import geometry
import utm
def google_sheets_to_df(key):
r = requests.get(f"https://docs.google.com/spreadsheet/ccc?key={key}&output=csv")
return pd.read_csv(BytesIO(r.... |
"""
Napari-time_series_plotter test module.
"""
from napari_time_series_plotter._dock_widget import *
import pytest
import numpy as np
# fixture for LayerSelector class tests
@pytest.fixture
def selector(make_napari_viewer):
_sync = None
viewer = make_napari_viewer(show=False)
viewer.add_image(np.random.r... |
import argparse
import time
import os
import random
import collections
import numpy as np
import torch
from model import DAE, VAE, AAE
from vocab import Vocab
from meter import AverageMeter
from utils import set_seed, logging, load_sent
from batchify import get_batches
parser = argparse.ArgumentParser()
# Path argume... |
#!/usr/bin/python
#
# Copyright 2018 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 ag... |
import linalgeuc.math.linear_algebra as lalib
from linalgeuc.graphics.mesh import Mesh, Regular, Circular
import math
# CONSTANTS
GOLDEN_RATIO = (1 + (5 ** 0.5)) / 2
# 0D
class Point(Mesh):
pass
# 1D
class Line(Mesh):
def __init__(self, start=[-1, 0, 0], end=[1, 0, 0], **kwargs):
start, end = la... |
import numpy as np
#from apmeter import APMeter
from sklearn.metrics import average_precision_score
from sklearn.metrics import roc_auc_score
def get_intervals(seq, thres=0.0001, mean=False):
'''
Get the positive interval of a prediction score sequence with the given threshold
Input:
seq -... |
# -*- coding: utf-8 -*-
"""
Minimal pyQT testbed
Created on Tue Mar 8 15:27:24 2022
@author: wardc
"""
#%% import libraries
#some of these might not be neccessary
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtCore
from PyQt5.QtCore import *
from PyQt5 import uic
import sys
import que... |
import sys
sys.path.append('../')
from tqdm import tqdm
from ref_free_metrics.pseudo_ref_builder import *
from .utils import parse_refs, parse_docs, get_sim_metric
from summariser.utils.misc import normaliseList
# build pseudo references; the selected sentences will have non-zero weights
def get_weights(sent_info_di... |
import numpy as np
import os
from pyarrow.parquet import ParquetDataset
import torch
from PIL import Image, ImageOps
import cv2
from data.base_dataset import BaseDataset
cv2.setNumThreads(0)
INTRINSICS = 1033.0 / 2, 0.0, 960.0 / 2, 0.0, 1033.0 / 2, 600.0 / 2, 0.0, 0.0, 1.0
DISTORTION_COEFS = -0.3286423683166504, 0.... |
import dataclasses
import inspect
from datetime import datetime
from typing import Optional
import marshmallow
import pytest
from marshmallow import ValidationError
from datafunctions import datafunction, ArgumentError, ReturnError
from .utils import raises_with_cause
@dataclasses.dataclass
class Point:
x: int
... |
#!/usr/bin/env python
from __future__ import print_function
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
__copyright__ = "Italian Mars Society"
"""
Robot diagnostics feedback aggregator Tango Device server
The server subscribes to the ROS topics which publishes all robot diagnostic
informat... |
from collections import namedtuple
from typing import Any, Text, Iterable, List, Dict
from onnx import AttributeProto, numpy_helper
import numpy as np
__author__ = "<NAME>, <NAME> (University of Tuebingen, Chair for Embedded Systems)"
def _convertAttributeProto(onnx_arg):
"""
Convert an ONNX AttributeProto i... |
import numpy as np
def linear(t):
return t
def in_quad(t):
return t * t
def out_quad(t):
return -t * (t - 2)
def in_out_quad(t):
u = 2 * t - 1
a = 2 * t * t
b = -0.5 * (u * (u - 2) - 1)
return np.where(t < 0.5, a, b)
def in_cubic(t):
return t * t * t
def out_cubic(t):
u = t - 1... |
#! /usr/bin/python
# Copyright 2015 <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... |
# Copyright (C) 2015-2019 <NAME>
# SPDX-License-Identifier: Apache-2.0
import traceback
import dolfin
from . import ocellaris_error, timeit
def make_expression(simulation, cpp_code, description, element, params=None):
"""
Create a C++ expression with parameters like time and all scalars in
simulation.dat... |
from visual import *
from random import random
# Bruce Sherwood; revised by <NAME>
# Converted core calculations to numpy, Sept. 2010, Bruce Sherwood
N = 4
Ntotal = N*N*N
scolor = (1,0.5,0)
bcolor = (0,0.58,0.69)
springs = []
atoms = []
m = 1.
k = 1.
L = 1.
R = 0.3*L
Rs = 0.9*R # end of spring is Rs from center of at... |
"""Contains utilities related to theme management, discovery and creation including:
- Section template discovery and creation
- Remote repo management
- Theme discovery & updating
"""
# Standard Library Dependencies
import os # Used for path validation and manipulation
import shutil ... |
# -*- coding: utf-8 -*-
'''
watdo.cli
~~~~~~~~~
This module contains both helper functions and main() for the CLI
interface.
:copyright: (c) 2013 <NAME>
:license: MIT, see LICENSE for more details.
'''
import functools
import os
import subprocess
import sys
import tempfile
import click
from... |
import cv2
import os
import PIL
from PIL import Image
import torch
import numpy as np
import json
import skimage
from torchvision import transforms,utils
from torch.utils.data import DataLoader,Dataset
from skimage.draw import polygon
import torchvision
import random
class JsonDataset(Dataset):
""" Torch Dataset C... |
from .wast import (
WArg,
WArray,
WAssert,
WAssign,
WAst,
WBinary,
WBlock,
WBoolOp,
WBreak,
WCall,
WClass,
WCompare,
WConstant,
WContinue,
WDel,
WExprStatement,
WFor,
WFuncDef,
WGetAttr,
WGetItem,
WIf,
WIfExpr,
WName,
WPass,... |
from pettingzoo import AECEnv
from pettingzoo.utils import agent_selector
from pettingzoo.utils import wrappers
from .backgammon import Backgammon as Game, WHITE, BLACK, COLORS
from gym import spaces
from . import bg_utils
import numpy as np
def env(**kwargs):
env = raw_env(**kwargs)
env = wrappers.TerminateI... |
import os
import csv
import logging
from tableschema import Schema, Field
from googleapiclient.discovery import Resource
from typing import Dict, List
from etl.helpers.field_mapping import common
from etl.helpers.field_mapping.common import FieldMapping, FieldMappings
from etl.helpers import drive
from etl.helpers.dri... |
import gc
import os
import time
import torch
import wandb
import random
import pickle
import argparse
import numpy as np
import torch.nn as nn
from gru import GRUNet
from lstm import LSTMTagger
import torch.optim as optim
import torch.nn.functional as F
def find(name, path):
paths = []
for root, dirs, files... |
"""Presentation exchange record."""
from os import environ
from typing import Any, Mapping
from marshmallow import fields, validate
from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema
from .....messaging.valid import UUIDFour
from ..messages.pres import V20Pres
from ..messages.pres_... |
from pathlib import Path
from typing import Generator
from unittest.mock import (
MagicMock,
call,
patch,
)
from datalad.runner.exception import CommandError
from datalad.tests.utils import (
SkipTest,
assert_false,
assert_in,
assert_true,
eq_,
)
from datalad_next.patches.push_to_expor... |
import re
GROUP_DELIMITER = re.compile(r'\s*\,\s*')
KEY_VALUE_DELIMITER = re.compile(r'\s*\:\s*')
from google.cloud.bigquery import QueryJobConfig
from google.cloud.bigquery.job import CreateDisposition, WriteDisposition, QueryPriority, SchemaUpdateOption
from google.cloud.bigquery.table import EncryptionConfiguratio... |
import pkgutil, time
import inspect
import types
import importlib
import tests
# TODO
# Check for memcached being up and add the session key so we hit and load the json 43709dd361cc443e976b05714581a7fb
# memcached -l 127.0.0.1 -p 11211 -d -m 50
if 1:
package = tests
for importer, modname, ispkg in pkgutil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.