text stringlengths 3.07k 12.6k |
|---|
import time
import zmq
import multiprocessing
import json
import traceback
import sys
import concurrent.futures
import daqbrokerDatabase
import daqbrokerSettings
from sqlalchemy import text
from sqlalchemy import bindparam
from sqlalchemy import func
from sqlalchemy.orm import sessionmaker, scoped_session
from supportF... |
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow_datasets as tfds
import tensorflow as tf
import os
import csv
import json
import time
import unicodedata
from selectolax.parser import HTMLParser
import numpy as np
import pandas as pd
def GetPreprocessFunctions(tok... |
#!/Users/11834/.conda/envs/Pytorch_GPU/python.exe
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :RNASolventAccessibility -> feature_extract
@IDE :PyCharm
@Date :2021/5/9 15:54
=================================================='''
import os, torch, random
import nu... |
#!/usr/bin/python
"""
Tests for postman repl
"""
import unittest
import urllib
import postman_repl as pmr
import json
class TestO(unittest.TestCase):
def test_init(self):
test = pmr.O(x=1, y=2)
self.assertDictEqual(test.__dict__, {'x': 1, 'y': 2})
def test_get(self):
test = pmr.O(x=... |
import base64
import os
import json
import time
import traceback
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from . import sessions
template = '''
<!DOCTYPE html>
<html lang="sk">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" co... |
import re
import json
import urllib.request
print("Preparing ...")
# # Download Spelunky2.json from the x64dbg github repo
# #url = "https://gitcdn.link/repo/spelunky-fyi/Spelunky2X64DbgPlugin/master/resources/Spelunky2.json"
# url = "https://raw.githubusercontent.com/spelunky-fyi/Spelunky2X64DbgPlugin/master/resour... |
# -*- coding: utf-8 -*-
# @Time : 2020/10/29 23:58
# @Author : nieyuzhou
# @File : flood.py.py
# @Software: PyCharm
from time import time
import csv
import os
import numpy as np
import rasterio
import torch
from torchvision import transforms
import torchvision.transforms.functional as F
import random
from PIL im... |
from __future__ import division
import csv
import time
from matrices import Matrix
from choleski import choleski_solve
def solve_linear_network(A, Y, J, E, half_bandwidth=None):
"""
Solve the linear resistive network described by the given matrices.
:param A: the incidence matrix
:param Y: the admit... |
""" Flask application to parse STF Files
"""
from six import string_types
from bottle import error, hook, get, request, response # , redirect, put, post
from bottle import HTTPResponse, install # , static_file, url
from bottle import run # , debug # @UnresolvedImport
from decorator import decorator # @UnresolvedI... |
import numpy as np
from utils.util import *
from dewarp.deskew import std_houghlines
''' Assumes image is already dewarped horizontally '''
def dewarp_vertical(img):
blocks_img = make_blocks(img)
keypoints = find_keypoints(blocks_img, show=False)
dewarped_ver = fix_verticals(img, keypoints)
return dew... |
# Copyright 2021 Collate
# 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... |
"""
Module that enables the use of neural networks with NowTrade.
"""
import cPickle
import numpy as np
from pybrain.tools.shortcuts import buildNetwork
from pybrain.datasets.supervised import SupervisedDataSet
from pybrain.supervised.trainers.backprop import BackpropTrainer
from nowtrade import logger
# Networks
FEED... |
# -*- coding: utf-8 -*-
## utilities.py [module]
##
# Utilities for the PETRARCH event data coder
##
# SYSTEM REQUIREMENTS
# This program has been successfully run under Mac OS 10.10; it is standard Python 2.7
# so it should also run in Unix or Windows.
#
# INITIAL PROVENANCE:
# Programmer:
# <NAME>
# ... |
# Copyright 2021 Huawei Technologies Co., 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... |
import os
import stat
import copy
import shutil
import time
import sys
currentTime = time.localtime()
strTime = "%d-%02d-%02d %02d:%02d:%02d" % (currentTime.tm_year, currentTime.tm_mon, currentTime.tm_mday, currentTime.tm_hour, currentTime.tm_min,currentTime.tm_sec)
# 服务模块
serviceName = "ggf"
# git信息
gitBranch = "un... |
import imgaug as ia
from xml_test import *
from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage
from imgaug import augmenters as iaa
# imageio library will be used for image input/output
import imageio
import pandas as pd
import numpy as np
import re
import os
import glob
# this library is needed to ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
# In[37]:
# Spline3_Coef pseudocode p.271
def Spline3_Coef(n, t, y, z):
h = np.zeros(n-1)
b = np.zeros(n-1)
u = np.zeros(n-1)
v = np.zeros(n-1)
for i in range(0, n-1):
h[i] = t[i+1] - t[i... |
#!/usr/bin/env python
# Importing all dependencies
import numpy as np
import rospy
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry
import geometry_msgs
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Point
import tf
import random
import math
from tf.transformations import eule... |
# 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 in wri... |
import time
import click
from perfectextractor.corpora.bnc.extractor import BNCExtractor
from perfectextractor.corpora.bnc.perfect import BNCPerfectExtractor
from perfectextractor.corpora.bnc.pos import BNCPoSExtractor
from perfectextractor.corpora.dpc.extractor import DPCExtractor
from perfectextractor.corpora.dpc.p... |
"""
Loads an autoencoder model, plots the latent space for the test set and the
plots sounds from a directory on top of that space, with arrows pointing to
each of the overlaid sounds. The arrows have labels that are the file names
of the sounds (without the extension).
"""
import argparse
import matplotlib.pyplot as p... |
import inspect
import itertools
import fnmatch
import os
from pymxs import runtime as rt
#
# can't import files from current dir by default, so duplicate path_utils here
#
import os, sys, inspect
def add_path_to_sys_path(path, mode, frame):
assert mode == "unchanged" or mode == "relative_to_cwd" or mode == "rela... |
import telebot
import spotipy
from typing import List, Dict
from src.model.api import MatchCoverAPI
import base64
import requests
import io
from PIL import Image
import credentials as cred
class Answer:
"""
This class represents user answer.
"""
def __init__(self, file_path):
self.file_path =... |
# ---------------------------------------------------------
# IOU Tracker
# Copyright (c) 2019 TU Berlin, Communication Systems Group
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# ---------------------------------------------------------
import cv2
import numpy as np
from lapsolver i... |
#!/usr/bin/python
import pytest
import logging
import fortimailapi
from packaging.version import Version
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger("fortimailapi")
@pytest.fixture
def session(request):
session = fortimailapi.FortiMailAPI()
session.debug("on")
session.https("off")
... |
from __future__ import absolute_import
from aheui.version import VERSION
class ParserError(Exception):
__description__ = ''
def __init__(self, desc=''):
self.desc = desc
def message(self):
return self.__description__ + self.desc
class TooFewArgumentError(ParserError):
__descripti... |
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import os
import pandas as pd
import numpy as np
class ToTensor(object):
"""Transform the numpy array to a tensor."""
def __init__(self, dtype=torch.float):
self.dtype = dtype
def __call__(self, input):
... |
import unittest
class TestDB(unittest.TestCase):
def test_get_all_cell_id_names(self):
"""
usage: python -m unittest cellmesh.test.TestDB.test_get_all_cell_id_names
"""
import os
from cellmesh.db import get_all_cell_id_names
PATH = os.path.dirname(os.path.abspath(__file__))
DB_DIR =... |
import numpy as np
import networkx as nx
from torch import neg_
from .constraint import Constraint
from .literal import Literal
class ConstraintsGroup:
def __init__(self, arg):
if isinstance(arg, str):
# ConstraintGroup(string)
with open(arg, 'r') as f:
self.constrai... |
import argparse
import os
import pickle
from collections import defaultdict
from os import listdir
from pathlib import Path
import cv2
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.model_zoo import model_zoo
from detectron2.modeling import build_model
im... |
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# the COPYING file included with this distribution or
... |
"""
"""
import os
from bs4 import BeautifulSoup
import pandas as pd
import requests
def _get_data_stat(row, data_stat, is_header=False):
if is_header:
return row.find('th', {'data-stat': data_stat}).text
return row.find('td', {'data-stat': data_stat}).text
def format_time(mp):
"""Convert minut... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A collection of auxiliary functions for manipulating data.
"""
import numpy as np
import torch
from numpy.lib.stride_tricks import as_strided
from numpy.fft import ifftshift
import sys
sys.path.append('../')
def random_phase(img):
"""
function for generating... |
# -*- coding: utf-8 -*-
"""Parser for PL/SQL Developer Recall files."""
from __future__ import unicode_literals
import os
import construct
from dfdatetime import delphi_date_time as dfdatetime_delphi_date_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import errors... |
import sys
import os
import json
import re
import subprocess
import argparse
def loadCompilecommandsJson(jsonfile: str) -> dict:
with open(jsonfile, encoding='utf-8') as fd:
js = json.load(fd)
return js
def changeCompilerCommand(cmdline: str) -> str:
"""
add -MM, delete -o
"""
# if c... |
# (C) Copyright 2021-2022 United States Government as represented by the Administrator of the
# National Aeronautics and Space Administration. All Rights Reserved.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# -... |
import torch
import inspect
import hashlib
import json
import logging
import numpy as np
log = logging.getLogger(__name__)
def collate_fn(list_dict, debug=False, merge='cat', dim=0):
"""
Collate function: from list-of-dicts to dict-of-lists
"""
assert merge in ('cat', 'stack'), "Only stack or ca... |
import mysql.connector
import os
ENCODING = 'latin1' # Default utf-8 encoding fails to read BLOB(images) data
# --------------------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import sys
import time
from functools import wraps
from logging import Logger, raiseExceptions
from logging import FileHandler
import settings
import utils
from services import sentry
class SplitLogger(Logger):
def __init__(self, name, level=... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 8 00:09:49 2017
@author: <NAME>
@author: <NAME>
"""
import logging
from collections import Counter
# pylint: disable=C0103
# Invalid constant name
logger = logging.getLogger('pipe.summary')
# pylint: disable=R0902
# Disable too many return
# p... |
# Will call the ITK t2mapping executable
#
# Copyright (C) 2018 <NAME>
# License: BSD 3-clause (see LICENSE)
import os
import subprocess
import logging
import configparser
import argparse
import csv
# path to t2mapping executable expected in ./bin/t2mapping
current_script_path = os.path.realpath(__file__)
current_scr... |
import numpy as np
from numpy import mean
import random
np.random.seed(0)
random.seed(0)
def get_class_name(rawtag):
# get (finegrained) class name
if rawtag.startswith('B-') or rawtag.startswith('I-'):
return rawtag[2:]
else:
return rawtag
class Sample:
def __init__(self, example):
... |
import PyPDF2 #pip install PyPDF2
import os
import pandas as pd
import spacy
# Discussion Partner:
# <NAME> and Ryan (<NAME>)
# url = 'https://www.eia.gov/outlooks/aeo/pdf/aeo2019.pdf'
# url = 'https://www.eia.gov/outlooks/aeo/pdf/aeo2018.pdf'
# Sources
# Prof Levy notes and codes example
# https://www.dataquest.i... |
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from base64 import b64encode
import os
import sys
import json
import getpass
from optparse import OptionParser
from datetime import datetime, timedelta
import time
f... |
#!/usr/bin/python3
import os
import time
import json
from bs4 import BeautifulSoup
import zipper
##########################################################################
# base website URL
URL : str = 'https://readcomiconline.to'
##########################################################################
# FUNCTION ... |
# -*- coding: utf-8 -*-
"""
httpbin.core
~~~~~~~~~~~~
This module provides the core HttpBin experience.
"""
import base64
import json
import os
import time
import newrelic.agent
from flask import Flask, Response, request, render_template, redirect, jsonify
from raven.contrib.flask import Sentry
from werkzeug.datas... |
import sys
sys.path.append("../../model/lib")
import os
import librosa
import numpy as np
import utils
import operator
import itertools
import time
# Parameter
SAMPLE_RANGE = (0,350) # data usage to generate database
TEST_RANGE = (350,550) # data usage to generate database
REPO_PATH = os.path.expanduser("./audio_train... |
# Based on https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/integrate
import torch
from .misc import (
_scaled_dot_product, _convert_to_tensor, _is_finite, _select_initial_step, _handle_unused_kwargs, _is_iterable,
_optimal_step_size, _compute_error_ratio
)
from .solvers import AdaptiveSt... |
import luigi
import os
import pandas as pd
from db import extract
from db import sql
from forecast import util
import shutil
import luigi.contrib.hadoop
from sqlalchemy import create_engine
from pysandag.database import get_connection_string
from pysandag import database
from db import log
class IncPopulation(luigi.T... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Utility functions for downloading, extracting, and reading the
BBC Hindi News Corpus.
https://github.com/NirantK/hindi2vec/releases/tag/bbc-hindi-v0.1
"""
import os
import pandas as pd
import logging
import n... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import h5py
import json
import os
import scipy.misc
import sys
import re
import fnmatch
import datetime
from PIL import Image
import numpy as np
def add... |
# Copyright 2013 Google Inc. All Rights Reserved.
"""Base classes for calliope commands and groups.
"""
import abc
from googlecloudsdk.calliope import usage_text
class LayoutException(Exception):
"""An exception for when a command or group .py file has the wrong types."""
class _Common(object):
"""Base clas... |
"""Count records or non-empty values per column.
This is a simple command that illustrates several aspects of building
a KGTK command. The following features are illustrated:
* Reading a KGTK input file.
* Writing a KGTK output file.
* Writing non-KGTK output to stdout.
* Writing progress feedback to etderr.
* A com... |
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
from scipy import linalg as la
from .cond_net import WCondNet
logabs = lambda x: torch.log(torch.abs(x))
# non-LU unconditional
class InvConv1x1Unconditional(nn.Module):
def __init__(self, in_channel):
super().__i... |
## Python 3.8
## by alber.py
import sys, os
import wx
from db import insert_into_table
from session import TinderBot
baseFolder = os.path.dirname(os.path.abspath('__file__'))
class Robot(wx.Frame):
def __init__(self, parent, title):
super(Robot, self).__init__(parent, title=title, size=(700... |
import pytest
from sqlalchemy import create_engine
import db
from model import model
from model.model import *
from db import Session, sessionScope
from sqlalchemy.exc import IntegrityError
import bcrypt
import pdb
import inspect, os
@pytest.yield_fixture(scope="module")
def connection():
# in-memory sqlite data... |
import Quartz
import pygetwindow
def getAllTitles():
"""Returns a list of strings of window titles for all visible windows.
"""
# Source: https://stackoverflow.com/questions/53237278/obtain-list-of-all-window-titles-on-macos-from-a-python-script/53985082#53985082
windows = Quartz.CGWindowLis... |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
@require_logged_in
def model():
return json.dumps(eidEvents.model)
@require_role(admin_role)
def create():
pass
@require_logged_in
def read():
eid_id = request.args(0)
return json.dumps(eidEvents.read(eid_id))
@require_logged_in
def read_all():
fields = request.vars.get('fields')
if fields:
... |
import numpy as np
import torch
from numpy.linalg import norm
from scipy.stats import entropy
from sklearn.neighbors import NearestNeighbors
__all__ = ['js_divercence_between_pc', 'jsd_between_point_cloud_sets']
#
# Compute JS divergence
#
def js_divercence_between_pc(pc1: torch.Tensor, pc2: torch.Tensor,
... |
import redis
import cloudpickle
import types
import logging
import queue
import itertools
import msgpack
from functools import reduce
from .utils import extract_redis_config
logger = logging.getLogger('lithops')
TASK_GROUP_GLOBAL = None
def get_group():
if TASK_GROUP_GLOBAL:
return TASK_GROUP_GLOBAL
... |
import time
import uuid
import logging
import functools
from autos.utils.csv import write_csv
from .service import Service
from .errors import SheetNotFound
from .errors import ExecutionError
from .errors import SheetAlreadyExists
from .errors import MissingSpreadsheetId
logger = logging.getLogger(__name__)
def ge... |
"""
MIT License
Copyright (c) 2021 - µYert
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, distr... |
# -*- coding: utf-8 -*-
import json
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.base import ModelBase
from django.db.models.fields import related_descriptors
from django.db.models.signals import (
pre_delete,
post_delete,
post_save,
m2m_... |
'''
TODO: use preferences to get arguments to Language
'''
import itertools
import numpy
from brian2.utils.stringtools import deindent, stripped_deindented_lines
from brian2.codegen.functions.base import Function
from brian2.utils.logger import get_logger
from brian2.parsing.rendering import CPPNodeRenderer... |
#!/usr/bin/env python
import sys
import signal
import subprocess
import argparse
###########
# GLOBALS #
###########
FFMPEG = "/usr/local/bin/ffmpeg"
###########
# CLASSES #
###########
class Chapter():
def __init__(self, start, end):
self.title = ""
self.start = start
self.end = end
def __repr__(... |
from drawnow import *
from matplotlib import pyplot as plt
import data
import cpu_redo as cp
import cpu6_redo as cp6
import data_for_1cpu as d1cpu
fig = plt.figure()
ax1 = fig.add_subplot(141)
ax2 = fig.add_subplot(142)
ax3 = fig.add_subplot(143)
ax4 = fig.add_subplot(144)
style = ['g--^', 'r:o', 'b-.s', 'm--*', 'k-.... |
import ast
import operator as op
import re
from collections import namedtuple
from math import pi, cos, sin
from numbers import Real
Point = namedtuple('Point', list('xy'))
OPERATORS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
... |
import os
import types
import pickle
from utils.misc import isnotebook
if isnotebook():
from tqdm import tqdm_notebook as tqdm
else:
from tqdm import tqdm
import numpy as np
import networkx as nx
import graph_tool as gt
import graph_tool.stats as gt_stats
import graph_tool.topology as gt_topology
import graph_t... |
# -*- coding: utf-8 -*-
# From https://gist.github.com/1865786 by @aventurella
# http://docs.neo4j.org/chunked/snapshot/rest-api-traverse.html
# #rest-api-traversal-returning-nodes-below-a-certain-depth
from neo4jrestclient import constants
from neo4jrestclient.iterable import Iterable
from neo4jrestclient.reques... |
# Python std library
import os
import time
# Third Party
import requests as rq
# Django
from django.db import models
# Project
from bot.models import Company, Contractor, PostSeller, Reminder, Seller
from globalvars.models import Global
class Helper(models.Model):
"""docstring for Helper"""
api_url = "htt... |
# -*- coding: utf_8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from data_loader import train_data_loader, test_data_loader
# Load initial models
from networks import E... |
"""
DogFaceNet
Losses for dog identification and embeddings optimization:
-arcface_loss: defined in https://arxiv.org/abs/1801.07698
implemented in https://github.com/auroua/InsightFace_TF
-triplet_loss: defined in https://arxiv.org/abs/1503.03832
implemented in https://git... |
import pygame
from pathlib import Path
from enum import Enum
from random import randrange
GAME_NAME = "Space Travel"
WIN_WIDTH, WIN_HEIGHT = 450, 800
STAR_MIN_RADIUS = 2
STAR_MAX_RADIUS = 5
TRANSPARENT_COLOR = (0, 0, 0, 0)
SPACE_BLUE = (10, 25, 50)
STAR_WHITE = (255, 255, 255)
SCORE_FONT_FAMILY = "comicsans"
SCORE_FON... |
import torch.nn as nn
import torch.nn.functional as F
from models.octave_conv import OctaveConv
class Conv_BN_Act(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=1, bias=False):
super(Conv_BN_Act, self).__init__()
self.layers = nn.Sequential(
n... |
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, ClassVar, Dict, Optional, Tuple
from .exceptions import AppCollectionsAlreadyExistsException, AppCollectionsConfigDoesNotExistException, \
AppCollectionConfigValidationException
from .protocols import A... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
_____________________________________________________________________________
Created By : <NAME> - Bacnv6, <NAME> - Trangnm5
Created Date: Mon November 03 10:00:00 VNT 2020
Project : AkaOCR core
_________________________________________________________________... |
from dynadb.models import DyndbFiles, DyndbFilesDynamics, DyndbModelComponents, DyndbCompound, DyndbDynamicsComponents,DyndbDynamics, DyndbModel, DyndbProtein,DyndbProteinSequence, DyndbModeledResidues
from view.assign_generic_numbers_from_DB import obtain_gen_numbering
from view.traj2flare_modified_wn import * #[!] N... |
from __future__ import absolute_import, division, print_function
from simtbx.nanoBragg import nanoBragg, nanoBragg_beam
from dials.array_family import flex
import numpy as np
"""Purpose of the test: compare nanoBragg background two ways:
1) single channel
2) multiple channels
Overall photon fluence is the same in both... |
import argparse
import glob
import logging
import os
import efficientnet.tfkeras as efn
from sklearn.model_selection import KFold
from models.losses import *
from models.pool import *
from models.preprocess_img import *
from pipeline.utils import get_linear_decay, get_disk_path, seed_everything, count_data_items, tra... |
import moviepy.editor as movie
import os
import re
import pandas as pd
import datetime
import time
# open current directory
os.chdir(os.path.dirname(os.path.realpath(__file__)))
clip_intro = movie.VideoFileClip('input/intro.mp4')
clip_action = movie.VideoFileClip('input/call-to-action-up.mp4')
clip_outro = movie.Vide... |
"""functions related to search for vegetation matching the users input"""
import geopandas as geopandas
import numpy as np
import pandas as pd
import os
import platform
import sqlite3
from gdal import ogr
from shapely.geometry import Point
from tabulate import tabulate
import gdal
from plantDB.plant import Plant
shp_d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
resnet3d
3d resnet model (backbone for deeplabv3)
Author: <NAME> (<EMAIL>)
Created on: December 31, 2019
"""
__all__ = ['ResNet3d', 'resnet3d18', 'resnet3d34', 'resnet3d50', 'resnet3d101']
import torch
from torch import nn
import torch.nn.functional as F
BASE_WIDT... |
"""
A simple key-value store that associates to each module name and a string key a
piece of JSON. If a module needs more efficient or structured storage it should
probably have its own DB handling code.
"""
from __future__ import annotations
import asyncio
import asyncpg
import contextlib
import json
import weakref
f... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import torch as t
import torchvision as tv
import torchvision.transforms as transforms
from torchvision.transforms import ToPILImage
from torch import nn
import torch as t
from torch.nn import functional as F
from torch import optim
show = ToPILImage() # 可以把Tensor转成Image,方便可视化
t.set_num_threads(8)
# 第一次运行程序torchvi... |
from .containers import Parameter, Temporary, DelegatedWrite
from .native_type import NativeType, as_var
from .cbl_type import CBLType, CBLTypeInstance
from .struct_type import StructuredType
from .function_type import IntrinsicCallable
import cmd_ir.instructions as i
class MaybeType(NativeType):
def __init__(se... |
import tensorflow as tf
import numpy as np
#Convolution implementation
def conv_down(batch_input, out_channels, stride=2, filterSize=3, initScale = 0.02, useXavier=False, paddingSize = 1, useBias=False, normKernel=True):
with tf.variable_scope("conv"):
in_height, in_width, in_channels = [batch_input.get_s... |
#!/usr/bin/env python
""" test of psalg_ext.local_minimums, local_maximums, threshold_maximums, local_maximums_rank1_cross
"""
#----------
import sys
import psalg_ext as algos
import numpy as np
#----------
def test01(tname='1', NUMBER_OF_EVENTS=5, DO_PRINT=True) :
print('local extrema : %s' % ('minimums' if tnam... |
# -*- coding: utf-8 -*-
import pandas as pd
from datetime import datetime
from src.api import conn
from src.util import connect_mongo
from log import LogHandler
log = LogHandler('api.log')
def get_dominant(code, start_date=None, end_date=None):
"""
获取某一期货品种一段时间的主力合约列表。合约首次上市时,以当日收盘同品种持仓量最大者作为从第二个交易日开始的主力合约... |
import cv2
import numpy as np
import math
size = 800
center = size//2
radius = 3*size//8
dark_red = (0,0,170)
red = (0,0,240)
dark_orange = (0,80,255)
orange = (0,120,255)
yellow = (0,200,255)
light_yellow = (214,250,255)
white = (255,255,255)
violet = (100,20,140)
dark_violet = (80,0,100)
dark_green = (0,120,0)
gree... |
import chainer
from chainer.backends import cuda
from chainer import Function, gradient_check, report, training, utils, Variable
from chainer import datasets, iterators, optimizers, serializers
from chainer import Link, Chain, ChainList
from chainer.dataset import convert
import chainer.functions as F
import chainer.li... |
from typing import Tuple, Dict, Any, Type, List
from datetime import datetime
from bson import ObjectId
from django.utils import timezone
from extutils.color import ColorFactory
from flags import AutoReplyContentType, ModelValidityCheckResult
from models import (
Model, AutoReplyModuleModel, AutoReplyContentModel... |
'''
| Filename : transducer_data.py
| Description : Functions that return the data fe to the transducer.
| Author : <NAME>
| Created : Tue Dec 8 17:50:51 2015 (-0500)
| Last-Updated: Thu Dec 31 01:08:44 2015 (-0500)
| By: <NAME>
| Update #: 22
'''
import codecs
import numpy
import string
impo... |
r"""!\file
\brief Utilities for memoizing function results.
Memoization decorators let us compute expensive functions once and store the result,
so that if the function is called again with the same arguments the result is just returned.
"""
import functools
import inspect
import typing
import weakref
from dataclass... |
#!/usr/bin/env python
'''
Outer ear simulator
Author: <NAME> <<EMAIL>>
Version: 1.0.0
Data: 2019-09-09
'''
from typing import Tuple
import numpy as np
import scipy.io.wavfile as wav
import scipy.signal as ss
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pysofaconventions import SOFAFile
def... |
# encoding: utf-8
from threading import currentThread, Thread, Lock
from time import time, sleep
from random import randint
# def download_task(filename):
# print('线程 %s 开始下载%s...' % (currentThread().name, filename))
# time_to_download = randint(5, 10)
# sleep(time_to_download)
# print('线程 %s 下载完成! 耗费了%d秒' % (cur... |
#!/usr/bin/python
'''
Program:
This is a liberary program of register
Usage:
1. from register_lib import [func name] or import curvefit
2. use it in your lovely code.
Editor:
Jacob975
#################################
update log
20180628 version alpha 1
1. Remove some
'''
import numpy as np
# cal... |
"""
Utilities for deform sim in PyBullet.
Note: this code is for research i.e. quick experimentation; it has minimal
comments for now, but if we see further interest from the community -- we will
add further comments, unify the style, improve efficiency and add unittests.
@contactrika
"""
from pathlib import Path ... |
import numpy as np
import pandas as pd
from pygmo.core import hypervolume
import matplotlib.pyplot as pltorc
import torch
import torch.nn as nn
def reset_model(model):
for layer in model.children():
if hasattr(layer, 'reset_parameters'):
layer.reset_parameters()
def weights_init(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.