text stringlengths 3.07k 12.6k |
|---|
#
# Copyright (c) 2018 Intel Corporation
#
# 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... |
import node
import string
import random
import container
import control
# List of needed control nodes:
# s:load - input set of strings
# o:time - increments time between generations - (ClockObserver)
# s:samplertank - Chooses a tank to work over that hasn't been chosen in the current generation - (SimpleSampler... |
#!/usr/bin/python
import MySQLdb
from MySQLdb import cursors
from math import sqrt
import sys
def computeYearlyStatsDeviation(db):
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = """SELECT word, cnt2000, cnt2001, cnt2002, cnt2003, cnt2004, cnt2005, cnt2006, cnt2007, cnt2008, cnt... |
# -*- coding: utf-8 -*-
"""Parser for utmpx files."""
from dfdatetime import posix_time as dfdatetime_posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import errors
from plaso.lib import definitions
from plaso.lib import specification
from plaso.parsers import dtf... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2015 Kitware 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 cop... |
# coding=utf-8
# analyse the performance of the strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns as rts
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.stratanalyzer import drawdown
from pyalgotrade.stratanalyzer import trades
from utility import Stock
from ... |
from datasets import *
from model import fc_resnet50
from prm.prm import peak_response_mapping
from losses import multilabel_soft_margin_loss
from solver import Solver
import os
import yaml, json
from utils import *
from util import *
import PIL.Image
import argparse
import cv2
import pandas as pd
import t... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 1996-2018 Cyberbotics 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 applicable law or agreed to in... |
from abc import abstractmethod
from collections.abc import Mapping, MutableMapping
from copy import deepcopy
from typing import (
Any,
Dict,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Set,
Type,
TypeVar,
Union,
)
import attr
from fontTools.misc.transform import Transfor... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import nltk
import re
def load_data_and_labels(path):
data = []
lines = [line.strip() for line in open(path)]
for idx in range(0, len(lines), 4):
id = lines[idx].split("\t")[0]
relation = lines[idx + 1]
sentence = lines[idx].split("\t")[1][1:-1... |
from .workflows import *
from copy import deepcopy
def bll6_forest_no_wic():
"""
No wic features
"""
return bll6_models(
forest(),
transform_search={'exclude':[['^wic.*']]})
def bll6_forest_no_kid():
"""
No kid-level aggregations
"""
args = deepcopy(aggregations... |
import unittest
import numpy
import pytest
import cupy
from cupy import testing
from cupy.testing import attr
import cupyx
from cupyx import lapack
@testing.parameterize(*testing.product({
'dtype': [numpy.float32, numpy.float64, numpy.complex64, numpy.complex128],
'n': [3],
'nrhs': [None, 1, 4],
'or... |
import logging
import math
import time
from urllib.parse import urlencode
import requests
from common.debug_util import use_debug_files
from common.ibc.api_common import (
EVENTS_TYPE_LIST_DEFAULT,
EVENTS_TYPE_RECIPIENT,
EVENTS_TYPE_SENDER,
EVENTS_TYPE_SIGNER,
TXS_LIMIT_PER_QUERY,
remove_duplic... |
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import time
import collections
import argparse
import numpy as np
import sklearn.neighbors
import tensorflow as tf
import keras
import dca_modpp.io
import Cell_BLAST as cb
import utils
N_EMPIRICAL = 10000
MAJORITY_THRESHOLD... |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.template import RequestContext
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
from django.http import Http404, HttpResponse, HttpResponseForbidden, Http... |
import requests
RESPONSE_CODES = {
200: "Operation successful",
204: "The resource was deleted successfully",
404: "Resource not found",
422: "Invalid input",
}
class AirbyteResponse:
def __init__(self, response):
if response.status_code in RESPONSE_CODES:
self.message = RESPO... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from django.db import models
from django.conf import settings
from django.contrib.auth import get_user_model
from simple_history.models import HistoricalRecords
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.utils.translation import u... |
"""
Copyright 2018 EPAM Systems, 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... |
"""
Assets
======
Coaster provides a simple asset management system for semantically versioned
assets using the semantic_version_ and webassets_ libraries. Many popular
libraries such as jQuery are not semantically versioned, so you will have to
be careful about assumptions you make around them.
.. _semantic_version:... |
#! /bin/env python
# -*- coding: utf-8 -*-
"""
reference -
"""
import logging
from django.contrib import messages
from django.http import Http404, HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from dja... |
"""
Copyright (C) 2018-2021 Intel Corporation
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 i... |
import math
import time
from ..math import vectorops
from cspace import CSpace
def default_sampleneighborhood(c,r):
return [ci + random.uniform(-r,r) for ci in c]
def default_visible(a,b):
raise RuntimeError("Can't check visibility")
def default_distance(a,b):
return vectorops.distance(a,b)
def default_... |
"""
Setup a custom except hook which formats exceptions that are uncaught.
In "DEBUGMODE", we'll just use the typical sys.excepthook behavior and print a
stacktrace. It's really for debugging problems with the CLI itself, but it
might also come in handy if we have issues with the way that we're trying to
format an exce... |
import yaml
from yaml.loader import Loader
import operator
from functools import reduce
from copy import deepcopy
from .py_utils import create_instance
try:
import torch
except ImportError:
torch = None
try:
import numpy as np
except ImportError:
np = None
def add(loader, node):
return sum(loade... |
import re
from .base.base import BasePhoneticsAlgorithm
from .config import RU_PHONEMES, FI_VOWELS, RU_VOWELS, EE_VOWELS, \
RU_REMOVE_MAP, RU_REPLACEMENT_J_MAP, RU_REPLACEMENT_VOWEL_MAP, RU_DEAF_CONSONANTS, \
EE_FI_DEAF_CONSONANTS, SE_VOWELS, SE_DEAF_CONSONANTS, SE_PHONEMES
class Metaphone(BasePhoneticsAlgor... |
# Copyright 2019 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 or agreed to in writing, so... |
# coding: UTF-8
import argparse
import os
import chainer
import numpy as np
from PIL import Image
import chainer.functions as F
import chainer.links as L
from chainer import initializers
from chainer import training
from chainer import Variable
from chainer import cuda
from chainer.dataset import iterator as iterator_m... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
"""Helper functions for calculating optimal binary quantization."""
from typing import Tuple
import torch
import torch.nn.utils.rnn as rnn_utils
from quant.binary.ste import binary_sign
def cost_function(matrix... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: ts=2 sw=2 et ai
###############################################################################
# Copyright (c) 2012,2021 <NAME> <EMAIL>
# parts of this software are based on tiler_tools (...)
# the license terms (see below) apply to the complete software the sam... |
# -*- coding: UTF-8 -*-
import json
from django.shortcuts import render
from django.contrib import messages
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.generic.base import View
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string... |
def potGraph(a, Etot, V0, ax1):
import numpy as np
import matplotlib.pyplot as plt
xtk = np.linspace(0,a*8,9)
ax1.set_xticks(xtk)
xlab = [0]+['{}a'.format(n) for n in range(1,9)]
ax1.set_xticklabels(xlab)
ytk = [-Etot, -V0, 0, V0, Etot]
ylab = [r'$-E_{tot}$', r'$-V_0$', '0', r'$V_0... |
# general imports
import os
import os.path
import sys
import json
import shlex
import re
from multiprocessing.pool import ThreadPool
from math import ceil, log2
from collections import namedtuple
from argparse import ArgumentParser
from subprocess import Popen, PIPE, STDOUT
from glob import glob
from typing import Unio... |
# RT - Original Command
from discord.ext import commands
import discord
from rtlib import DatabaseManager
class DataManager(DatabaseManager):
DB = "OriginalCommand"
def __init__(self, db):
self.db = db
async def init_table(self, cursor) -> None:
await cursor.create_table(
... |
import time
import numpy as np
import torch as pt
import math
# choose cpu or gpu computing
dvc = pt.device("cuda")
# tune default type
pt.set_default_dtype(pt.double)
pt.cuda.synchronize()
t0 = time.time()
pi = math.pi
def kron(m1, m2):
"""
matrix kronecker product
"""
return pt.... |
import optparse
import os
import shutil
import stat
import sys
import cx_Freeze
__all__ = ["main"]
USAGE = \
"""
%prog [options] [SCRIPT]
Freeze a Python script and all of its referenced modules to a base
executable which can then be distributed without requiring a Python
installation."""
VERSION = \
"""
%%prog %s... |
# Copyright 2020, The TensorFlow Federated 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 o... |
"""
This module provides classes to build an OrderList for input to a plant,
including the Order instances and their Recipe instances.
"""
from xml.dom import minidom
from plant import CraneMoveTime
class Recipe(object):
"""
This class provides a Recipe for an Order. It is a list (or dictionary) of
tuples (str mac... |
"""
:mod:`braindump` exposes an API to serialize and deserialize Pegasus's braindump file.
Basic Usage::
>>> from Pegasus import braindump
>>> braindump.loads("user: mayani\ngrid_dn: null\n")
{'grid_dn': None, 'user': 'mayani'}
>>> print(braindump.dumps({"grid_dn": None, "user": "mayani"}))
'{"gr... |
from openapi_server.models.address import Address
from openapi_server.models.tx_summary import TxSummary
from openapi_server.models.address_tag import AddressTag
from openapi_server.models.address_tags import AddressTags
from openapi_server.models.neighbors import Neighbors
from openapi_server.models.neighbor import Ne... |
import os
import numpy as np
import data_provider
import gc
import time
from itertools import combinations, permutations
'''
本脚本是將样本的激活数据的边覆盖情况具现化保存
数据结构边写边考虑
'''
'''
目前只考虑1-1的三种情况的覆盖
写尽可能考虑可拓展性
'''
def check_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# 获取两层之间的每个数据的对应的
def p... |
from math import pi
from typing import Optional, Literal
import random
from direct.showbase.Loader import Loader
from panda3d.core import NodePath, Point3F, Quat, Vec3
class Track:
LENGTH = 2
def __init__(
self, direction: Vec3, normal: Vec3, start_pos: Point3F, node_path: NodePath
):
se... |
import pygame
import random
import math
import os
pygame.init()
PATH = os.getcwd().replace('\\', '/')
img = pygame.image.load('./img/icon.png')
pygame.display.set_icon(img)
class DrawInformation:
BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
GREEN = 0, 255, 0
BLUE = 0, 0, 255
BACKGROU... |
import pandas as pd # data analysis toolkit - create, read, update, delete datasets
import numpy as np #matrix math
from sklearn.model_selection import train_test_split #to split out training and testing data
#keras is a high level wrapper on top of tensorflow (machine learning library)
#The Sequential container is a ... |
import json
import logging
import os
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
import pre_commit.constants as C
from pre_commit.clientlib import load_manifest
from pre_commit.clientlib i... |
import json
import os
import shutil
import time
import pandas as pd
import numpy as np
import pathlib
import geopandas as gpd
import pysal as ps
from sklearn import cluster
from sklearn.preprocessing import scale
# Data reading & Processing
app_path = pathlib.Path(__file__).parent.resolve()
data_path = pathlib.Path(... |
from django.contrib import messages
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext
from ..forms import (
AnonymousUserBillingForm, BillingAddressesForm,
BillingWithoutShippingAddressForm)
from ...userprofile.forms import... |
import os
import sys
import cv2
import time
import logging
import json
import tensorflow as tf
import numpy as np
import glob
import tqdm
tf.compat.v1.disable_eager_execution()
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
import src
from src.data_manager import EmojifierDataManager
from src.__in... |
import logging
import multiprocessing
import os
from collections import defaultdict
from datetime import datetime
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
from sklearn.model_selection import KFold, StratifiedKFold, RepeatedKFold, RepeatedStratifiedKFold, train_test_split
from .const... |
import datetime
import enum
import attr
import six
from dbnd._core.utils.timezone import make_aware, utcnow
RESULT_PARAM = "result"
CURRENT_DATETIME = utcnow()
CURRENT_TIME_STR = CURRENT_DATETIME.strftime("%Y%m%d_%H%M%S")
CURRENT_DATE = CURRENT_DATETIME.date()
class EnvLabel(object): # env label
dev = "dev"... |
from pathlib import Path
import yaml
from simod.configuration import config_data_from_file, AndPriorORemove, Configuration, GateManagement, MiningAlgorithm, \
CalendarType, DataType, PDFMethod, Metric, ExecutionMode, SimulatorKind
class TestConfigurationFromStringConversion:
def test_MiningAlgorithm_from_st... |
import sqlite3
try:
import tkinter
except ImportError: # python 2
import Tkinter as tkinter
conn = sqlite3.connect('lesson_176_music.sqlite')
class Scrollbox(tkinter.Listbox):
def __init__(self, window, **kwargs):
# tkinter.Listbox.__init__(self, window, **kwargs) # Python 2
super()._... |
import logging
import osmo.api_historical
from osmo.config_osmo import localconfig
import osmo.constants as co
def _transfers(log, wallet_address):
"""
Parses log element and returns (list of inbound transfers, list of outbound transfers),
relative to wallet_address.
"""
transfers_in = _transfers... |
import logging
from homeassistant.components.camera import Camera
import requests
import os
import pickle
from homeassistant.components.local_file.camera import LocalFile
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
DOMAIN,
CONF_PHOTOS_ENTITY,
CONF_PHOTOS,
... |
from __future__ import print_function
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
import numpy as np
from copy import deepcopy
from utils.model_utils import calc_emd, calc_cd
# Number of children per tree levels for 2048 output points... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
#!/usr/bin/env python3
"""build_pot
Build a PO template (for i18n) and update the .po files to reflect
the last changes.
"""
import glob
import os.path
import sys
import tokenize
from distutils.core import Command
from utils.i18n import pygettext
# from pygettext.main():
class Options:
# constants
GNU = 1
... |
def gen(i,j,c):
return j+1+(i*c)
def cUp(m,i,j):
return (m[i-1][j]!="#")
def cRight(m,i,j):
return (m[i][j+1]!="#")
def cDown(m,i,j):
return (m[i+1][j]!="#")
def cLeft(m,i,j):
return (m[i][j-1]!="#")
def getAdjecencyList(m,r,c):
g={}
for i in range(0,r):
for j in ran... |
# 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
# distributed under the... |
from flask import abort, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session
from csh import constants
from csh import db
from csh.disanfang.gongyong import user_pd,news_phb
from csh.models import News, Comment, CommentLike, User
from csh.modules.news impor... |
"""
Bokeh based functions for line, histogram and bar charts
"""
import os
import time
import numpy as np
from bokeh import __version__ as bokeh_release_ver
from bokeh.plotting import figure
from bokeh.models import (
HoverTool,
NumeralTickFormatter
)
LOADER = """
#loader {
position: absolute;
... |
"""Provides a core function for validating proofs along with a class for validation receipts
"""
from .hashing import hash_machine
from .serializers import ReceiptSerializer
import uuid
import time
import json
import os
def validateProof(target, proof):
"""Core utility for validating proofs
Validates the in... |
import os
import argparse
from sklearn.feature_selection import (
SelectKBest,
mutual_info_classif,
)
from imblearn.over_sampling import RandomOverSampler
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
import classifiers as clfs
import utils
def main(args):
print("Loading and prep... |
# -*- coding: utf-8 -*-
# Copyright 2021 Tampere University and VTT Technical Research Centre of Finland
# This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Aut... |
"""
Pydantic schemas for the Moonstream HTTP API
"""
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from pydantic import BaseModel, Field
USER_ONBOARDING_STATE = "onboarding_state"
class TimeScale(Enum):
month = "month"
week = "w... |
# -*- coding: utf-8 -*-
import torch
from torch import nn
from torch.nn import functional as F
import nics_fix_pt as nfp
import nics_fix_pt.nn_fix as nnf
import numpy as np
def _generate_default_fix_cfg(names, scale=0, bitwidth=8, method=0,
range_method=nfp.RangeMethod.RANGE_MAX):
re... |
from selenium import webdriver
from bs4 import BeautifulSoup
import json
import time
from selenium.webdriver.common.by import By
import csv
browser = webdriver.Chrome()
pageurl = "https://www.linkedin.com/uas/login?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fsearch%2Fresults%2Fpeople%2F%3Fnetwork%3D%255B%25... |
import io
from typing import BinaryIO, Optional
from .base import CIOType, CFixedType
from .buffer import c_buffer
from ..encoding import auto_decode
__all__ = [
'CStringType',
'c_str',
'CSizedStringType',
'c_sized_str',
]
def _auto_encode(s: str, encoding) -> bytes:
return s.encode(encoding if ... |
import os
import numpy as np
from netCDF4 import Dataset
import pytest
from desc.equilibrium import Equilibrium, EquilibriaFamily
from desc.grid import Grid, LinearGrid
from desc.utils import area_difference
from desc.__main__ import main
def test_compute_geometry(DSHAPE):
"""Test computation of plasma geometric... |
#!/usr/bin/python
"""
Copyright (c) 2015, ICFLIX Media FZ LLC All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Desc: Nagios auto-reconfigurator meant to be executed from cron
"""
import argparse
import json
import logging
import logging.handlers
imp... |
import numpy as np
from typing import Tuple
from IMLearn.metalearners.adaboost import AdaBoost
from IMLearn.learners.classifiers import DecisionStump
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def generate_data(n: int, noise_ratio: float) -> Tuple[np.ndarray, np.... |
from typing import Optional
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QVBoxLayout, QLineEdit, QTreeWidget, QTreeWidgetItem, QPushButton
from angr.analyses.decompiler.decompilation_options import options as dec_options
from angr.analyses.decompiler.optimization_passes import get_optimization... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
import logging
from datetime import datetime
from typing import Optional, Tuple
from waitlist.storage.database import APICacheCharacterInfo, APICacheCorporationInfo, SSOToken
from waitlist.utility.outgate.exceptions import check_esi_response, ESIException,\
ApiException
from waitlist.utility.swagger.eve.character ... |
import torch
from pytorch3d.structures import Meshes
from pytorch3d.renderer import look_at_view_transform, FoVPerspectiveCameras, RasterizationSettings, PointLights, \
MeshRenderer, MeshRasterizer, SoftPhongShader, TexturesVertex
from vedo.mesh import Mesh
from vedo.io import screenshot
from vedo.plotter import sh... |
# Copyright (C) 2016 Ion Torrent Systems, Inc. All Rights Reserved
import logging
import json
import httplib2
import urlparse
from django.conf import settings
from iondb.rundb.plan.ampliseq import AmpliSeqPanelImport
from iondb.utils.utils import convert
logger = logging.getLogger(__name__)
"""
This parses all the e... |
# -*- coding:utf-8 -*-
# Copyright xmuspeech (Author: JFZhou 2020-05-31)
import numpy as np
import os
import sys
sys.path.insert(0, 'subtools/pytorch')
import libs.support.kaldi_io as kaldi_io
from plda_base import PLDA
class CORAL(object):
def __init__(self,
mean_diff_scale=... |
"""
Interface for integrating with DLPack.
Some of the following code is derived from the following resources:
https://github.com/dmlc/dlpack/blob/main/apps/from_numpy/main.py
https://github.com/vadimkantorov/pydlpack/blob/master/dlpack.py
"""
import ctypes
import dace
import torch
import torch.utils.dlpack
from dac... |
import time
import random
import hashlib
from social.utils import setting_name, to_setting_name, module_member
from social.store import OpenIdStore
class BaseTemplateStrategy(object):
def __init__(self, strategy):
self.strategy = strategy
def render(self, tpl=None, html=None, context=None):
... |
###################################
# This scraper shows you how to gather assets from
# a Frame.io account and write to a CSV.
# Assets are gathered recursively from each
# team's projects. Folders, files and version stacks are written to the CSV.
# Note: Debug statements are left in the file and commented out.
#####... |
import json
import os
import sys
from logging.config import dictConfig
from urllib.parse import urlencode
import boto3
import responses
from dotenv import load_dotenv
from flask import Flask
from flask import request
from moto import mock_dynamodb2
from pyngrok import ngrok
from twilio.rest import Client
from utils.j... |
from dataclasses import dataclass
from typing import Dict, List, Sequence, Tuple
from django.conf import settings
from django.core.management.base import BaseCommand
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from gnosis.eth import EthereumClientProvider
from gnosis.eth.ethereum_client impo... |
"""
Utility functions surrounding terminal devices & I/O.
Much of this code performs platform-sensitive branching, e.g. Windows support.
This is its own module to abstract away what would otherwise be distracting
logic-flow interruptions.
"""
from contextlib import contextmanager
import os
import select
import sys
... |
# -*- coding: utf-8 -*-
# ToMaTo (Topology management software)
# Copyright (C) 2010 <NAME>, University of Kaiserslautern
#
# 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 ... |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
The notarization module manages uploading artifacts for notarization, polling
for results, and stapling Apple Notary notarization tickets.
"""
import os
... |
from argparse import ArgumentParser
from typing import List, Dict
import pandas as pd
import numpy as np
import os
from glob import glob
from itertools import combinations, product
from common import Role, Argument
from evaluate import Metrics, joint_len, iou
from evaluate_dataset import eval_datasets, yield_paired_p... |
import random
import torch
import torch.nn as nn
from nntools.nnet import register_loss
class MultiLabelSoftBinaryCrossEntropy(nn.Module):
def __init__(self, smooth_factor: float = 0, weighted: bool = True,
mcb: bool = False, hp_lambda: int = 10,
epsilon: float = 0.1, logits=Tru... |
import numpy as np
import pytest
from sunkit_image import asda
from sunkit_image.data.test import get_test_filepath
def test_asda_artificial():
"""
Generate an artificial vortex using the Lamb_Oseen class in asda, then
perform the vortex detection.
"""
# Generate an artificial vortex
vmax = 2... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
from captain.reflection import (
ReflectCommand,
ReflectMethod,
ParseArg,
Name,
)
from captain import Command
from . import testdata, TestCase, FileScript, ModuleScript
class Re... |
import math
import torch
import torch.nn.functional as F
from torch import nn
class ResidualBlock(nn.Module):
def __init__(self, channels):
super().__init__()
self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
self.prelu = nn.PReLU()
self.conv2 = nn.Conv2d(channe... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-0307-Range-Sum-Query-Mutable.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-04-04
===========================... |
#!/usr/bin/env python3
#
# Author: <NAME>
# Affiliation: ANYbotics
# Date: 16.01.2020
import struct
from os.path import commonprefix
from warnings import warn
from .config import TOPIC_SEPARATOR
common_suffixes = []
common_suffixes.extend(['_angular_{}'.format(coord) for coord in ['x', 'y', 'z']])
c... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 28 22:19:20 2021
@author: yoonseok
"""
from soynlp.noun import LRNounExtractor_v2
from soynlp.word import WordExtractor
from soynlp.tokenizer import LTokenizer
from konlpy.tag import Hannanum, Kkma, Okt
from PyKomoran import Komoran
from ckonlpy.tag import Twitter
import... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from tempfile import mkdtemp
from shutil import rmtree
import numpy as np
from nipype.testing import (assert_equal, assert_false, assert_true,
assert_raises, skipif)
... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# Copyright 2020 The TensorTrade 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 agreed to... |
# Copyright 2014 Diamond Light Source 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 applicable law or agreed t... |
import os
import sys
import glob
import json
from .Loader import Loader
from ..Versioned import Versioned
# compatibility with python 2/3
try:
basestring
except NameError:
basestring = str
class UnexpectedRootContentError(Exception):
"""Unexpected root content error."""
class UnexpectedAddonsDataError(Ex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.