text stringlengths 3.07k 22.1k |
|---|
# <NAME> - 170401040
from socket import*
from os import system, name
import os
import time
import sys
os.chdir("istemci dosyaları") # Istemciye ait dosyaların bulundugu klasore yukseltir
def listele(): ... |
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 b... |
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Train and eval functions used in main.py
"""
import json
import os
import math
from typing import Iterable, Optional
import torch
from timm.data import Mixup
from timm.utils import accuracy
from timm.loss import SoftTargetCrossEntropy
from torch.n... |
import numpy as np
from scipy import signal, ndimage
from math import floor
import SBM_gauss
def ssim(img1, img2, cs_map=False):
"""Return the Structural Similarity Map corresponding to input images img1
and img2 (images are assumed to be uint8)
This function attempts to mimic precisely th... |
# -*- coding: utf-8 -*-
r"""
Frequency-dependent foreground components.
This module implements the frequency-dependent component of common foreground
contaminants.
This package draws inspiration from FGBuster (<NAME> and <NAME>)
and BeFoRe (<NAME> and <NAME>).
"""
import inspect
import types
import numpy as np
from ... |
# Copyright 2021 The Private Cardinality Estimation Framework 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 b... |
from simpleeval import simple_eval, NameNotDefined
from datetime import datetime
import uuid
import copy
import pylabnet.utils.pulseblock.pulse as po
import pylabnet.utils.pulseblock.pulse_block as pb
from pylabnet.utils.iq_upconversion.iq_calibration import IQ_Calibration
from pylabnet.utils.pulseblock.placeholder im... |
# Solving Riddler Classic @ https://fivethirtyeight.com/features/can-you-guess-the-mystery-word/
# Using Python 3.9
#
# Rather than exploring all possible word combinations, it uses a heuristic approach,
# namely: considering only words made up of the letters that are most frequent in 5-letter words,
# position by posi... |
from datetime import datetime
import itertools
import json
import joblib
import matplotlib.pyplot as plt
import numpy as np
from keras.callbacks import ModelCheckpoint
import tensorflow_hub as hub
from keras_preprocessing.sequence import pad_sequences
from sklearn.utils import shuffle
from keras.models import Sequent... |
#!/usr/bin/python
from threading import Thread
from threading import Lock
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
import json
from urllib import parse
import pandas as pd
import csv
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas imp... |
# Copyright (c) 2017, IGLU consortium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and... |
import time, psutil, gc, tracemalloc, threading, weakref, datetime, sys, random
import logging
from collections import namedtuple
from IPython import get_ipython
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
#logger.setLevel(logging.DEBUG)
def b2mb(x): return int(x/2**20)
... |
# Python modules.
import os
# Django modules.
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect, JsonResponse, HttpResponseNotFound
from django.shortcuts import get_object_or_404
# Django Rest Framework
from rest_framework.response import Response
from re... |
#! /usr/bin/env python
#
#
# EXAMPLE
# python util_NRNearestSimulationTo.py --approx SEOBNRv2 --nr-group Sequence-RIT-Generic --verbose --srate 4096 --fname overlap-grid.xml.gz --force-aligned-interpret
# python util_NRNearestSimulationTo.py --fname-fisher fisher_gamma.dat --fname overlap-grid.xml.gz --npts 3 ... |
def get_book_by_osis_id(id):
"""
Retrieves book meta data
:param id: the osis book id
:return:
"""
sort = find_key(id, osis_ids)
return get_book_by_sort(sort)
def get_book_by_sort(sort):
"""
Retrieves book metadata
:param sort: the sort order of the book to look up
:return:
... |
"""
Copyright (c) 2013 <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, modify, merge, publish, distribute, sublice... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as modelzoo
from torch.nn import BatchNorm2d
resnet18_url = 'https://download.pytorch.org/models/resnet18-5c106cde.pth'
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Con... |
import pandas as pd
from datetime import datetime
import plotly.graph_objs as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
##### Layouts for Tab 1 #####
# Dropdown list for single stock choice
def get_tab1_info_box():
return html.Div([
html... |
import turicreate.aggregate as agg
from turicreate import SFrame
from subs2network.consts import IMDB_RATING_URL, OUTPUT_PATH, IMDB_CREW_URL, IMDB_TITLES_URL, IMDB_PRINCIPALS_URL, \
DATA_PATH, IMDB_NAMES_URL
from subs2network.utils import download_file
def get_gender(profession):
if "actor" in profession:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Tuesday - September 08 2020, 18:25:36
@author: <NAME>, University of Glasgow
Script to create data augmentation for the BIDS folder.
The variables 'T1_identif' and 'GT_identif' are the volumes augmented.
The code checks if the volumes has been augmented al... |
from itertools import permutations
from cons import cons
from pytest import raises
from unification import reify, unify, var
from unification.core import _reify, stream_eval
from kanren import conde, eq, run
from kanren.constraints import (
ConstrainedState,
ConstrainedVar,
DisequalityStore,
isinstanc... |
from deap import base
from deap import creator
from deap import tools
import random
import numpy
import matplotlib.pyplot as plt
import seaborn as sns
import elitism
from static_pipelay import static_pipe_lay
# thetaPT = 0...5 # Angle of inclination of firing line from horizontal, [deg]
# LFL = 80...150 # Length... |
import os
import gi
import numpy
from enum import Enum
gi.require_version('WebKit2', '4.0')
from gi.repository import GObject, WebKit2, Gtk, Gdk
from mxdc import Registry, IBeamline, Object, Property
from mxdc.conf import settings
from mxdc.utils import colors, misc
from mxdc.utils.gui import ColumnSpec, TreeManager... |
"""
MIT License
Copyright (c) 2018 <NAME> and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge... |
import json
import yaml
from airone.lib.acl import ACLType
from airone.lib.http import render
from airone.lib.http import http_get, http_post
from airone.lib.http import http_file_upload
from airone.lib.http import HttpResponseSeeOther
from airone.lib.log import Logger
from django.core.paginator import Paginator, Pag... |
import base64
from mognet.exceptions.result_exceptions import ResultFailed, ResultNotReady, Revoked
import pickle
import importlib
import traceback
import logging
from typing import (
Any,
AsyncGenerator,
Dict,
Optional,
TYPE_CHECKING,
)
from .result_state import (
ERROR_STATES,
READY_STATES... |
"""Measurements collection."""
from datetime import date, datetime, timedelta, timezone
from decimal import ROUND_HALF_UP, Decimal
from typing import Dict, List, Literal, Optional, cast
import pymongo
from pymongo.database import Database
from model.queries import get_attribute_type, get_measured_attribute
from serv... |
"""
Read in the MCU file header, extract relevant constants,
and create modmcuconst.c.
This is not part of the automatic build process because MCU header file isn't
expected to change. After generating the file, some manual intervention is
needed to copy the new qstr definitions to qstrdefsport.h.
"""
from __future_... |
from flask import Flask, render_template, request, redirect, url_for
from math import ceil
from db import *
from tablegen import *
from editbase import *
from olad import *
app = Flask(__name__)
is_edit = False
is_new = False
is_editing = False
qcount = 1
edit_rows = []
cmp_queries = []
hiding_cells = []
hiding_... |
#!/usr/bin/env python
from os.path import expandvars
from icecube import icetray, dataclasses, phys_services
from I3Tray import I3Units
import math
@icetray.traysegment
def GenerateNeutrinos(tray, name,
RandomService=None,
RunID=None,
NumEvents=100,
SimMode='Full',
... |
# distributed training on single node
import os
import time
import argparse
import datetime
import torch
import torch.nn as nn
from torch import device, optim
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
import torchv... |
from os import makedirs
from datetime import datetime
from typing import List, Callable, Tuple
from abc import ABC, abstractmethod
import numpy as np
class FitnessFncBase(ABC):
@abstractmethod
def __call__(self, genes: np.ndarray, objectives: np.ndarray) -> np.ndarray:
raise NotImplementedError
cla... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST, CIFAR10
from torchvision.transforms import Compose, ToTensor, Normalize
from torchvision import transforms
from tensorboardX import SummaryWrit... |
"""a vary mary Xmas
<NAME> are some proliminary extensions for Xmas
"""
import typing
from os.path import dirname, realpath, join
from tkinter import PhotoImage
from tkinter import Canvas as tkCanvas
from time import sleep
from random import randint, choice, random, gauss
from functools import partial
... |
import os
import plotly.graph_objs as go
from plotly.offline import plot
import random
from pandas.core.series import Series
from pandas.core.frame import DataFrame
from pandas import to_datetime, Timestamp
from datetime import datetime
import pytz
"""
This file contains all the tools used for plotting data.
I... |
'''
Cross-compare blobs with incremental adjacency, within a frame
'''
from class_cluster import ClusterStructure, NoneType
import numpy as np
import cv2
class CderBlob(ClusterStructure):
_blob = object
mB = int
dB = int
dI = int
mI = int
dA = int
mA = int
dG = int
mG = int
dM... |
"""While the various variable importance methods can, in general, for many
different situations, such as evaluating the model-agnostic presence of
information withing a dataset, the most typical application of the method is to
determine the importance of variables as evaluated by a particular model. The
tools provid... |
import pandas as pd
import os
import numpy as np
import json
import glob
import sys
import time
#from git import Repo
def find_range(x,a,b,option='within'):
"""
Find indices of data within or outside range [a,b]
Inputs:
-------
x - numpy.ndarray
Data to search
a - float or int
... |
import config as cfg
from PIL import Image
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import numpy as np
def add_image_new(x0, y0):
eps = 0.2
new_xy = []
for i in [-1.,0.,1.]:
for j in [-1.,0.,1.]:
if i != 0 or j != 0:
x = x0 + i + j*cfg... |
#!/usr/bin/env python
"""
Uses Gaussian Mixture Models to separate members of clusters from non members. A series of data reductions are conducted on the supplied dataset to prepare it for Gaussian Mixture Model processing. Subordinate functions take care of clean up operations.
"""
# imports
import matplotlib.pyplot... |
# File: geom_utils.py
# Date: 05-10-2019
# Author: <NAME>
#
# This module contains all function that perform geometric actions as
# traslation, rotation, etc.
#
"""
Module with utility function for manipulation points in various coordinate system and plot them.
"""
# General imports
from trace import logger
import num... |
#conding=utf-8
# @Time : 2020/6/3 15:14
# @Author: fufuyu
# @Email: <EMAIL>
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.parameter import Parameter
from .loss import normalize
class GeneralizedMeanPooling(nn.Module):
r"""Applies a 2D power-average adaptive pooling over an inp... |
# -*- coding: utf-8 -*-
"""Color handling module."""
from typing import Any, List, Tuple, Union, Optional, Sequence
import numpy as np
from pandas import Series, DataFrame, to_numeric
from scipy.stats import entropy
from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import is_categorical_dtype
f... |
import logging
from argparse import ArgumentParser
from collections import OrderedDict
import numpy as np
import pandas as pd
from ampligraph.datasets import load_wn18
from ampligraph.latent_features import ComplEx, HolE, TransE
from ampligraph.evaluation import evaluate_performance, mrr_score, hits_at_n_score
from amp... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
# Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import math
import string
from dataclasses import dataclass, field
from collections import OrderedDict
from typing import Optional
import torch
fro... |
from queue import Queue
from threading import Thread, Condition
import librosa
import numpy
class Sound(object):
""" Sound object which can be read chunk by chunk. """
def __init__(self, y, sr, chunk_size=1024):
"""
:param array y: numpy array representing the audio data
:param int sr... |
from operator import itemgetter
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponsePermanentRedirect, HttpResponse, \
HttpResponseRedirect
from django.shortcuts import get_object_or_404
from ... |
import os
import pytorch_lightning as pl
from dgl.nn.pytorch import GATConv
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor
from torch.nn import BCEWithLogitsLoss, ModuleList
from torch.nn.functional import elu
from torch.optim import Adam
from torchmetrics import F1
from p... |
#
# Copyright 2012 keyes.ie
#
# License: http://jkeyes.mit-license.org/
#
from unittest import TestCase
from nose.tools import raises
from amzlist import LinkedList
from amzlist import Node
class ListTest(TestCase):
""" Test the linked list """
def setUp(self):
self.linked_list = LinkedList()
d... |
'''
<NAME>, <NAME>, <NAME>, <NAME>
CIS 422
Simple Calendar Application
4/29/18
'''
from datetime import datetime,date,timedelta
from tkinter import messagebox
def get_weekdays(y,m,d):
'''(string, string, string) -> list
example:
>>> get_weekday('2018','4','24')
return['2018-4-2... |
"""
Serializer used by Tournesol's API
"""
from typing import Optional
from django.db import IntegrityError, transaction
from django.db.models import ObjectDoesNotExist, Q
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from r... |
"""Various utilities"""
from __future__ import annotations
import os
import pathlib
import re
import shutil
from datetime import datetime, timedelta
import geopandas as gpd
import geoutils as gu
import numpy as np
import pandas as pd
import xdem
def get_satellite_type(dem_path):
"""Parse the satellite type fro... |
# -*- coding: utf-8 -*-
import json
import logging
from collections import namedtuple
try:
from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError: # < Django 1.7
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import Conte... |
# All rights reserved; available under the terms of the BSD License.
"""
runas.sudo_win32: win32 platform-specific functionality for runas
This module implements the runas interface using ctypes bindings to the
native win32 API. In particular, it uses the "runas" verb technique to
launch a process with administrativ... |
#!/bin/python3.6
"""
Date Created: Feb 11 2020
This file will contain the training utils
"""
import os
import glob
import h5py
import torch
import configparser
import argparse
from datetime import datetime
import numpy as np
from models import *
import kaldi_python_io
from kaldiio import ReadHelper
from to... |
# Added recovery lap data - counter-steering angle 1.0
#import os
import csv
#import cv2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.models import Sequential
fro... |
import pathlib, sys
from collections import OrderedDict
import logging
from logging import FileHandler
import codecs
import time
import os
if sys.version > '3':
import configparser
else:
import ConfigParser as configparser
class MyConfigParser(configparser.ConfigParser):
"""
自定义 MyConfigParser,重写 op... |
import abc
import importlib
from typing import TypeVar, Generic, Union, Any, cast, Iterator, Type, Callable
from types import ModuleType
from pathlib import Path
import amino
from amino import boolean
from amino.func import I
from amino.tc.base import F
from amino.util.mod import unsafe_import_name
from amino.tc.monoi... |
import subprocess
import os.path
import getpass
GELINK=""
GETARBALL=""
STEAM_INSTALL_TYPE=""
GE_PATH=""
def SETUP_GE():
global GELINK
global GETARBALL
global GE_PATH
subprocess.call(["wget", GELINK])
subprocess.call(["tar", "-xvf", GETARBALL, "-C", GE_PATH])
subprocess.call(["rm", GETARBALL])... |
import logging
import re
from fnmatch import fnmatch
from collections import OrderedDict, namedtuple
from enum import Enum, auto
from functools import singledispatch
from typing import List
from meltano.core.behavior.visitor import visit_with
SelectPattern = namedtuple(
"SelectPattern", ("stream_pattern", "prope... |
#!/usr/bin/env python
"""
Usage:
preprocess.py [options] INPUT_FOLDER INPUT_FNAMES TARGET_FOLDER
Options:
-h --help Show this screen.
--max=<int> max dataset size [default: 10000]
--shard-size=<int> shard size [default: 5000]
--test-file=<file> test f... |
#!/usr/bin/env/python3
# -*- coding:utf-8 -*-
import networkx as nx
from collections import defaultdict, deque
from math import log
import numpy as np
import scipy.sparse as sp
from sklearn.base import BaseEstimator, TransformerMixin
from math import log
class SpreadingActivationTransformer(BaseEstimator, Transform... |
from pyracing.helpers import parse_encode
class SubSessionData:
def __init__(self, data):
self.cat_id = data['catid']
self.caution_laps = data['ncautionlaps']
self.caution_type = data['cautiontype']
self.cautions = data['ncautions']
self.corners_total = data['cornersperlap'... |
import sys, os
from pyprojroot import here
root = here(project_files=[".here"])
sys.path.append(str(here()))
from typing import Dict, Optional, Union, Any
from collections import namedtuple
import pathlib
import argparse
import pandas as pd
from tqdm import tqdm
import numpy as np
import time
import joblib
import xar... |
from components import SpriteSheetSequenceComponent
from components import RectangleColliderComponent
from components import ResetPositionComponent
from components import ObstacleTagComponent
from components import ScrollableComponent
from components import RenderableComponent
from components import TransformComponent
... |
import pygame
import sys
import time
# Imports from another module
from pygame.locals import *
from random import random
# Imports form another file
from colors import *
def main(default=False):
if not default:
place_random_tile()
print_matrix()
while True:
for event... |
from ValidateModel import *
import re
import os.path
import numpy as np
import shutil
import copy
BASE_FOLDER = "/Users/eahlb/coding/"
TABLE_FOLDER = "/Users/eahlb/Dropbox/KTH/SH204X/rapport/tables/"
# this folder is a remnant from my thesis
# use at own risk
class ErrorFinder:
def __init__(self, input_path, out... |
import grp
import os
import pwd
import shlex
import subprocess
from typing import Set, List
from helpers.ssh_key_object import SSHKeyObject
from helpers.gitlab_operations import GitlabGroupConfig
from helpers.config_operations import sanitize_sudoers_line, sanitize_username
__all__ = [
"UserOps",
"UOProtectedU... |
from functools import lru_cache
from math import sqrt
from time import time
@lru_cache()
def line_value(line):
"""Return the value associated with a line (series of # and . chars)"""
val = 0
for char in line:
val <<= 1
val += char == "#"
return val
@lru_cache()
def complement(value):
... |
#!/usr/bin/python3
def pc1(d):
"""Computes top principal component.
Parameters
------------
d: numpy.ndarray(shape=(n1,n2))
Returns
----------
numpy.ndarray(shape=(n2,))
"""
import numpy as np
from sklearn.decomposition import TruncatedSVD
# Normalize data
t1 = d.T
t1 = t1 - t1.mean(axis=0)
t1 = t1 /... |
# Copyright 2019 Mycroft AI 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 writin... |
"""
Distributed TensorFlow Training
-------------------------------
When you need to scale up model training using TensorFlow, you can use :py:class:`~tensorflow:tf.distribute.Strategy` to distribute your training across multiple devices.
There are various strategies available under this API and you can use any of the... |
# Python libraries
import json
import datetime
import re
import subprocess
# For accessing Excel files.
import pylightxl
# Add logging support
import logging
# We read config from `.env`.
import os
from dotenv import dotenv_values
config = {
**dotenv_values(".env.default"), # default configuration
**dotenv_v... |
import re
from datetime import date, timedelta
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from anilist_api.anilist import populate_series_item
from showings.models import Show
# Series model to describe ... |
# Copyright 2021 The Trieste Contributors
#
# 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... |
# ====================================================================
# 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 re... |
import numpy as np
from numpy import nanmin, nanmax
class DataHandler(object):
"""
The purpose of the DataHandler class is to generate normalized (transformed)
arrays of the input data. The input data is either two-dimensional
(comprising arrays x and y) or three-dimensional (comprising arrays x, y
... |
import io
import re
SUBSECTION_RE = re.compile(br'(.+)\s+\d+\Z') # [ITEM TYPE] [COUNT]EOL
ITEM_RE = re.compile(br'(\d+):') # [IDX]: ...
CMP_RE = re.compile(br'(\d+):\s+(\S+)') # [IDX]: [FILENAME]
# [IDX]: [FILENAME] 1 1
MATERIAL_RE = re.compile(
br'(\d+):\s+(\S+)\s+(-?\d*(\.\d+)?)\s+(-?\d*(\.\d+)?)')
POSXYZ_RE ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
def binf2dec(binArr):
if (type(binArr) is not np.ndarray ):
raise RuntimeError("Invalid type.")
isNegative = False
finalNumber = 0
# 16 bits
# 16 bit: bias = 15 ( 2^(5-1) - 1 = 15)
expSize = 5
mantSize = 10
... |
import os
import random
import numpy as np
from tqdm import tqdm
from PIL import Image, ImageDraw
from east import cfg
from east.utils import reorder_vertexes, shrink, point_inside_of_quad, point_inside_of_nth_quad
data_dir = cfg.data_dir
origin_img_dir = os.path.join(data_dir, cfg.origin_img_dir_name)
origin_txt_d... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from rnn_encoder import RNNEncoder
'''
batch_first = False
LSTM输入: input, (h_0, c_0)
- input (seq_len, batch, input_size): 包含输入序列特征的Tensor。也可以是packed variable ,详见 [pack_padded_sequence](#torch.nn.utils.lstm.pack_padded_sequence(in... |
"""
Base class for instrument objects.
"""
import os
from dataclasses import dataclass
import numpy as np
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter
import astropy.units as u
from astropy.coordinates import SkyCoord
from sunpy.util.metadata import MetaDict
from sunpy.coordinates.f... |
# global imports
import unittest
import numpy as np
import numpy.testing as nptest
import scipy.integrate as scint
# local imports
from .. import helper as bhlp
from .. import network as bnet
from .. import meanfield as bmf
from .. import unitginzburgmeanfield as ugbmf
np.random.seed(123456)
class MeanfieldTestCase... |
#! /usr/bin/env python3
from construct import *
import codecs
import datetime
import gar
import sys
def trace(x):
print(x)
return x
class CustomFloat16(Adapter):
def __init__(self, units, *args, **kwargs):
self.units = units
f = ByteSwapped(Bitwise(Struct(
'exponent' / Bit... |
import torch
import torch.nn as nn
import torch.optim as optim
from PIL import Image
from torchvision import transforms
import pytorch_lightning as pl
from torchvision import models
def set_parameter_requires_grad(model, feature_extracting):
"""
Freezes all layers if we need just to extract features
Arg... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import defaultdict
from django.db.models import Count
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from django.utils.translation import gettext_lazy as __
from django.db import models
from django.shortcuts import reverse
... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
from __future__ import print_function
import numpy as np
import os
from cntk import... |
import sys
import random
import numpy as np
from cv2 import cv2
from env.env_utils import Statistic
from env.rxr_env_base import RxREnvBase
class RxREnv(RxREnvBase):
def __init__(
self,
config: dict,
scan_ids: list = []
) -> None:
super().__init__(config, scan_ids)
# en... |
#! /usr/bin/python3
from PIL import Image
from math import *
from numpy import cross, dot
from constants import *
from random import random
#rotation = 0 # Global rotation adjust in degrees (so this property can be animated)
def f():
pass
def normalize(v):
magnitude = sqrt(sum(n**2 for n in v))
return [n ... |
import asyncio
import pathlib
import ssl
import websockets
import os
import time
import sys
import re
import traceback
import wave
import helper as helper
from google.cloud import speech_v1p1beta1 as speech
from six.moves import queue
from audio_stream import ResumableMediaStream
from config import cfg
from concurren... |
#!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2016-2019 Illumina, Inc.
# 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/LIC... |
import numpy as np
import sys
import os
import time
from sklearn.externals import joblib
from pc_toolbox.model_slda.slda_estimator__w_given_pi import (
estimate_w_CK__given_pi_DK)
from pc_toolbox.model_slda.slda_utils__dataset_manager import (
load_dataset,
)
from pc_toolbox.utils_io import (
pprint,
... |
"""
Python reference implementation of the
sequence transducer.
Author: <NAME>
Based on the papers:
- "Sequence Transduction with Recurrent Neural Networks"
Graves, 2012
https://arxiv.org/abs/1211.3711
- "Speech Recognition with Deep Recurrent Neural Networks"
Graves, et al., 2013
https://arxiv.org... |
import os
import glob
import hashlib
import json
import time
import sys
import argparse
import xml.etree.ElementTree as ET
class RomIgnoredError(RuntimeError):
pass
class Rom(object):
def __init__(self, system_dir, rom_name):
rom_base_name = os.path.splitext(rom_name)[0]
rom_dir = os.path.join... |
import os
from math import pi
from typing import Tuple
import click
import jax
import jax.numpy as jnp
from jax import random
from scipy.optimize import minimize_scalar
from diffbank.bank import Bank
from diffbank.constants import MSUN, C, G
from diffbank.utils import Array, PRNGKeyArray
from diffbank.waveforms.taylo... |
# Copyright (c) 2019 Graphcore Ltd. All rights reserved.
import popart
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import numpy.random as npr
import sys
from pathlib import Path
sys.path... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module for scraping meneame stories
"""
from model import Story, Comment
import requests
import logging
import feedparser
from bs4 import BeautifulSoup
import re
import os
class ScraperFactory(object):
"""
ScraperFactory: returns a Scraper implementation.
... |
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_array_equal
from cforest.tree import _compute_global_loss
from cforest.tree import _compute_valid_splitting_indices
from cforest.tree import _find_optimal_split
from cforest.tree import _find_optimal_split_inner_loop
from cforest.tre... |
from Utilitis import overlay_dicom_map, load_nii, save_nii, resize_mask_array
import numpy as np
from scipy.optimize import curve_fit
from abc import ABC, abstractmethod
import csv, os
import glob
from multiprocessing import Pool, cpu_count
import scipy.io as sio
import pandas as pd
class AbstractFitting(ABC):
""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.