text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
"""
Estimates the static background in a STORM movie.
The estimate is performed by averaging this might
not be the best choice for movies with a high density
of real localizations.
This may be a good choice if you have a largish
fixed background and a relatively low density of
real localizations... |
#!/usr/bin/env python
# Copyright (C) 2016 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:n
#
# 1. Redistributions of source code must retain the above copyright
# notice, this li... |
#!/usr/bin/env python3
# coding: utf-8
def position(T, s):
"""renvoie la position de la chaine s dans la liste T
Si s n'appartient pas à la liste T, la fonction renvoie -1 à la place.
T: liste de chaine de caractères
s: chaine de caractère
résultat: nombre entier
"""
try:
return T... |
from __future__ import print_function, division
from PIL import Image
from torchvision.transforms import ToTensor, ToPILImage, Compose, Normalize
import numpy as np
import random
import tarfile
import io
import os
import pandas as pd
import torch
from torch.utils.data import Dataset
# %% custom dataset
class Places... |
"""
某些网络数据在一定周期内不会发生变化。如股票代码列表。如果在
同一个会话中,使用funtools的cache机制,可以避免多次下载同
一数据。但计划任务程序中,由于每次运行会话不同,如果需要使
用网络数据,就需要多次从网络下载。数据代理类使用本地文件持
久化存储,在特点时点自动更新,确保数据时效性,同时减少网络
下载,提高运行效率。
数据代理主要用于计划任务程序。适用于每天变动,但在24小时内,
数据一直为静态的网络数据采集。如股票列表等。
也可用于频繁访问,但单次查询需要较长时间的数据提取。
读取代理数据,直接使用类的`read`方法,少数需要进一步转换。
好处:
1、避免当天重复下载同一网络数据
... |
#!flask/bin/python
import os, pymongo
import models
from flask import Flask, jsonify, abort, request, make_response, url_for
app = Flask(__name__)
# Error Handler for 400: Bad Request
@app.errorhandler(400)
def not_found(error):
return make_response(jsonify( { 'error': 'Bad request' } ), 400)
# E... |
import os
import requests
import yaml
import re
import html
from dotenv import load_dotenv
from typing import List
# define config object
config = {
"api_key": "",
"api_url": "",
"output_dir": "",
"save_html": False,
"docs": [],
"increase_heading_levels": 1,
}
# load config from file
with open... |
#!/usr/bin/env python
# coding: utf-8
"""
run consensus analysis to identify overall pattern
analysis method developed by <NAME> and <NAME>
"""
import os
import sys
import glob
import numpy
import nibabel
import nilearn.plotting
import nilearn.input_data
import matplotlib.pyplot as plt
from statsmodels.stats.multites... |
import urllib.parse
from wikked.db.base import NoWantedPages
from wikked.page import WantedPage
from wikked.utils import get_absolute_url
from wikked.webimpl import (
get_page_meta, get_page_or_raise, make_page_title,
is_page_readable, get_redirect_target,
get_or_build_pagelist, get_generic_page... |
from datetime import datetime
import os
from os.path import join
import pandas as pd
from pathlib import Path
import pickle
import spacy
import sys
import torch
from torch import optim
from torch.nn import Embedding, LSTM
from torch.nn.functional import mse_loss
from torch.utils.data import TensorDataset
from torch.uti... |
# Copyright 2020 Adap GmbH. 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 applicable law or ag... |
import random
class Thing:
"""
This represents any physical object that can appear in an Environment.
"""
def is_alive(self):
"""Things that are 'alive' should return true."""
return hasattr(self, 'alive') and self.alive
def show_state(self):
"""Display the agent's int... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.core import validators
from django.db import models
from django.db.models import fields as django_fields
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django... |
import os, sys
import logging
import weakref
import pygame
from .resourceLoaders import *
class ResourceError(Exception):
pass
_GAME_PATH=calculate_real_path(os.path.dirname(sys.argv[0]))
def _BuildLogger():
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
log_format = logging.F... |
"""ResNets.
With only TensorFlow backend.
Follows fchollet's design
Author: <NAME>
Email : <EMAIL>
"""
from __future__ import print_function, absolute_import
from builtins import range
from spiker import log
logger = log.get_logger("models-resnet", log.DEBUG)
try:
from keras.layers import Input
from keras... |
import logging
import re
import gzip
from pathlib import Path
from argparse import ArgumentParser
from Bio import AlignIO
from make_prg.from_msa import MSA
from make_prg.prg_encoder import PrgEncoder, PRG_Ints
def load_alignment_file(msa_file: str, alignment_format: str) -> MSA:
msa_file = str(msa_file)
log... |
""" This script is the scraping controller """
# Standard library imports
from datetime import date
import logging
from typing import List, Dict, Sequence, Type, Tuple, Union
# Third party imports
import click
from sqlalchemy.engine.base import Connection
# Local imports
from naccbis.Scraping import (
BaseScraper... |
import numpy as np
from pyNN.random import NumpyRNG
from sklearn.linear_model import LinearRegression
import math
def gaussian_convolution(spikes,dt):
#---- takes a spiketrain and the simulation time constant
# and computes the smoothed spike rate
#-----works only after the simulation has run; not onli... |
import tensorflow as tf
import os
#LABEL_PATH = "/home/neo/projects/deepLearning/data/labelTest/"
#IMAGE_PATH = "/home/neo/projects/deepLearning/data/imageTest/"
LABEL_PATH = "/home/neo/projects/deepLearning/data/label/"
IMAGE_PATH = "/home/neo/projects/deepLearning/data/image/"
LABEL_SUFIX = "_emotion"
LABEL_FORMAT =... |
import pandas as pd
import os
import random
class MetaData:
def __init__(self, db):
self.db = db
self.ljs_path = '/data2/sungjaecho/data_tts/LJSpeech-1.1'
self.emovdb_path = '/data2/sungjaecho/data_tts/EmoV-DB/EmoV-DB'
self.metadata_path = 'metadata'
self.df = None... |
import math
import collections
import intergalactic
'''
gas_H = diffuse gas in the galactic Halo
gas_D = diffuse gas in the galactic Disc
cloud_H = molecular gas in the halo
cloud_D = molecular gas in the disc
f = infall rate
Stars are divided in two groups:
1) Low/intermediate mass stars (m <= 4 Msun... |
import librosa
from numba import jit
import numpy as np
@jit(nopython=True, cache=True)
def __C_to_DE(C: np.ndarray = None,
dn: np.ndarray = np.array([1, 1, 0], np.int64),
dm: np.ndarray = np.array([1, 0, 1], np.int64),
dw: np.ndarray = np.array([1.0, 1.0, 1.0], np.float64),
... |
#
# Copyright 2021 <NAME>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish... |
__all__ = [
'PyForwardRef',
'PyLiteral',
'PyProtocol',
'PyDeque',
'PyTypedDict',
'PyTypedDicts',
'FrozenKeys',
'DefFactory',
'NoneType',
'ExplicitNullType',
'ExplicitNull',
'JSONList',
'JSONObject',
'ListOfJSONObject',
'JSONValue',
'Encoder',
'Decoder'... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017-2018 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
# Copyright (c) 2009 The Foundry Visionmongers Ltd. All Rights Reserved.
import nuke
import nukescripts
import random
import os
import textwrap
def copy_knobs(args):
thisGroup = nuke.thisGroup()
if( thisGroup is not nuke.root() and ( thisGroup.locked() or thisGroup.subgraphLocked() ) ):
raise RuntimeError(... |
# -*- coding: utf-8 -*-
from flask import Flask
from flask import render_template
from flask import request
from flask import make_response
import pandas as pd
import numpy as np
import csv
import io
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
DATA = pd.read_csv("Exp... |
import tclab
import time
import numpy as np
import sys
import first_principles_model as fp
def doublet_test(data_file='step_test.csv', show_plot=True):
'''doublet test the system and save data to given file path'''
import Adafruit_DHT # Only importable on the Pi itself
tc1 = tclab.TCLab()
tc1.LED(100... |
import face_recognition
import cv2
import numpy as np
# getMouthImage (from TLR Teeth Appearance Calculation.ipynb)
def getMouthImage(faceImage,margin=0):
# face_locations = face_recognition.face_locations(faceImage)
face_landmarks_list = face_recognition.face_landmarks(faceImage)
if len(face_landmarks_list) == ... |
import traceback
import copy
from cloud_console_common.utils import *
from cloud_console_common import log
class ExtractLogic:
"""Implementation of ExtractLogic that will extract the data from a remote API call
"""
def __init__(self):
pass
def extract(self, raw_data)->dict:
"""Receiv... |
#%%
#==============================================================================#
# #
# Title: Make PostCodes Dataset #
# Purpose: To download and process the data for the App ... |
import numpy as np
import pandas as pd
import datetime as dt
import operator
import time
import os
def most_common_day(dataframe):
start = time.time()
most_common_day_dict = dataframe['Day of the Week'].value_counts().to_dict()
popular_day_of_the_week = max(most_common_day_dict.items() , key=operator.item... |
# coding=utf8
"""
@author: <NAME>
@date: 09/26/2019
@code description: It is a Python3 file to implement cosine similarity with TF-IDF and Word Embedding methods.
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise im... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import Imputer, LabelBinarizer, StandardScaler
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.model_selection import StratifiedShuffleSplit, GridSearchCV, train_test_split, c... |
# Copyright (c) 2011, <NAME> [see LICENSE.txt]
# This software is funded in part by NIH Grant P20 RR016454.
import unittest
import warnings
import os
import math
from random import shuffle, random
from collections import Counter,OrderedDict
from dictset import DictSet,_rep_generator
from math import isnan, isinf, fl... |
import pdb
import os
import torch
import tqdm
import argparse
import sys
sys.path.append('../utils/')
sys.path.append('../models/')
from torch.utils.data import DataLoader
from distances.euclidean import euclidean_distance
from distances.mahalanobis import mahalanobis_distance
from distances.kullback_leibler import k... |
from typing import Optional, List
from thinc.types import Floats2d
from thinc.api import Model, with_cpu
from spacy.attrs import ID, ORTH, PREFIX, SUFFIX, SHAPE, LOWER
from spacy.util import registry
from spacy.tokens import Doc
# TODO: replace with registered layer after spacy v3.0.7
from spacy.ml import extract_ngra... |
from collections import defaultdict
import itertools
from skorch.net import NeuralNet
from skorch.dataset import Dataset
import pandas as pd
from sklearn import preprocessing
from tqdm import tqdm
import more_itertools as mit
import numpy as np
import skorch
import torch
import logging
logging.getLogger('matplotlib').... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Hillas shower parametrization.
TODO:
-----
- Should have a separate function or option to compute 3rd order
moments + asymmetry (which are not always needed)
- remove alpha calculation (which is only about (0,0), and make a get
alpha function tha... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File: software/utils/loop.py
# By: <NAME>
# For: Myself
# Description: This file implements the main loop for object detection with OpenCV.
IS_ARDUCAM = False
if IS_ARDUCAM:
from utils_arducam import ArducamUtils
from utils.inference impor... |
#!/usr/bin/env python3
import argparse
import configparser
import getpass
import logging
import os
import requests
import requests_toolbelt
import sys
import urllib3
from scapy.all import *
import ipaddress
import json
from scapy.layers.http import HTTPRequest # import HTTP packet
from scapy.layers.http import HTTP
CU... |
"""
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wit... |
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... |
# coding=utf-8
# Copyright 2017 The Tensor2Tensor 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... |
import os
import numpy as np
import tensorflow as tf
import math
from PIL import Image
#import pdb
F = tf.app.flags.FLAGS
"""
Save tensorflow model
Parameters:
* checkpoint_dir - name of the directory where model is to be saved
* sess - current tensorflow session
* saver - tensorflow saver
"""
def save_model(checkpo... |
#!/usr/bin/env python
"""
mbed
Copyright (c) 2017-2017 ARM Limited
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 boto3
#import botocore
import sys
import os
import shutil
import json
import pickle
import lmdb
import subprocess
import argparse
import time
import datetime
import S3
import concurrent.futures
import requests
import subprocess
import pymongo
map_size = 100 * 1024 * 1024 * 1024
# default endpoint
endpoint_pd... |
# included from libs/combination.py
"""
Combination
Not fastest but PyPy compatible version
"""
MOD = 998_244_353
K = 301
def makeInverseTable(K=K, MOD=MOD):
"""calc i^-1 for i in [1, K] mod MOD. MOD should be prime
>>> invs = makeInverseTable(10)
>>> [i * invs[i] % MOD for i in range(1, 10)]
[1, 1, ... |
#Copyright (C) 2011 by <NAME> and <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, dist... |
import sys
sys.path.append('..')
import torch as th
import torch.nn as nn
import geoopt as gt
from util.hyperop import *
class hyperRNN(nn.Module):
def __init__(self, input_size, hidden_size, d_ball, default_dtype=th.float64):
super(hyperRNN, self).__init__()
self.input_size = inp... |
from math import ceil
import warnings
from collections import namedtuple
import numpy as np
from .basis import conv_basis, delta_stim, boxcar_stim, make_nonlinear_raised_cosine
__all__ = ['Design', 'Covariate']
class Design:
covariates = {}
bias = False
def __init__(self, experiment):
self.exp... |
# --------------------------------------------------------------------#
# --------------------------------------------------------------------#
# ---------- Made by <NAME> @ircam on 11/2015
# ---------- Analyse audio and return soudn features
# ---------- to us this don't forget to include these lines before your scrip... |
#!/usr/bin/env python3
import argparse
import sys, os
import subprocess
from collections import defaultdict
import logging
import re
import math
sys.path.insert(0, os.path.sep.join([os.path.dirname(os.path.realpath(__file__)), "../PyLib"]))
import ctat_util
logging.basicConfig(stream=sys.stderr, level=logging.INFO... |
# coding: utf-8 -*-
'''
GFS.py contains utility functions for GFS
'''
__all__ = ['get_akbk',
'get_pcoord',
'read_atcf']
import numpy as _np
import pandas as _pd
def get_akbk():
'''
Returns ak,bk for 64 level GFS model
vcoord is obtained from global_fcst.fd/gfsio_module.f
ak,bk ... |
import datetime as dt
from functools import singledispatch
__holidays = {}
__cache = set()
__min_year = None
__max_year = None
class _Holiday(object):
'''Container for public holiday meta information.
Most holidays recur on the same day every year so these
only require the month and day. Once-off holid... |
'''
* @author <NAME>
* @email <EMAIL>
* @create date 01-01-2022 17:03:09
* @modify date 01-01-2022 17:03:09
* @desc This code generates a dataset containing data of chess games played on lichess.org
'''
import pandas as pd
import time
from pandas.core.frame import DataFrame
import constants as C
import json
impo... |
"""Main module."""
import warnings
import os
import sys
import re
from six.moves import input
from activelearner import dataset, models, strategies, labeler, utils
# Define active learning labeling modes
def interactive_mode(data, keywords, querier, oracle, save_every,
path, file_name, print_p... |
import argparse
import os
import importlib
import tensorflow as tf
from modules.compound_model import CompoundModel
from modules.regressor_trainer import train_regressor
from modules.compound_model_trainer import train_compound_model
from modules.training_helper import evaluate_regression_MSE, get_tensorflow_d... |
# This file is mainly derived from https://github.com/openai/baselines.
from collections import deque
import os.path as osp
import time
import csv
import json
from gym.core import Wrapper
import numpy as np
from .vec_env import VecEnvWrapper
class Monitor(Wrapper):
EXT = "monitor.csv"
f = None
def __in... |
import math, pygame
from pygame.locals import *
#############################################
## Standard colors (RGB)
BLACK = (20, 20, 40)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
#############################################
## Customize plot here
def function_to_print(x):
... |
from rest_framework import serializers
from .hz_to_note import convert_to_notes
from .models import Voice, File, Song, Genre, Singer
"""
### Saving serializer (Create & Update)
# .save() will create a new instance.
serializer = CommentSerializer(data=tata)
# .save() will update the existing `comment` instance.
seria... |
# Copyright (c) 2015 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# 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... |
"""
Defines a set of document formats.
(c) 2015 Massachusetts Institute of Technology
"""
# Native
import datetime
import hashlib
import os
# LO-PHI Automation
import lophi_automation.database.utils as utils
DELIMITER = '_'
def analysis_doc_uid(analyzer_name, analyzer_version, sample_uid):
"""
Ret... |
# Member.py
import discord
from discord.ext import commands
from discord.utils import get
import os
import mysql.connector
import isbnlib
from isbnlib import *
import asyncio
ROLE = "Book Worm"
def initdb():
return mysql.connector.connect(
host = os.getenv('HOST'),
user = os.geten... |
#!/usr/bin/env python3
import hashlib
import re
import requests
import sys
from pprint import pprint as pp
from .exceptions import PCloudException
from .connection import AbstractPCloudConnection
from .pcloudbin import PCloudBinaryConnection
PCLOUD_SERVER_SUFFIX = '.pcloud.com' # only allow downloads from pcloud s... |
#%% Setup
from matplotlib import rc
rc("font", **{"family": "serif", "serif": ["Computer Modern Roman"], "size": 20})
rc("text", usetex=True)
import os
import numpy as np
import mpmath as mp
import matplotlib.pyplot as plt
from scipy.special import lambertw
from scipy import optimize
# path = os.path.expanduser(
# ... |
# ====================================
# > Messaging and reporting utilities
# =================================
import textwrap
from collections import Counter
from datetime import datetime
from typing import Sequence, Tuple, cast
import rich
from rich.markup import escape
from rich.panel import Panel
from rich.prog... |
# -----------------------------------------------------------------------------
# Copyright * 2014, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache
#... |
from asyncio import FastChildWatcher
import os
from unicodedata import category
from flask import request, current_app, url_for
from flask_restful import Resource
from datetime import datetime
from flask_jwt_extended import (
jwt_required, current_user
)
from werkzeug.utils import secure_filename
from sqlalchemy.or... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Functions that handle saving and loading of checkpoints."""
import os
import pickle
from collections import OrderedDict
import torch
from fvcore.common.file_io import PathManager
import net.utils.logging_tool as loggin... |
from typing import Tuple
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
def label_encoder(c: str) -> np.ndarray:
lc = LabelEncoder()
return lc.fit_transform(c)
def load_dataset() -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
path = "../../input/tabular-playg... |
import sys
from collections import namedtuple, defaultdict
import concrete
from concrete.util import CommunicationReader
import numpy as np
import json
Mention = namedtuple("Mention", "text start end sentence entityType confidence uuid")
def get_entities(comm, entity_tool):
"""
Returns:
list of concrete.Entity o... |
#! /usr/bin/env python3
"""A module which provides a unified CLI to all the functionality.
This module serves as a single entry point for a user. It exposes a CLI
which can be use to call the different commands and set their properties.
This CLI replaces `__main__.py` files scattered around the project with
a single,... |
"""
Generate all synonymous mutants for a input protein
<NAME>
"""
# Ensure Python 2/3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import itertools
import argparse
import sys
from signal import signa... |
import logging
from vespid import setup_logger
logger = setup_logger(__name__)
import pandas as pd
import numpy as np
from tqdm import tqdm
def calculate_interdisciplinarity_score(
membership_vectors
):
'''
Given a set of entities and
one vector for each representing the (ordered) strength
of memb... |
"""
Cadquery Extensions
name: extensions.py
by: Gumyr
date: August 2nd 2021
desc:
This python module provides extensions to the native cadquery code base.
Hopefully future generations of cadquery will incorporate this or similar
functionality.
license:
Copyright 2021 Gumyr
Licensed under the... |
#!/usr/bin/env python3
from collections import namedtuple, defaultdict
from os.path import join as join_path, dirname, abspath
from copy import deepcopy
from pegparse import create_parser_from_file, ASTWalker
EBNF_FILE = join_path(dirname(abspath(__file__)), 'c-like.ebnf')
CodeBlock = namedtuple('CodeBlock', ['entr... |
#!/usr/bin/env python3
import os
import ctypes
import platform
import logging
logger = logging.getLogger(__name__)
def load_dll():
dl_path_env = os.getenv("CENTAURUS_DL_PATH", "")
if platform.uname()[0] == "Windows":
dl_path = os.path.join(dl_path_env, "libpycentaurus.dll")
elif platform.uname()[... |
from __future__ import print_function
import os
import time
import torch
import torchvision.transforms as transforms
from Dataset import DeblurDataset
from torch.utils.data import DataLoader
from utils import *
from network import *
from Dataset import DeblurDataset, RealImage
def test(args):
device = torch.devi... |
"""
Some meta networks
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from utils.quantize import Function_STE, Function_BWN
from utils.miscellaneous import progress_bar
from utils.quantize import quantized_CNN, quantized_Linear
import utils.global_var as gVar
meta_count = 0
class... |
"""A text format for Bril.
This module defines both a parser and a pretty-printer for a
human-editable representation of Bril programs. There are two commands:
`bril2txt`, which takes a Bril program in its (canonical) JSON format and
pretty-prints it in the text format, and `bril2json`, which parses the
format a... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
"""
import pytest
import os
import tarfile
from pathlib import Path
import nibabel as nib
import numpy as np
from ....tests.resource import setup as setuptestresources
from .... |
import unittest
from fastNLP import Vocabulary
from fastNLP.embeddings import BertEmbedding, BertWordPieceEncoder
import torch
import os
from fastNLP import DataSet
@unittest.skipIf('TRAVIS' in os.environ, "Skip in travis")
class TestDownload(unittest.TestCase):
def test_download(self):
# import os
... |
import logging
import os
import numpy as np
import torch
if torch.cuda.is_available():
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
device = torch.device('cuda')
else:
device = torch.device('cpu')
def _patch_noise_extend_to_i... |
from absl import app, flags, logging
from absl.flags import FLAGS
import tensorflow as tf
import numpy as np
import cv2
from tensorflow.keras.callbacks import (
ReduceLROnPlateau,
EarlyStopping,
ModelCheckpoint,
TensorBoard
)
from yolov3_tf2.models import (
YoloV3, YoloV3Tiny, YoloLoss... |
from torchfes.opt.utils.generalize import generalize
from typing import Dict
import torch
from torch import Tensor, nn
from .. import properties as p
from .utils import (
Lagrangian, set_directional_hessian, set_directional_gradient)
from ..utils import detach
# Line search Newtons method is below
# gp := g(x + a ... |
from typing import Optional
from cumulusci.core.utils import process_list_arg, process_bool_arg
from cumulusci.tasks.metadata_etl import MetadataSingleEntityTransformTask
from cumulusci.utils.xml.metadata_tree import MetadataElement
class AddRelatedLists(MetadataSingleEntityTransformTask):
entity = "Layout"
t... |
import platform
import sys
from datetime import datetime, timedelta
from functools import partial
from types import ModuleType
import pytest
import pytz
from apscheduler.util import (
datetime_ceil, get_callable_name, obj_to_ref, ref_to_obj, maybe_ref, check_callable_args)
class DummyClass(object):
def meth... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
class VideoInputStreamIterator:
"""
iterator through the read video
"""
def __init__(self, input_stream):
self._stream = input_stream
def __next__(self):
return self._stream.grab_frame()
class VideoInputStream:
"""
... |
import random
import pygame
class GameObject(pygame.sprite.Sprite):
'''
All sprites should inherit from this class.
'''
def __init__(self, game, name):
'''
Sets the sprite image and rect Surface.
'''
# Call the parent class (Sprite) constructor
pygame.sprite.Spr... |
# Copyright (c) 2021, Hitachi America Ltd. 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... |
import logging
import os
import tempfile
import warnings
from configparser import ConfigParser
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence, Type, Union
from articat.utils.class_or_instance_method import class_or_instance_method
logger = logging.get... |
import cv2
import time
import os
import matplotlib.pyplot as plt
import torch
from torch import nn
import torchvision.models as models
import torchvision.transforms as transforms
import numpy as np
savepath='./color_heatmap'
if not os.path.exists(savepath):
os.mkdir(savepath)
def draw_features(width, height, x, ... |
import logging
class GpioException(Exception):
def __init__(self,errors):
self.errors = errors
def toString(self):
return ' '.join(self.errors) # str(self.errors).replace('\'','').replace('[','').replace(']','')
class GpioDummy(object):
def __init__(self):
self.args = {'mode':'BCM'... |
# -*- coding: utf-8 -*-
import numpy as np
import scipy.io as sio
import glob
import os
import torch
import torch.utils.data
import torchvision.transforms.functional
import cv2
def read_dataset(path):
"""
Read training dataset or validation dataset.
:param path: The path of dataset.
:return: The list of filenames... |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @author: Drizzle_Zhang
# @file: cufflinks.py
# @time: 2018/10/24 20:14
from time import time
from argparse import ArgumentParser
import os
import subprocess
def cufflinks(bam_path, cufflinks_out, process=3, thread=10):
# read samples from results of ... |
import gem
from abc import ABCMeta, abstractmethod
try:
from firedrake_citations import Citations
Citations().add("Kirby2018zany", """
@Article{Kirby2018zany,
author = {<NAME>},
title = {A general approach to transforming finite elements},
journal = {SMAI Journal of Computational Mathem... |
import random
import sys
class Card:
def __init__(self, suit, value, face, ace):
self.suit = suit
self.value = value
self.face = face
self.ace = ace
class Deck:
def __init__(self):
# Create a List to Hold all of the Cards in our Deck
self.card = []
# Fil... |
import fnmatch
import file_dir_dialog as fdd
import pandas as pd
import msgbox
import time
from datetime import date
from read_config_functions import *
import xlwings as xw
import os
class New_Excel_WB:
def __init__(self):
self.wb = xw.Book()
def df_to_excel(self, df, path):
... |
# __init__.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Public API for flowsa
For standard dataframe formats, see https://github.com/USEPA/flowsa/tree/master/format%20specs
"""
import os
import pprint
from esupy.processed_data_mgmt import load_preprocessed_output
from flowsa.common import paths, biboutputpat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.