text
stringlengths
3.07k
22.1k
# -*- coding: UTF-8 -*- from random import randint from math import sqrt import random ''' import numpy import pylab ''' def make_fair_dice(sides): ''' Creation of game dice with SIDES sides >>> one_sided_dice = make_fair_dice(1) >>> one_sided_dice() 1 ''' assert type(sides) == int and sides >=...
from threading import Thread, Lock, Event from curses import doupdate from wingen import WinGen import curses class ConsoleScreen(object): def __init__ (self): self.screen = None self.clsLock = Lock () self._execThread = None self._Stop = Event () self.enabled = False def __del__ (self): if self.sc...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. 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 # to us...
#------------------------------------------------------------------------------- # Copyright (c) 2020 DOIDO Technologies # # Author : Walter # Version : 1.0.5 # Location : github #------------------------------------------------------------------------------- #-----------------------------------------------...
#! /usr/bin/python3 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # # FIXME: # # - command line method to discover installed capabiltiies; print # each's __doc__ # # - do not pass device--each function should gather it from target's # tags """ .. _pos_multiroot: Provisioning OS...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org...
import torch import torch.nn as nn # Discriminator Model class CoDis28x28(nn.Module): def __init__(self): super(CoDis28x28, self).__init__() # conv0 self.conv0_a = nn.Conv2d(3, 32, kernel_size=5, stride=2, padding=2) self.conv0_b = nn.Conv2d(3, 32, kernel_size=5, stride=2, padding=...
from __future__ import absolute_import # Copyright (c) 2010-2016 openpyxl # Simplified implementation of headers and footers: let worksheets have separate items import re from warnings import warn from openpyxl.descriptors import ( Bool, Strict, String, Integer, MatchPattern, Typed, ) from op...
# Copyright 2020 Kaggle 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, ...
# In this file, we extract the vision features as the keys in retrieval. import argparse import os import pickle import shutil import sys import h5py import torch from torchvision import transforms from torchvision.datasets.folder import default_loader import tqdm from transformers import BertTokenizer from PIL import...
#!/usr/bin/env python from __future__ import print_function import os import re import sys from datetime import datetime import click from send2trash import send2trash # Verify that external dependencies are present first, so the user gets a # more user-friendly error instead of an ImportError traceback. from elodie...
import math import time import torch import torch.cuda.nvtx as nvtx import numpy as np import torch.nn.functional as F import torch.optim as optim import torch.utils.data from tqdm import tqdm from utils.initializers import args_initialize, env_initialize, log_initialize, model_initialize from a2c.helper import call...
# -*- coding: UTF-8 -*- from flask import Flask, render_template, send_from_directory, send_file from flask import request import JsonWriter import netifaces as ni import sys import signal import wheaterData as wD from _thread import start_new_thread import time from datetime import datetime from flask import Markup im...
import types import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def get_mask(in_features, out_features, in_flow_features, mask_type=None): """ mask_type: input | None | output See Figure 1 for a better illustration: https://arxiv.org/pdf/1502.03509.pdf """ ...
#!/usr/bin/env python # coding=utf8 from __future__ import absolute_import from __future__ import division from __future__ import print_function """BFE 논문의 성능 비교를 위해 CUB BIRD200-2011 를 생성한다.""" import os import random import argparse import sys sys.path.append('./') sys.path.append('../') from datetime import datet...
""" Name: HumbleForwarder Author: kjp URL: https://github.com/kjpgit/HumbleForwarder Humble SES email forwarder. Simple address mapping is supported. Feel free to fork it if you want more configurability. See README.md for full documentation """ import email.message import email.parser import email.policy import js...
import argparse import time import numpy as np from ssn_dataset import SSNDataSet from transforms import * from ops.utils import temporal_nms import pandas as pd from multiprocessing import Pool from terminaltables import * import sys sys.path.append('./anet_toolkit/Evaluation') from anet_toolkit.Evaluation.eval_dete...
from static.simulation.plot import create_plot, create_plot2 import numpy as np from static.simulation.country import CountryCreator from static.simulation.seir import seibqhr from static.simulation.real_data import download # TODO Add True Recovered rc, rr, rd = download() countries_arr, countries_keys = CountryCreat...
from SkateUtils.NonHolonomicWorld import NHWorld, NHWorldV2 from SkateUtils.DartMotionEdit import DartSkelMotion import numpy as np from math import exp, pi, log from PyCommon.modules.Math import mmMath as mm from random import random, randrange import gym import gym.spaces from gym.utils import seeding import pydart2 ...
from __future__ import division from __future__ import print_function import time import argparse import numpy as np import torch import torch.nn.functional as F import torch.optim as optim from pygcn.utils import load_data, accuracy from pygcn.models import GCN, MLP from sklearn.preprocessing import StandardScaler ...
import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from tensorflow.keras.models import Model, load_model def identity_block(input_ten...
from Base.BaseType import * CODE_PAGE = 'cp932' SEPITH_CHI = 0 SEPITH_MIZU = 1 SEPITH_HONO = 3 SEPITH_KAZE = 2 SEPITH_TOKI = 4 SEPITH_SORA = 5 SEPITH_GEN = 6 CHIP_TYPE_CHAR = 7 CHIP_TYPE_APL = 8 CHIP_TYPE_MONSTER = 9 class ScenarioChipInfo: # ULONG chipindex def __init__(self, fs = None): ...
"""Module for Regression Testing the InVEST GLOBIO model.""" import unittest import tempfile import shutil import os import pygeoprocessing.testing from osgeo import ogr from osgeo import gdal import numpy from natcap.invest import utils SAMPLE_DATA = os.path.join( os.path.dirname(__file__), '..', ...
import pandas as pd import numpy as np import os import datetime # Helpers # Identify Win/Loss Streaks if any. def get_3game_ws(last_matches): if hasattr(last_matches, "__len__"): return 1 if len(last_matches) > 3 and last_matches[-3:] == 'WWW' else 0 return np.nan def get_5game_ws(last_matches): ...
import os import json import numpy import math from PIL import Image, ImageDraw, ImageFont import copy from tqdm import tqdm type_dict = {0:(0,255,0),1:(255,0,0),2:(230,230,0),3:(230,0,233),4:(255,0,255),5:(125, 255, 233)} def get_point(points, threshold): count = 0 points_clean = [] for point in points: ...
#!/usr/bin/env python3 import sys import json import argparse from string import Template try: from html import escape # python 3.x except ImportError: from cgi import escape # python 2.x class GCVAnnotation: height = None width = None templates = { 'ocr_page': Template("""<?xml versi...
from collections import namedtuple from collections.abc import Iterable from scipy.stats import rv_discrete, rv_continuous, multivariate_normal, norm from scipy.stats._distn_infrastructure import rv_sample from numpy import interp from os.path import dirname import numpy as np import pickle import os __all__ = ['cum_...
# cantest.py Tests of task cancellation # The MIT License (MIT) # # Copyright (c) 2017-2018 <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 li...
import sys from dataclasses import dataclass import numpy as np from scipy import spatial from utils import MinHeap, Quadric, Plane def quadric_error_function(src, tgt, halfedge): # If this is a boundary edge, form the boundary condition quadric if halfedge is not None: if halfedge.is_boundary() or...
# -*- coding: utf-8 -*- # Copyright 2017 Vector Creations Ltd # # 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...
from __future__ import unicode_literals from flask import Flask, render_template_string, Markup from unittest import TestCase from textwrap import dedent try: from unittest import mock except ImportError: import mock import misaka from misaka import (EXT_AUTOLINK, EXT_FENCED_CODE, # pyflakes.ignore ...
#!/usr/bin/python # pylint: disable=missing-module-docstring # pylint: disable=missing-function-docstring # pylint: disable=missing-class-docstring import os import shutil import sys from argparse import ArgumentParser import python_hosts from dotenv import load_dotenv from mininet.cli import CLI # from mininet.link...
import torch from torch import nn, optim import torch.nn.functional as F import random __all__ = ['ImgVAE', 'ImgDiscriminator', 'ReplayBuffer'] class ResizeConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, scale_factor, mode='nearest'): super().__init__() self.scale_fa...
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import logging as log import numpy as np from openvino.tools.mo.front.common.partial_infer.utils import assign_dims_to_weights, int64_array, compatible_dims, compatible_shapes, \ shape_array, is_fully_defined, shape_delete, shape_i...
import datetime import getpass import json import logging from copy import deepcopy from hashlib import sha1 from botocore.credentials import (CachedCredentialFetcher, CanonicalNameCredentialSourcer, CredentialProvider, Credentials, ...
from __future__ import with_statement import random import re import socket import mock from nose.tools import eq_ from statsd import StatsClient ADDR = (socket.gethostbyname('localhost'), 8125) def _client(prefix=None): sc = StatsClient(host=ADDR[0], port=ADDR[1], prefix=prefix) sc._sock = mock.Mock() ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import pytest import numpy as np import astropy.units as u from astropy.io import ascii from astropy.utils.data import get_pkg_data_filename import synphot from .. import core from ..core import * from ...photometry import bandpass from ...calib...
# coding=utf-8 # Copyright 2020 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...
from math import sqrt import einops import torch import torch.nn as nn import torch.nn.functional as F from modeling.ops import PositionalEncodingFourier, DropPath class MultiHeadXCITAttention(torch.nn.Module): def __init__(self, embed_size, num_heads, attention_dropout_rate, projection_dropout_rate, attention_...
# py--lint: disable=import-error def send_email(sender:str, receivers:list, msg_title, msg_body, smtp_server:str, password:str, cc_emails:list=None, sender_name:str='', attachment_filepath=None, attachment_name=None, receivers_can_see_eachother=False, print_ret=False) -> bool: ...
# Copyright (c) 2021 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 appli...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # OpenCenter(TM) is Copyright 2013 by Rackspace US, Inc. ############################################################################## # # OpenCenter is licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
''' STEP1: load data --> STEP2: prepare data --> STEP3: learn node embeddings --> STEP4: downstream evaluations python src/main.py --method abrw by <NAME> 2018 <<EMAIL>> ''' import time import random import numpy as np from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from sklearn.linear_model impor...
import os import time from data_util.log import logger import torch as T import rouge from model import Model from data_util import config, data from data_util.batcher import Batcher, Example, Batch from data_util.data import Vocab from beam_search import beam_search from train_util import get_enc_data from rouge impor...
""" Ray factory classes that provide vertex and triangle information for rays on spheres Example: rays = Rays_Tetra(n_level = 4) print(rays.vertices) print(rays.faces) """ from __future__ import print_function, unicode_literals, absolute_import, division import numpy as np from scipy.spatial import Con...
""" Morphology module ================= :synopsis: Create foam morphology in CAD format. .. moduleauthor:: <NAME> <<EMAIL>> """ from __future__ import print_function import os import numpy as np from blessings import Terminal from OCC.Core.gp import gp_Pnt, gp_Vec, gp_Trsf from OCC.Core.BRep import BRep_Builder from O...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import sys #from __future__ import unicode_literals from pytoxr.mathfunctions import sine, sine_perfect_helix, residuals import scipy.optimize import os #from thoipapy.sine_curve.tlabtools import tools #import tlabtools as tools #from thoipapy.utils...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. from __future__ import absolute_import, division, print_function, unicode_literals import pytest import sys import debugpy import tests from tests import debug from...
'''Check files for broken links.''' import os import re import sys import yaml import logging import requests import time from multiprocessing.dummy import Pool as ThreadPool from multiprocessing.dummy import Lock # This isn't a perfect URL matcher, but should catch the large majority of URLs. # This now matches URLs...
import datetime as dt import discord generated_ids = 0 def make_id(): global generated_ids # timestamp discord_epoch = str(bin(int(dt.datetime.now().timestamp() * 1000) - 1420070400000))[2:] discord_epoch = "0" * (42 - len(discord_epoch)) + discord_epoch # internal worker id worker = "00001"...
# coding: utf-8 ''' Module to be used for static analysis ''' import numpy as np import sympy as sp import scipy import matplotlib.pyplot as plt from matplotlib import patches from mpl_toolkits.mplot3d import Axes3D def simple_support(): L = 15 P = 5 Ploc = 5 plt.rcParams['figure.figsize'] = (10, 8)...
import time from typing import Any, Iterable, List, Optional, Set, Union import numpy as np import wrapt def subsample_sequence(old_len, new_len): if new_len == old_len: return 0, old_len assert new_len < old_len max_start = old_len - new_len start = np.random.randint(0, max_start) return...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import collections import json from crypto import (PublicKey, PrivateKey, seed_from_mnemonic, root_from_seed, decode_xkey, xpub_from_xprv, private_derivation, public_derivation) from address import Address from mnemonic import generate_mnemonic from ...
import tensorflow as tf import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import re import sys import time import pickle import I2S_Model from datetime import datetime np.set_printoptions(threshold=sys.maxsize) tpu = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='node-3') print('Runni...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegres...
import logging import numpy import chaospy def approximate_inverse( distribution, idx, qloc, bounds=None, cache=None, parameters=None, xloc0=None, iterations=300, tolerance=1e-12, ): """ Calculate the approximation of the inverse Rosenbl...
import numpy as np import tensorflow as tf import cv2 import tqdm from network_sn import Network import load import random IMAGE_SIZE = 128 LOCAL_SIZE = 64 HOLE_MIN = 24 HOLE_MAX = 48 LEARNING_RATE = 5e-4 BATCH_SIZE = 16 PRETRAIN_EPOCH = 100 HOGO = 100 BETA1 = 0.9 BETA2 = 0.999 RETAIN = True def train(): val_g =...
from scipy.stats.stats import pearsonr, spearmanr from plotly import tools from plotly.graph_objs import * from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go import matplotlib.pyplot as plt import seaborn as sns import itertools import numpy as np import pandas ...
# Copyright (c) 2019, Myrtle Software Limited. All rights reserved. # Copyright (c) 2019, NVIDIA 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 # # ...
from downloader import Downloader from descriptive_analysis import * from export_collection_data import * from pymongo import MongoClient from pymongo.errors import PyMongoError from bs4 import BeautifulSoup from datetime import datetime import ssl import re ssl._create_default_https_context = ssl._create_un...
import asyncio import datetime import json import asyncpg import discord from discord.ext import commands, tasks from discord.ext.commands.cooldowns import BucketType class Stats(commands.Cog): def __init__(self, bot): self.bot = bot # Track command count self.command_count = 0 s...
"""Datadog monitor to OSC messages This program reads the query from a Datadog monitor, calls their query API and normalizes the resultant values against the threshold to send out as an OSC message """ import argparse import os import time import sys from pprint import pprint from pythonosc import udp_client from ...
#!/usr/bin/env python ###################################################################### # Software License Agreement (BSD License) # # Copyright (c) 2012, Rice University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that t...
# coding=utf-8 """API to most common queries to the dataset.""" import collections import os import sqlite3 from typing import AnyStr import tqdm def main(): db_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '../data/dataset/evalution2.db')) # use verbose=1 for debugging. db = EvaldDB(d...
import json import logging import os from pathlib import Path from typing import Tuple import hydra import numpy as np import torch from apex.parallel.LARC import LARC from omegaconf import OmegaConf from torch.utils.data import DataLoader from src.data.ag_news import (CollateSupervised, collate_eval_batch, ...
import auth, os, random, re, socket, sys, time import sqlite3 as sql from markov import Markov DIR = os.path.dirname(os.path.realpath(__file__)) print(DIR) """ Helper functions. """ # Initiation. def init (): init_ops() # Average output generator def avg (list_): x = 0 for i in list_: x += i return int(x / l...
import os, time import unittest import pandas as pd import numpy as np from pathlib import Path from pyrolite.util.synthetic import test_df, test_ser from pyrolite.util.general import temp_path, remove_tempdir from pyrolite.util.meta import subkwargs from pyrolite.util.pd import * class TestColumnOrderedAppend(unitte...
''' ############################################################################### FIT POLYNOMIAL MODULE ############################################################################### This module contains the following functions: Polynomial fits --------------- > fit_poly(x,y) > fit_polynomial(data) > polyfit2d(x, ...
# -*- coding: utf-8 -*- """ @created on: 9/21/19, @author: <NAME>, @version: v0.0.1 @system name: badgod Description: ..todo:: """ import numpy as np import random from collections import defaultdict """ Monte-Carlo In this problem, we will implememnt an AI player for Blackjack. The main goal of thi...
## @package optimizer_test_util # Module caffe2.python.optimizer_test_util from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import numpy as np from caffe2.python import brew, core, workspace, cnn, optimi...
import os import sys DEBUG = False COMPRESS = True OVERWRITE = True sys.path.insert(0, '../..') import tabixpy def runTest(testName, infile, expects, indexType): tb = tabixpy.Tabix(infile, indexType=indexType) gzfile = tb.bgz indexFile = tb.indexFile sourceFile = tb.sourceFile ...
# Original Link: https://github.com/kuangliu/pytorch-cifar/ # Original Author: <NAME> # Original License: MIT # Adapted to support Model quantization '''MobileNetV2 in PyTorch. See the paper "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" for more details. '...
"""Testing utilities """ from textwrap import dedent from xml.etree import ElementTree import time import datetime import calendar def to_utc(a_datetime): timestamp = time.mktime(a_datetime.timetuple()) return datetime.datetime.utcfromtimestamp(timestamp) def to_rfc3339(a_datetime): utc_dt = to_utc(a_d...
import math import numpy as np import os import pandas as pd import torch from tqdm import tqdm as tqdm from spacy import displacy from spacy.util import is_in_jupyter from transformers import AutoTokenizer from typing import Dict from thermostat.data import get_local_explanations from thermostat.utils import delistif...
"""watch a given directory for file changes using the command line, useful for demos""" import os, platform, sys, time, argparse, math, logging from colour import Colour def normalised_path(input_path:str) -> str: """returns a normalised "real"/"full" filepath for a given directory then checks its a valid dir...
import importlib import inspect import os import re import sys import traceback from types import FunctionType, MethodType from devtool.utils.getModules import get_modules_location from graphviz import Digraph from entity2uml import FakeClass, __default_methods__ from entity2uml.drawer import (Diagram, __engines__, _...
import ast from unittest import TestCase from darglint.lex import ( condense, lex, ) from darglint.parse.sphinx import ( parse, ) from .sphinx_docstrings import docstrings from darglint.utils import ( CykNodeUtils, ) class SphinxParserTest(TestCase): def test_parse_short_description_is_line_cyk(...
import math import numpy as np from numpy import linalg as LA import numpy as np import scipy from scipy.sparse import * from scipy.sparse.linalg import norm import time import nonnegfac import importlib importlib.reload(nonnegfac) def claculate_norm(X, A, K, PARFOR_FLAG): # UNTITLED3 Summary of this function go...
from __future__ import division from __future__ import print_function from __future__ import absolute_import from builtins import zip from builtins import range from builtins import object from past.utils import old_div import numpy as np import pandas as pd import os import collections from ..serialize import Seriali...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. 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 th...
import os.path as path import logging import sqlite3 import pickle from collections import deque from ipaddress import ip_address from threading import Lock from time import time, sleep from urllib.parse import urlparse from tracker import Tracker max_input_length = 20000 submitted_trackers = deque(maxlen=10000) if p...
# Required to upload files from rest_framework.parsers import FileUploadParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework import generics from .serializers import AmenitiesSerializer, MmuSerializer from .models import Ameni...
"""This file contains some sample functions for the domain operations. Since Union/Cut/Intersection follow the same idea for sampling for a given number of points. """ import torch import warnings from torchphysics.problem.spaces.points import Points def _inside_random_with_n(main_domain, domain_a, domain_b, n, para...
""" The MIT License (MIT) Copyright © 2015 RealDolos Copyright © 2018 Szero 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, cop...
import unittest from pathlib import Path from bridgebots.board_record import BidMetadata from bridgebots.deal_enums import Direction, Rank, Suit from bridgebots.pbn import _build_record_dict, _parse_bidding_record, _sort_play_record, parse_pbn class TestParsePbnFile(unittest.TestCase): def test_parse_file(self):...
import numpy as np import gym import matplotlib.pyplot as plt SHOW_ENV_DISPLAY_FREQUENCY = 100 DEFAULT_ITERATION_COUNT = 100000 Observation = [30, 30, 50, 50] np_array_win_size = np.array([0.25, 0.25, 0.01, 0.1]) # Creates a table of Q_values (state-action) initialized with zeros # Initialize Q(s, a), for all s ∈ S,...
#!/usr/bin/env python """*************************************************************************** ** ** Copyright (C) 2005-2005 Trolltech AS. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License versio...
#!/usr/bin/env python # coding=utf-8 """Module Description Copyright (c) 2018 <NAME> <<EMAIL>> This code is free software; you can redistribute it and/or modify it under the terms of the MIT License. @Gene-panel sequencing analysis pipeline in somatic mode @status: experimental @version: 1.0 @author: <NAME> @contact...
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from collections import namedtuple from typing import Union import torch from pytorch3d import _C from torch.a...
# -*- coding: utf-8 -*- import torch import torch.nn as nn from supar.modules.dropout import SharedDropout from torch.nn.modules.rnn import apply_permutation from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence class CharLSTM(nn.Module): r""" CharLSTM aims to generate character-level embedding...
from nltk.stem.snowball import SnowballStemmer from nltk.corpus import stopwords from summariser.rouge.rouge import Rouge import summariser.utils.data_helpers as util import numpy as np import operator as op import functools from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text im...
from __future__ import print_function from copy import copy, deepcopy import datetime import inspect import sys import traceback from django.core.management import call_command from django.core.management.commands import loaddata from django.db import models from django import VERSION as DJANGO_VERSION import south....
from pynq import Overlay from pynq.lib import AxiGPIO ol = Overlay("./overlays/CICADA_N_CLAIRE.bit") import numpy as np import time trig_ldo_dut_ip = ol.ip_dict['gpio_spi_trig_ldo_dut'] dut_tx_rx_data_ip = ol.ip_dict['gpio_spi_dut_tx_rx_data'] ts_rst_dut_rst_ip = ol.ip_dict['gpio_spi_ts_rst_dut_rst'] trig_dut = AxiG...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import pandas as pd from numpy import float64 as npfloat64 from scipy.sparse import coo_matrix, csr_matrix from sklearn.model_selection import ParameterGrid from implicit.als import AlternatingLeastSquares from implicit.evaluation import train_test_split from imp...
#!/usr/bin/env python import sys import multiprocessing import gzip import os from subprocess import check_call as cc, CalledProcessError from enum import IntEnum argv = sys.argv if sys.version_info[0] != 3: raise Exception("Python 3 required") class ExitCodes(IntEnum): EXIT_SUCCESS = 0 EXIT_FAILURE = 1...
#! /usr/bin/env python # encoding: utf-8 # <NAME>, 2011 (ita) """ A client for the network cache (playground/netcache/). Launch the server with: ./netcache_server, then use it for the builds by adding the following: def options(opt): opt.load('netcache_client') The parameters should be present in the environment ...
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] <NAME>, <NAME>, <NAME>, <NAME> Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np cla...
import numpy as np from rsrespic.utilities import constants from numpy import exp, sin, einsum import numba pi = np.pi q = constants.cgs_constants['q'] c = constants.cgs_constants['c'] ## Convert units to cgs from mks class sine_transform_2D(object): def __init__(self): self.name = '2-d electrostatic solv...
# -*- coding: utf-8 -*- # Copyright 2020 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 law ...
#!/usr/bin/env python import argparse import contextlib from collections import defaultdict import string import sys import os def main(): script_path = os.path.realpath(__file__) script_dir = os.path.dirname(script_path) default_input = os.path.join( script_dir, "UnitTests", "TestData", "gen", "...