text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
from argparse import ArgumentParser
from operator import add
from random import choice as choice_from
from re import split
class Grid:
"""
Represents a rectangular shape grid that can hold values.
"""
DOWNWARD = (1, 0)
LEFTWARD = (0, -1)
RIGHTWARD = (0, 1)
UPWARD = ... |
# Copyright (c) 2021 <NAME>.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""GEMPAK calculations."""
import numpy as np
# Gravitational constant
g = 9.80616 # m / s^2
# Dry air gas constant
Rd = 287.04 # J / K / kg
def interp_logp_height(sounding, missing=-99... |
import argparse
import fnmatch
import os
import numpy as np
from basic_utils import Models, DataTypes, RunSteps, format_bytes
def get_params():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--log-root", dest="log_root", default="../../logs",
... |
#!/usr/bin/env python3
import inspect
import json
import pickle
import re
import time
from collections import defaultdict
from operator import itemgetter
import nltk
import requests
from bs4 import BeautifulSoup
from nltk.corpus import wordnet
'''
Antonym Dict = {
WORD_1: {
ORIGIN_1: [ANTONYM_1, ..., ANT... |
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <<EMAIL>>
#
# 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 ... |
from __future__ import print_function
from twisted.internet import defer
import math
import os
import errno
import pokeher.cards as cards
from pokeher.theaigame import TheAiGameActionBuilder
from hand_stats import HandStats
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python ... |
import torch
from math import log
from itertools import chain
from collections import defaultdict, Counter
from multiprocessing import Pool
from functools import partial
from tqdm.auto import tqdm
__all__ = ['bert_types']
bert_types = [
'bert-base-uncased',
'bert-large-uncased',
'bert-base-cased',
'be... |
## main reference: https://github.com/fspaolo/captoolkit
## author: <NAME>;
## create: 2021.8.8;
import numpy as np
from utils.make_grid import make_grid
from utils.spatial_filter import spatial_filter
from scipy.ndimage import map_coordinates
from scipy.spatial import cKDTree
from scipy.spatial.distance import cdi... |
import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.functional as tf
import torch.utils.data
import time
from tqdm import tqdm
import model
import argparse
try:
import nvidia_smi
NVIDIA_SMI = True
except:
NVIDIA_SMI = False
import sys
import os
import pathlib
class Dataset(torc... |
from tensorflow.keras.utils import Sequence
from multiprocessing import current_process
from MultiPlanarUNet.logging import ScreenLogger
from utime.preprocessing.scaling import apply_scaling, assert_scaler
from utime.utils import assert_all_loaded
from utime.errors import NotLoadedError
from functools import wraps
impo... |
import os
from random import choice, randint, uniform
import json
import time
from PIL.ImageDraw import Draw
"""
sudo pip3 install PIL
"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
class VerifyCode(object):
"""生成验证码模块"""
# 去掉易混淆字符'i' 'I' 'l' 'L' 'o' 'O' 'z' 'Z'
DEFAULT_CHARS = "0123456789a... |
__copyright__ = \
"""
Copyright ©right © (c) 2019 The Board of Trustees of Purdue University and the Purdue Research Foundation.
All rights reserved.
This software is covered by US patents and copyright.
This source code is to be used for academic research purposes only, and no commercial use is allowed.
For any ... |
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import datasets, models, transforms
from torch.utils.data import DataLoader
import os, argparse, random, math
import copy, logging, sys, time, shutil, json
from collections import Counter, OrderedDict
from lib import wr... |
# Copyright (c) FlowTorch Development Team. All Rights Reserved
# SPDX-License-Identifier: MIT
import warnings
from typing import Any, Dict, Optional, Sequence, Tuple
import torch
import torch.nn as nn
from torch.nn import functional as F
import flowtorch
def sample_mask_indices(
input_dim: int, hidden_dim: in... |
#!/usr/bin/python3
import logging
import socket
import traceback
from io import RawIOBase
from math import cos, radians, sin, degrees
from pathlib import Path
from queue import Queue
from threading import Event, Thread
from typing import Any, Callable, Optional, Tuple
from pynmea2 import ChecksumError, NMEASentence, P... |
import os
import sys
import pickle
import numpy as np
import pandas as pd
import random
import torch
import pdb
from torch.utils.data import Dataset, DataLoader,RandomSampler
import torchvision.transforms as transforms
from torchvision.utils import save_image
from PIL import Image
import matplotlib.pyplot as plt
from ... |
from __future__ import (
division, print_function, unicode_literals, absolute_import
)
import numpy as np
from scipy.special import gammaln
from scipy.integrate import quad
import pandas as pd
def get_purity(y_true, y_pred, threshold):
num = ((y_true == 1) & (y_pred >= threshold)).sum()
denom = (y_pre... |
import sqlite3
from sqlite3 import Error
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import folium
conn = sqlite3.connect('../data/rodents_data.db')
sql_statement = """SELECT latitude,longitude,count(inspection_date) as recurrence_index FROM 'rodent_incidents' where inspection_dat... |
"""
Usage:
for database:
python this_file.py --file <input_jsonl> --version <pytakes|runrex> --connection-string <sqlalchemy-style-connection-string>
for output file
python this_file.py --file <input_jsonl> --version <pytakes|runrex> --output-directory <directory-to-place-output>
This program automates the proc... |
from json import dump
from json import load
from math import floor
from operator import attrgetter
from random import choice
from random import randint
from random import random
from random import sample
from random import uniform
from typing import List
import sys
from neural_network import NeuralNetwork
from populat... |
import sys
import tqdm
from abc import abstractmethod
import torch
import numpy as np
from typing import *
sys.path.append('')
from transformers import AutoTokenizer
from transformers import AutoModel
from cube.io_utils.objects import Sentence, Document
import fasttext
import fasttext.util
class LMHelper:
def _... |
#-*- coding: utf-8 -*-
import json
from .git_one_commit_features import GitOneCommitFeatures
from defect_features.git_analysis.analyze_git_logs import retrieve_git_log
from defect_features.object.features import PurposeFeatures as PurposeFeaturesObj
from classifier.classifier import *
from analyzer.git_commit_linker im... |
#!/usr/bin/env python3
"""
Author: <NAME>
Email: <EMAIL>
Github: https://github.com/meherett
"""
import sha3
import hmac
import ecdsa
import struct
import codecs
import hashlib
import binascii
import random
from hashlib import sha256
from ecdsa.curves import SECP256k1
from mnemonic.mnemonic import Mnemonic
from ecdsa... |
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.python.ops.linalg.sparse import sparse as tfsp
from . import modes as modes
from . import ops as ops
def dot(a, b, transpose_a=False, transpose_b=False):
"""
Dot product between `a` and `b`, with automatic handling of batch dim... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import necessary Python Packages
import re
import pickle
import torch
import torch.optim as optim
from data_manager import DataManager, load_config
from model import BiLSTMCRF
from utils import *
import warnings
import numpy as np
warnings.filterwarnings("ignore")
devi... |
import asyncio
import logging
from functools import partial
import typing
from slixmpp import Message, Iq, Presence, JID
from slixmpp.xmlstream.handler import Callback
from slixmpp.xmlstream.matcher import StanzaPath
from slixmpp.plugins import BasePlugin
class XEP_0100(BasePlugin):
"""
XEP-0100: Gateway in... |
# -*- coding: utf-8 -*-
"""Tests for hydx.py"""
from collections import OrderedDict
from unittest import TestCase
import pytest
from hydxlib.hydx import check_headers, ConnectionNode, Connection, Structure, Profile
from hydxlib.importer import import_hydx
def test_check_headers(caplog):
a = [1, 2, 3]
b = [2,... |
from __future__ import annotations
import abc
import asyncio
import logging
import typing as t
from contextlib import asynccontextmanager
from fnmatch import fnmatch
from warnings import warn
try:
from functools import cached_property
except ImportError:
from backports.cached_property import cached_property
... |
# General Imports
import csv
import cv2
import numpy as np
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
## -----
## METHODS
# Helper function to read in images from center, left and right cameras
def readx3(angles, images, batch_sample, correction, path):
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from enum import Enum
import numpy as np
import traceback
import seedot.config as config
from seedot.util import *
class Op:
Op = Enum('Op', '+ - * / << >> & | ^ ~ ! && || < <= > >= == !=')
Op.print = lambda self, ... |
import os
import warnings
from openpyxl import load_workbook
from openpyxl.styles import NamedStyle, Font, PatternFill, Alignment, Border, Side
import tkinter as tk
from tkinter import *
from tkinter import messagebox
import tkinter.font
class GUI(tk.Frame):
def __init__(self, master):
self.window = maste... |
# The Admin4 Project
# (c) 2013-2014 <NAME>
#
# Licensed under the Apache License,
# see LICENSE.TXT for conditions of usage
nodeinfo=[]
from SpecificEntry import SpecificEntry
from Entry import Entry
from . import AttrVal
from wh import xlt
import wx, adm
class Groups(SpecificEntry):
name=xlt("Groups")
def ... |
import numpy as np
from keras.models import Sequential
from keras.layers import Lambda, Dropout
from keras.layers.convolutional import Convolution2D, Conv2DTranspose
from keras.layers.pooling import MaxPooling2D
from keras.callbacks import ModelCheckpoint
import os
from ..io.tiling import get_tiles, get_tiles_fast, get... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# mmshop.api
'''
:author: madkote
:contact: madkote(at)bluewin.ch
API
---
The API implementation
'''
import cherrypy
import datetime
import jinja2
import json
import logging
import os
import mmshop
VERSION = (0, 4, 0)
__all__ = ['MickeyMouseShop']
__author__ = 'madkot... |
import os
import numpy as np
import cardio.batchflow as bf
from cardio import EcgBatch
from my_pipelines.my_pipelines import PanTompkinsPipeline, HMM_predict_pipeline, LoadEcgPipeline, HilbertTransformPipeline
from my_tools import calculate_old_metrics, calculate_metrics, calc_metr_batch, calc_metr_qrs, get_meta, show_... |
import pyttsx3
import speech_recognition as sr
import datetime
import os
import cv2
import random
import time
from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtCore import QTimer,QTime,QDate,Qt
from PyQt5.QtGui import QMovie
from PyQt5.QtCore import *
from PyQt5.QtWidgets import*
from PyQt5.QtCore impor... |
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
#!/usr/bin/env python
"""
Copyright 2014 <NAME>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 08:50:12 2019
@author: <NAME>
"""
import itertools as it
import numpy as np
### IGNORE SET
import json
with open("ignored.json", 'r') as f:
_ignored = set()
for el in json.load(f):
# typing
try:
_ignored.add(int(... |
import glob
import hashlib
import json
import os
import shutil
import signal
import stat
import zlib
from tqdm import tqdm
from multiprocessing import Pool
# BLOCK_SIZE = 1000000 # The size of each read from the file
BLOCK_SIZE = 65536 # The size of each read from the file
def initializer():
"""Ignore CTRL+C ... |
import argparse
import io
import os
import math
import uuid
import tensorflow as tf
import hypergan as hg
import hyperchamber as hc
import json
from hypergan.generators import *
from hypergan.search.random_search import RandomSearch
from hypergan.viewer import GlobalViewer
from common import *
from PIL import Image
im... |
# -*- encoding: utf-8 -*-
from django.contrib import messages
from django.contrib.sites.models import Site
from django.http import Http404
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django... |
import json
import mysql.connector
from passlib.apps import custom_app_context as pwManager
from functools import wraps
def connection_needed(f):
''' Decorator function for all function that connects to the database.
'''
@wraps(f)
def dbConnect(*args, **kwargs):
config = args[0].config #Get the current con... |
from utils import color
import ast
import os
BUFFER_SIZE = 8 * 1024
'''
Sends information about file added to the filesystem in the following format:
ADD <source_path> <destination_path>
'''
def add_file(src, dst, client):
msg = "ADD {} {}".format(src, dst)
client.send(msg)
send_file(src, client)
m... |
#!/usr/bin/env python
'''
Takes two <.react> files and a <.fasta> file and a static nucleotide motif, or a list of motifs.
These motifs must obey the standard nucleic acid alphabet; A,G,C,T and R,Y,W,S,M,K,B,H,D,V,N
Lists all occurances of that motif along with surrounding 5' and 3' nucleotides, along with the
reacti... |
# +
from theforce.similarity.similarity import SimilarityKernel
from theforce.descriptor.soap import HeteroSoap, NormalizedSoap
from theforce.descriptor.cutoff import PolyCut
from theforce.util.util import iterable
import torch
class HeterogeneousSoapKernel(SimilarityKernel):
def __init__(self, kernel, a, b, lma... |
import os
import sys
import yaml
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QTableWidgetItem, QMessageBox
from JDMCA_Form import Ui_JDMCA
from utils.config import get_config
import subprocess
from utils.getchromedriver import check_driver_version
mirror_dic = {
"清华": "https://pypi.tuna.tsinghu... |
# Utility class that wraps KMeans and outputs the formatted experiment output
import time
from sklearn.metrics import f1_score
import pandas as pd
import numpy as np
#Normalizes all data except the label column, since we want to leave that intact.
def normalizeLabeledData(data):
result = data.copy()
for feat... |
"""
Application : ReplSim
File name : ANN.py
Authors : <NAME>, <NAME>, <NAME>
Creation : 04/19/21
Description : This file contains the development of a neural net
the Neural Net is a recurrent neural net with supervised learning
called long short-term memory learn sequences
"""
# C... |
import os, sys
import numpy as np
import pdb
import time
import multiprocessing as mp
from .compute_roc import compute_roc_points
__all__ = ["test_megaface", "test_megaface_roc"]
probe_num = 3530
label_file = 'data/megaface_test/facescrub3530/label.txt'
# probe_num = 3964
# label_file = '/mnt/lustre/zhouyucong/veri... |
"""
Copyright 2016, <NAME> <<EMAIL>>
ModelFamily class and related functionality for instantiating models.
"""
import copy
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor
__author__ = 'langmead'
class ModelFamily(object):
""" Model family and simple hill-climb... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Osia 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 la... |
from inc_noesis import *
import os
SECTION_HEADER_SHORT = 0
SECTION_HEADER_LONG = 1
COLOR_RGBA = 3
COLOR_RGB = 4
def registerNoesisTypes():
handle = noesis.register( \
"Rainbow Six (1998) static model", ".sob")
noesis.setHandlerTypeCheck(handle, rsStaticModelCheckType)
noesis.setHandlerLoadMode... |
from __future__ import annotations
import argparse
import base64
import io
import json
import math
import os
import re
import shutil
import sys
import traceback
from collections import OrderedDict
from contextlib import ExitStack
from hashlib import sha256
from math import isclose
from pathlib import Path
from typing ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
import numpy as np
from sklearn import decomposition, preprocessing
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.initializers import Constant
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.models import Sequential
from ten... |
# -*- coding: utf-8 -*-
"""
flask_dialogflow.conversation
~~~~~~~~~~~~~~~~~~~~~~~~~
The core Dialogflow Conversation classes.
:copyright: (c) 2018 ONSEI GmbH
:license: Proprietary
"""
from collections import defaultdict
from typing import Optional, Mapping, Any, DefaultDict, List
from flask_dialo... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"Logical model of dynamic fixtures creation."
# pylint: disable=invalid-name
# pylint: disable=global-variable-not-assigned
# pylint: disable=global-statement
# pylint: disable=no-else-return
import copy
fr... |
import time
from itertools import product
import numpy as np
from loguru import logger
from scipy.optimize import minimize
from tqdm import tqdm
import wandb
from model_wrapper import LinearRegressionWrapper
from quantum_circuit import QuantumBox
from util import generate_measurement_matrices
def generate_random_co... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
# Brain Tumor Classification
# Enhance tumor region in each image.
# Author: <NAME>
# Copyleft: MIT Licience
# ,,, ,,,
# ;" '; ;' ",
# ; @.ss$$$$$$s.@ ;
# `s$$$$$$$$$$$$$$$'
# $$$$$$$$$$$$$$$$$$
# $$$$P""Y$$$Y""W$$$$$
# $$$$ p"$$$"q $$$$$
# $$$$ .$$$$$. $$$$'
# $$$DaU$$O$$DaU$$$'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/3 19:45
# @Author : duanhaobin
# @File : use_reg_deal_douban_book_data_co.py
# @Software: PyCharm
# @desc: 使用正则表达式处理豆瓣图书信息 主要是对作者 译者 定价作处理
import requests
import time
from bs4 import BeautifulSoup
import re
def get_urls(n):
'''
分页网页url... |
# -*- coding: utf-8 -*-
"""
# Pars as object
"""
import numpy as np
import pandas as pd
# import re
class Pars_gen:
def __init__(self):
self.filedir = []
self.fnameshort = []
self.fixed_values = np.array([[0, 0, 0], [0, 0, 0]], dtype=float)
self.hydro = hydro()
... |
from colorama import Fore, Style, Back
from pathlib import Path
userpath = Path.home() # Detectando pasta do usuário /Users//
userpath = str(userpath) + '\\Downloads' # Pasta do usuário em tipo str
def traco(msg):
"""
-> Print personalizado com traços de acordo com o tamanho do parâmetro msg
:param msg:... |
import os
import datetime
import tensorflow as tf
from tensorflow.contrib.rnn import GRUCell
from tensorflow.python.ops.rnn import bidirectional_dynamic_rnn as bi_rnn
from util_rnn import attention, batch_iter
def hnn_train(x_train, y_train, FLAGS, w2v_model, hnn_dir):
with tf.Graph().as_default():
sessio... |
from .geometry import breadth_first_traversal, centroid, make_path, TreeLayoutBase
import numpy as np
#: clock-face coordinates assume left-horizontal growth
index_position_shift = {
0: (-0.0, -0.0),
2: (-0.0, 1),
3: (-0.5, 1),
4: (-0.8, 0),
5: (-0.5, -1),
6: (-0.6, -1),
8: (-0, -1)
}
index... |
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# Th... |
import sys
sys.path.insert(0, "./..")
import textract
import jieba
import jieba.analyse
import os
import itertools
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import collections
import operator
import gensim
import logging
import math
import codecs
from gensim.models import ... |
# -*- coding: utf-8 -*-
'''
A Convolutional Neural Network implementation example using Tensorflow Library.
The example uses the mnist data in kaggle
https://www.kaggle.com/c/digit-recognizer
Author:sfailsthy
'''
# Libraries
import tensorflow as tf
import numpy as np
import csv
# setting parameters
learning_rate=1e-4... |
from sys import exit
from random import randint
from textwrap import dedent
###########################################
###########################################
###########################################
class Scene(object):
def enter(self):
print(f"{self} has not yet been implemented.")
exit(1)
###########... |
#!/usr/bin/env python3
# coding=utf-8
# date 2019-06-20 15:09:25
# author calllivecn <<EMAIL>>
import io
import os
import sys
import stat
import logging
from struct import pack, unpack, pack_into, unpack_from, Struct
from shutil import copyfileobj
#--------------------------------------------------------
# Init
#----... |
# coding=utf-8
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn import GINConv
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
'''
num_layers: number of layers in the neural networks (EXCLUDING the input ... |
# Imports
import os
import shutil
import zipfile
import csv
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import smtplib
import emails
import indicators
# Constants
DOWNLOAD_PATH = "https://static.stooq.pl/db/h/d_pl_txt.zip"
ARCHIVE_PATH = "data/all_data.zip"
QUOTES_PATH... |
from __future__ import unicode_literals
from django.contrib import admin
from django.conf import settings
from django.conf.urls import url
from django import forms
from django.core.urlresolvers import reverse
from django.contrib.admin.util import quote
from django.utils.translation import ugettext_lazy as _, ugettext,... |
#!/usr/bin/env python2
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Script to enter the ChromeOS chroot with mounted sources.
This script enters the chroot with mounted sources.
"""
from __future__ import print_function
__author__ = '<EMAIL> (<NAME>)'
import argparse
import getpass
import os
import pwd
im... |
import sys
import numpy as np
import time
import os
import filecmp
import datetime
import random
import argparse
sys.path.append("../dnam/")
from processfile import ProcessFile
from log import get_logger
parser = argparse.ArgumentParser(description="Simulation file for dNAM")
parser.add_argument("-s", "--start", help... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date : 2018-04-11
# Author : <NAME> (<EMAIL>)
import os
import sys
import argparse
import logging
from Bio import pairwise2
from Bio import SeqIO
from Bio.pairwise2 import format_alignment
from itertools import groupby
import operator
from core.sequence import rev... |
import abc
import numpy as np
import torch
from ..utils import softmax
from ..utils.decorators import enforce_observed
from ..posteriors import Posterior
from ..priors import Prior
class Model(metaclass=abc.ABCMeta):
"""Base class for models with a log-likelihood function"""
def __init__(self, verbose=Fals... |
# -*- python -*-
# stdlib imports ---
import os
import os.path as osp
import textwrap
import subprocess
try:
subprocess.check_output
except AttributeError:
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-ze... |
# -*- coding: utf-8 -*-
"""
Script generator for ogs5py.
.. currentmodule:: ogs5py.tools.script
Generator
^^^^^^^^^
.. autosummary::
:toctree: generated
gen_script
Helpers
^^^^^^^
.. autosummary::
:toctree: generated
formater
get_line
tab
add_block_file
add_load_file
add_list_file
---... |
import json
import csv
import random
import os
import re
import numpy as np
import gc
import copy
class server(object):
def __init__(self,
startTime,
setupTime,
requestCanHandle = 50,
failureProbability = 0.,
type = 0):
s... |
#!/usr/bin/env python3
import glob
import os
import platform
import sys
import shutil
import subprocess
import re
import multiprocessing
import itertools
from contextlib import contextmanager
# Overall script settings
this_project_package = f'{os.getcwd()}/bdsg'
this_project_source = f'{this_project_package}/src'
t... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import pandas as pd
from sklearn.metrics import confusion_matrix
from .confusion_matrix import pretty_plot_confusion_matrix
def create_ara(c, steps=10):
mini = np.min(c)
maxi = np.max(c)
if (maxi-mi... |
from typing import Sequence, Any, Optional, List, Tuple, Dict, Union, Set
from datacode.logger import logger
from datacode.models.dtypes.base import DataType
from typing_extensions import Protocol
import pandas as pd
from datacode.models.column.column import Column
from datacode.models.variables import Variable
from ... |
#######################################################
#### NOW AT A GITHUB REPO ####
#### https://github.com/tusing/unicorn_phat ####
#######################################################
#!/usr/bin/env python
# Display a list of user-defined color bars;
# fill the remaining area w... |
from morango.constants import transfer_stages
from morango.constants import transfer_statuses
from morango.errors import MorangoContextUpdateError
from morango.models.certificates import Filter
from morango.models.core import SyncSession
from morango.models.core import TransferSession
from morango.utils import parse_ca... |
import ctypes
import json
import os
import sys
import time
import mouse
from PyQt5.Qt import QThread
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QProgressBar
import ocr
from UIWindow import Ui_MainWindow
from art_saver import ArtDatabase
from art_scanner_logic import ArtScannerLogic, GameInfo
... |
#yoloを使用したkeyframeの抽出
import av
import matplotlib.pyplot as plt
from PIL import Image
import cv2
import numpy as np
import time
from sklearn.cluster import DBSCAN
import pretrainedmodels as ptm
#yolo用のモジュール
import torch
import torch.nn as nn
from torchvision import datasets, models, transforms
from torc... |
import os
import torch
import numpy as np
from subprocess import call
from geometry_utils import load_obj, export_obj
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
from quaternion import qrot
from colors import colors
cube_mesh = load_obj(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cube.obj'), no... |
# Copyright (c) 2013, veena and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, add_days
from frappe import _
from datetime import datetime
def execute(filters=None):
columns = get_columns()
data=[]
conditions=get_co... |
# \file NiftyReg.py
# \brief This class makes NiftyReg accessible via Python
#
# \author <NAME> (<EMAIL>)
# \date Aug 2017
# Import libraries
import os
import numpy as np
import SimpleITK as sitk
from abc import ABCMeta, abstractmethod
import nipype.interfaces.niftyreg
import pysitk.python_helper as ph... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import optuna
import h5py
import numpy as np
import numpy as np
import pandas as pd
import h5py
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Net(nn.Module):
def __init__(self,num_unit1,num_unit2,drop_out):
... |
"""
/*
* Copyright (c) 2017, University of Louisiana at Lafayete
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copy... |
"""
Author: <NAME>
Created: 25/02/2021 2:08 PM
"""
import pandas as pd
import ksl_env
import os
import itertools
import glob
from copy import deepcopy
from Storylines.storyline_building_support import base_events, map_irrigation
from Storylines.check_storyline import ensure_no_impossible_events
from Climate_Shocks ... |
import logging
import datetime
from base64 import b16encode
import core
from core.helpers import Url
import json
logging = logging.getLogger(__name__)
def score(releases, imdbid=None, imported=False):
''' Scores and filters scene releases
releases (list): dicts of release metadata to score
imdbid (str):... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
* https://wiki.python.org/moin/TimeComplexity
* http://algs4.cs.princeton.edu/21elementary/
* https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm
* http://www.cs.princeton.edu/courses/archive/spr15/cos126/lectures/41analysis-2x2.pdf
"""
... |
"""Miscellaneous general utility functions"""
import numpy as np
from numba import njit, prange
from .interpolation import interpolate
def to_list(obj):
"""Cast an object to a list. Almost identical to `list(obj)` for 1-D objects, except for `str`, which won't be
split into separate letters but transformed ... |
# Import any DAObject classes that you will need
from docassemble.base.util import Individual, Person, DAObject
# Import the SQLObject and some associated utility functions
from docassemble.base.sql import alchemy_url, upgrade_db, SQLObject, SQLObjectRelationship
# Import SQLAlchemy names
from sqlalchemy import Column,... |
# -*- coding: utf-8 -*-
# ------
# License: MIT
# Copyright (c) 2013 <NAME> (eowenr atmark gmail dot com)
"""
Utils for videolectures-dl
"""
import re
import sys
import os
import subprocess
import time
import requests
def _regex_match_get(pattern, text, position=1):
"""
Return matched pattern or None
""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.