text stringlengths 3.07k 12.6k |
|---|
from __future__ import absolute_import, division
import logging
import re
from datetime import datetime
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import func
from changes.config import db
from changes.constants import Result
from changes.db.utils import create_or_update
from changes.models import... |
import random
import numpy as np
from MAIN.Basics import Processor, Space
from operator import itemgetter
class StateSpace(Processor, Space):
def __init__(self, agent):
self.agent = agent
super().__init__(agent.config['StateSpaceState'])
def process(self):
self.agent.dat... |
"""
Controller helper
"""
from flask import current_app
from functools import wraps
from flask import request
from jose import jwt
import requests
import datetime
from model import SystemAuthKey
from shared import db
class AuthError(Exception):
"""
Authentication error
Error related to Authentication.
... |
import numpy as np
#pythran export _Aij(float[:,:], int, int)
#pythran export _Aij(int[:,:], int, int)
def _Aij(A, i, j):
"""Sum of upper-left and lower right blocks of contingency table."""
# See `somersd` References [2] bottom of page 309
return A[:i, :j].sum() + A[i+1:, j+1:].sum()
#pythran export _Dij... |
import random
import pytest
import redis
from RLTest import Env
from test_helper_classes import _get_ts_info
def test_ooo(self):
with Env().getClusterConnectionIfNeeded() as r:
quantity = 50001
type_list = ['', 'UNCOMPRESSED']
for chunk_type in type_list:
r.execute_command('ts... |
"""api request/response models."""
import abc
from typing import Dict, Optional, Type, Union, List
from datetime import datetime
import attr
from fastapi import Body, Path, Query, Response
from pydantic import BaseModel, create_model
from pydantic.fields import UndefinedType
from . import descriptions
NumType = Union... |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 25 21:23:38 2011
Author: <NAME> and Scipy developers
License : BSD-3
"""
import numpy as np
from scipy import stats
from statsmodels.tools.validation import array_like, bool_like, int_like
def anderson_statistic(x, dist='norm', fit=True, params=(), axis=0):
"""
... |
from rsqsim_api.fault.multifault import RsqSimMultiFault, RsqSimSegment
import multiprocessing as mp
from typing import Union
import h5py
import netCDF4 as nc
import numpy as np
import random
sentinel = None
def multiprocess_gf_to_hdf(fault: Union[RsqSimSegment, RsqSimMultiFault], x_range: np.ndarray, y_range: np.nda... |
import logging
import os
import UserDict
import yaml
CONTOUR_YAML_NAMES = ['contour.yaml', 'contour.yml']
# TODO: Handle other configuration formats.
# TODO: Handle persitent storage of configuration.
class MissingConfigurationError(Exception):
"""Missing configuration option."""
class BadModulePathError(Exc... |
import random
from typing import List, Optional
import torch
import torch.nn as nn
class HardMultimodalMasking(nn.Module):
def __init__(
self,
p: float = 0.5,
n_modalities: int = 3,
p_mod: Optional[List[float]] = None,
masking: bool = True,
m3_sequential: bool = Tr... |
import sys
import numpy
import helper
import bayesianClusterEvaluationLaplacian
import experiments
import baselineMultiLogReg
import pickle
import syntheticDataGeneration
import sklearn.metrics
import constants
def getANMI(allResults, criteriaID):
bestId = numpy.argmax(allResults[:, criteriaID])
return allRes... |
# Copyright 2016 PerfKitBenchmarker Authors. 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... |
# A sample spatial model with agents eating grass off patches.
# No visualization as of yet
#===============
# SETUP
#===============
from helipad import Helipad
heli = Helipad()
heli.name = 'Grass Eating'
heli.order = 'random'
heli.stages = 5
heli.addParameter('energy', 'Energy from grass', 'slider', dflt=2, opts=... |
# Copyright (C) 2019-present eyeo GmbH
#
# 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, d... |
import numpy as np
from skimage import morphology
import hy
# setup tensorflow
import os
os.environ["CUDA_VISIBLE_DEVICES"]=""
import tensorflow as tf
print(f'tensorflow version = {tf.__version__}')
tf_device = '/cpu:0'
setup = {
# based on 3_compare_re_nn.py
'in_size': 64,
'undersample_target': False,
# Number of... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
# Copyright 2019 The Vitess Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
import torch
from .loss import GeneratorLoss, DiscriminatorLoss
from .functional import boundary_equilibrium_generator_loss, boundary_equilibrium_discriminator_loss
__all__ = ['BoundaryEquilibriumGeneratorLoss', 'BoundaryEquilibriumDiscriminatorLoss']
class BoundaryEquilibriumGeneratorLoss(GeneratorLoss):
r"""Bou... |
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
import getopt
import sys
import os
import io
import string
import pickle
import math
import operator
# Dictionary is a dictionary of {term: {index: i, doc_freq: n}}
# Postings is a dictionary of {term:{interval: x, doc_ids: list(doc_ids... |
from bip import *
import idc
import pytest
"""
Test for all classes used for representing ast nodes are tested by this
file, this is also used for testing the visitors.
Are tested in this file the following:
* :class:`AbstractCItem` from ``bip/hexrays/astnode.py``
* :class:`CNode`, :class:`CNod... |
##############################################################################
#
# Copyright (c) 2009 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
#!/usr/bin/env python
import getpass
import optparse
import os
import struct
import sys
import unittest
from random import randrange
PY3 = sys.version_info[0] == 3
if PY3:
import builtins
print_ = getattr(builtins, 'print')
raw_input = getattr(builtins, 'input')
else:
def print_(s):
sys.stdout.... |
# -*- coding: utf-8 -*-
import os, sys
import numpy as np
import itertools
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from pydaily import filesystem
def get_slide_filenames(slides_dir):
slide_list = []
svs_file_list = filesystem.find_ext_files(slides_dir, "svs")
slide_li... |
"""Plugwise Switch component for HomeAssistant."""
from __future__ import annotations
import logging
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import (
ATTR_ID,
ATTR_NAME,
ATTR_STATE,
STATE_OFF,... |
from argparse import (
Action,
ArgumentParser,
Namespace,
_SubParsersAction,
)
import contextlib
from typing import Iterator, Tuple, Sequence, Type, Any
from async_service import Service
from eth_utils import ValidationError, to_tuple
from lahja import EndpointAPI
from eth.db.header import (
Head... |
""" Layer common utilities """
import pickle
import numpy as np
import tensorflow as tf
from absl import logging
def init_word_embedding(vocab_size, num_units, we_trainable, we_file=None, name_prefix="w"):
"""Initialize word embeddings from random initialization or pretrained word embedding """
if not we_fi... |
import os
import sys
import json
import torch
import logging
from tqdm import tqdm
from . import loader_utils
from ..constant import BOS_WORD, EOS_WORD, Tag2Idx
logger = logging.getLogger()
# -------------------------------------------------------------------------------------------
# preprocess label
# ------------... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 12:43:36 2021
@author: ziyi
"""
import numpy as np
import json
import networkx as nx
import math
import torch
# CLS and DTW method copy from: https://github.com/aimagelab/perceive-transform-and-act/
class CLS(object):
""" Coverage weighted ... |
import cadquery
from copy import copy
import logging
from cqparts.utils import CoordSystem
from cqparts.utils.misc import property_buffered
from . import _casting
log = logging.getLogger(__name__)
# --------------------- Effect ----------------------
class Effect(object):
pass
class VectorEffect(Effect):
... |
import itertools
import logging
import math
from math import copysign, gcd
from operator import itemgetter
from typing import Hashable, Tuple, Dict
LOG = logging.getLogger(__name__)
ASTEROID_MARKER = "#"
NodeID = Hashable
Node = Dict
Edge = Tuple[NodeID, NodeID]
class Graph():
def __init__(self):
self.... |
# coding: utf-8
from struct import calcsize, unpack
from jotdx.crawler.base_crawler import BaseCralwer
import shutil
import tempfile
import random
import os
import six
if six.PY2:
import zipfile
"""
https://github.com/rainx/jotdx/issues/133
获取历史财务数据的接口,参考上面issue里面 @datochan 的方案和代码
"""
class HistoryFinancialL... |
#! /usr/bin/env python3
import os
import subprocess
import re
import sys
import fnmatch
from collections import defaultdict
from optparse import OptionParser
lint_root = os.path.dirname(os.path.abspath(__file__))
repo_root = os.path.dirname(os.path.dirname(lint_root))
def git(command, *args):
args = list(args)
... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
"""
This module contains utility functions to use with the attr package, concerning for instance parameter validation
or serialization. They are used within the ote_config_helper or the configuration elements.
"""
from enum import En... |
import time
import config
from typing import Dict, List
from lib.textdiff import diff
from model import esdb
from model._post import POST_TYPES
from model.manage_log import ManageLog, MANAGE_OPERATION as MOP
from model.post_stats import post_stats_add_topic_click, post_stats_topic_move, post_stats_topic_new, post_stats... |
from django.conf.urls import url
from django.contrib import messages
from django.contrib.admin import ModelAdmin
from django.db.models import Q
from django.template.response import TemplateResponse
from django.templatetags.static import static
from django.urls import reverse
from django.utils.translation import ugettex... |
def mind_ssc(image, quantisation_step):
return image
import torch
import torch.nn as nn
import torch.nn.functional as F
def pdist(x, p=2):
if p==1:
dist = torch.abs(x.unsqueeze(2) - x.unsqueeze(1)).sum(dim=3)
elif p==2:
xx = (x**2).sum(dim=2).unsqueeze(2)
yy = xx.permute(0, 2, 1)
... |
from discord.ext import commands
import discord
import cybereco
import json
import random
import asyncio
rarities = {
0: "Common",
1: "Rare",
2: "Legendary"
}
items = {
1: {"rarity": 0, "name": "Common Gun"},
2: {"rarity": 1, "name": "Rare Sword"},
3: {"rarity": 2, "name": "Legendary Fist"}
... |
import argparse
import logging
import os
import asyncio
import pathlib
import time
import detail.shell
import detail.ip
import detail.netns
import detail.rely_tunnel
import detail.iperf_shell
def script_path():
return pathlib.Path(__file__).resolve().parent
async def monitor(log):
while True:
awai... |
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
from torch import autograd
EPSILON = 1e-16
class Critic(nn.Module):
def __init__(self, image_size=100, image_channel_size=3, channel_size=64):
# configurations
super().__init__()
self.... |
# Copyright All Rights Reserved.
"""Generates data for training/validation and save it to disk."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import multiprocessing
import os
import yaml
from absl import app
from absl import flags
fro... |
"""Evaluation function handler for sequential or cascaded."""
import numpy as np
import sys
import torch
import torch.nn.functional as F
class SequentialEvalLoop:
"""Evaluation loop for sequential model."""
def __init__(
self,
num_classes,
keep_logits=False,
keep_embeddings=False,
... |
import pickle
import numpy as np
from tqdm.auto import tqdm
import moses
from moses import CharVocab
class NGram:
def __init__(self, max_context_len=10, verbose=False):
self.max_context_len = max_context_len
self._dict = dict()
self.vocab = None
self.default_probs = None
se... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 30 15:08:31 2021
@author: Korean_Crimson
"""
#pylint: disable=line-too-long
import sys
import ctypes
import tkinter as tk
class Tk(tk.Tk):
"""Extends tk.Tk as root of the app for better row, col and icon API"""
def __init__(self):
super().__init__()
... |
#!/usr/bin/env python3
import collections
import curses
import math
import os
import random
import time
from pynput import keyboard
def get_winsize():
rows, columns = os.popen("stty size", "r").read().split()
return int(rows), int(columns)
FRAME_RATE = 60 # fps
LEVEL_WIDTH = 100
LEVEL_HEIGHT = 30
PRESSE... |
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
import os
import sys
from .fields import *
from statistics import median
# Models
ehr = 'ehr'
ehr_questions = 'ehr_questions'
#EHR Questions
ehr_q1 = 'ehr_q1'
# ehr_q2 = 'ehr_q2'
# ehr_q3 = 'ehr_q3'
# ehr_q4 = 'ehr_q4'
# ehr_q5 = 'ehr_q5'
# ehr_q6a = 'ehr_q6a'
# ehr_q6b = 'ehr_q6b'
# ehr_q7 =... |
import matplotlib.pyplot as plt
import numpy as np
import torch
import cv2
def draw_figure(fig):
fig.canvas.draw()
fig.canvas.flush_events()
plt.pause(0.001)
def show_tensor(a: torch.Tensor, fig_num = None, title = None, range=(None, None), ax=None):
"""Display a 2D tensor.
args:
... |
import numpy as np
from africanus.util.numba import jit
@jit(nogil=True, nopython=True, cache=True)
def fac(x):
if x < 0:
raise ValueError("Factorial input is negative.")
if x == 0:
return 1
factorial = 1
for i in range(1, x + 1):
factorial *= i
return factorial
@jit(no... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019~2999 - Cologler <<EMAIL>>
# ----------
#
# ----------
import subprocess
from contextlib import contextmanager
from typing import List, Tuple
from click import Context, get_current_context, echo, style
import fsoopify
import execode
from anyioc import ServiceProvider
from... |
# Copyright (c) 2007, <NAME> <<EMAIL>>
# 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 copyright notice,
# this list of condition... |
'''
Script to infer labels on data from a pre-saved keras model, using folder-structured testing data
'''
import argparse
import os
import csv
import PIL
from PIL import Image
import numpy as np
import cv2
import tensorflow
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.mod... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
All o... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`<NAME> (<EMAIL>)`
:copyright: © 2017 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
saltpylint.thirdparty
~~~~~~~~~~~~~~~~~~~~~
Checks all imports against a list of known and allowed 3rd... |
import sqlite3
import os
MAX_DEPTH_CHAIN = 10
P_INSTANCE_OF = 31
P_SUBCLASS = 279
MAX_ITEMS_CACHE = 100000
conn = None
entity_cache = {}
chain_cache = {}
DB_DEFAULT_PATH = os.path.abspath(__file__ + '/../../data_spacy_entity_linker/wikidb_filtered.db')
wikidata_instance = None
def get_wikidata_instance():
gl... |
import sys, getopt
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
import ICA_support_lib as sup
import ICA_coupling_pattern as cp
import ICA_ising as ising
class astro_pp_ising_creator:
def __init__(self):
self.main_Path = os.getcwd()
self.ising_model_Path... |
"""LoanScan Model"""
import argparse
import logging
from typing import Any, Dict
import pandas as pd
import requests
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import get_user_agent, log_and_raise
logger = logging.getLogger(__name__)
api_url = "https://api.loanscan.io"
P... |
from functools import partial
from itertools import groupby
from math import (ceil,
log)
from typing import (Any,
Callable,
Iterable,
Sequence,
Tuple,
TypeVar,
Union)
from ground.ba... |
# Copyright (c) 2021 Aiven, Helsinki, Finland. https://aiven.io/
from collections import deque
from journalpump.journalpump import JournalPump
from journalpump.senders import WebsocketSender
import asyncio
import json
import logging
import snappy
import threading
import time
import websockets
class WebsocketMockServ... |
# Copyright (c) 2022, ETH Zurich and UNC Chapel Hill.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this ... |
# -*- coding: utf-8 -*-
# from django.db import transaction
import django
from datetime import datetime
from django.utils.encoding import force_unicode
from adminactions import api
from django.contrib import messages
from django.contrib.admin import helpers
from django import forms
from django.forms import TextInput, H... |
import numpy as np
import matplotlib.pyplot as plt
import cvxpy as cvx
from scipy.linalg import circulant
from scipy.stats import norm
import seaborn as sns
import pandas as pd
from scipy.integrate import solve_ivp
from scipy.spatial.distance import cdist
def BinaryRandomMatrix(S,M,p):
r = np.random.rand(S,M)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import json
import logging
from datetime import datetime
from twitter import TwitterSession
class Cache():
def __init__(self, path):
self.path = path
if not os.path.exists(path):
os.mkdir(path)
if not os.path.is... |
import copy
import itertools
import json
from collections import defaultdict
from itertools import chain
from typing import DefaultDict, FrozenSet, NamedTuple, Tuple
import graphviz
Symbol = str
State = str
StateSet = FrozenSet[State]
def shrink(transitions):
return {k: v for k, v in transitions.items() if v}
... |
"""
Content Provider: StockSnap
ETL Process: Use the API to identify all CC-licensed images.
Output: TSV file containing the image, the respective
meta-data.
Notes: https://stocksnap.io/api/
No rate limit specified. No ... |
import unittest
import numpy as np
import scipy.sparse as sp
from multimodal.lib.array_utils import normalize_features
from multimodal.evaluation import (evaluate_label_reco,
evaluate_NN_label,
chose_examples)
class TestLabelEvaluation(unittest.T... |
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from datetime import datetime, timedelta
from .models import StaffMemberListPluginModel, Lo... |
import cv2
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Cropping2D
from keras.layers import Convolution2D, Conv2D
fr... |
"""Code is from the url listed below, modified to avoid warnings and improve
readability.
URL: https://github.com/juntang-zhuang/Adabelief-Optimizer/blob
/update_0.2.0/PyTorch_Experiments/imagenet/AdaBelief.py
"""
import math
import torch
from torch.optim.optimizer import Optimizer
def zeros_like(tenso... |
# ----------------------------------------------------------------------
# Copyright (c) 2013-2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation... |
# Copyright (c) 2018, The Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, thi... |
from config import args
from modules import *
import tensorflow as tf
def forward_pass(sources, targets, params, reuse=False):
with tf.variable_scope('forward_pass', reuse=reuse):
pos_enc = _get_position_encoder()
# ENCODER
en_masks = tf.sign(sources)
with tf.variable_scope('... |
from traitlets.config import Configurable
from traitlets import (
Int,
List,
Unicode,
)
import numpy as np
import logging
from event.arguments.prepare.event_vocab import TypedEventVocab
from event.arguments.prepare.event_vocab import EmbbedingVocab
from event.arguments.prepare.hash_cloze_data import HashPar... |
# -*- coding: utf-8 -*-
import os
import re
import codecs
import cPickle as pickle
from const import *
from glob import iglob
from itertools import chain
from datetime import datetime
from configparser import SafeConfigParser
ROOT = os.path.abspath('.') + '/'
USER = ROOT + 'user.backup/'
SERIES = USER + 'series/'
SE... |
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torchtext import data, data... |
def _project():
return {
"title": "Demo Project",
"code": "DEMO",
"counts": {
"cases": 10,
"suites": 3,
"milestones": 0,
"runs": {"total": 1, "active": 1},
"defects": {"total": 0, "open": 0},
},
}
def _test_case():
... |
# type:ignore[overload]
from typing import Any, Callable, Dict, Optional, overload, Type
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa
from cryptography.hazmat.primitives.asymmetric import utils
from cryptography.h... |
#!/usr/bin/python
"""This file contains code for use with "Think Bayes",
by <NAME>, available from greenteapress.com
Copyright 2013 <NAME>
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
1, Original link -
refer to https://github.com/AllenDowney/ThinkBayes/blob/master/code/redline_data.py
2, As http://devel... |
"""An implementation of CDSSM (CLSM) model."""
import typing
import torch
from torch import nn
import torch.nn.functional as F
from mzcn import preprocessors
from mzcn.engine.base_model import BaseModel
from mzcn.engine.param import Param
from mzcn.engine.param_table import ParamTable
from mzcn.engine.base_callback i... |
"""
This script aims to pretty plot s params obtained from VSA or Python scikit-rf
References:
- https://scikit-rf.readthedocs.io
"""
import argparse
import logging
import os
import sys
from typing import List, Tuple
import matplotlib.pyplot as plt
import skrf as rf
from matplotlib import ticker
from stouchtoo... |
import cupy as np
# 准备四叉树索引
s1 = slice(0,None,2), slice(0,None,2)
s2 = slice(0,None,2), slice(1,None,2)
s3 = slice(1,None,2), slice(0,None,2)
s4 = slice(1,None,2), slice(1,None,2)
ss = s1, s2, s3, s4
# 保证连续
def dilation(img, layer):
msk = img>=layer
buf = msk.copy()
buf[1:] &= msk[:-1]
buf[:-1] &= msk... |
from __future__ import unicode_literals, print_function
from kivy.uix.label import Label
from kivy.event import EventDispatcher
from flat_kivy.uix.flatlabel import FlatLabel
from kivy.clock import Clock
from kivy.properties import ListProperty
import operator
def get_style(style):
if style is not None:
tr... |
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Dict, List
import matplotlib.pyplot as plt
import numpy as np
from myfitnesspal.exercise import Exercise
from myfitnesspal.meal import Meal
from . import styles
@dataclass
class MaterializedD... |
#! /usr/bin/env python3
"""
function collection for handling different versions of log files
"""
from typing import List, Tuple
from pyulog import ULog
from ecl_ekf_analysis.log_processing.custom_exceptions import PreconditionError
def get_output_tracking_error_message(ulog: ULog) -> str:
"""
return the nam... |
from sklearn.neighbors import KDTree
from os.path import join, exists, dirname, abspath
import numpy as np
import pandas as pd
import os, sys, glob, pickle
import nibabel as nib
from multiprocessing import Process
import concurrent.futures
from tqdm import tqdm
from scipy import ndimage
import argparse
BASE_DIR = dir... |
import sys
import random
import bisect
import logging
from . import event
from . import fight
from . import terrains
from . import props
from . import world
class Goals(list):
def __init__(self, person, *args, **kw):
super().__init__(*args, **kw)
self.person = person
def __contains__(self, it... |
from fractions import Fraction
import unittest
# import pytest
from claptrap.backports import choices, suppress
# class SomeError(Exception):
# '''some error'''
# class SomeOtherError(Exception):
# '''some other error'''
# def test_suppress_normal():
# with backports.suppress(SomeError):
# r... |
"""
Written in Python 3.5
The purpose of this script is to take a PubMed XML file as input, parse out the MeSH Descriptors and Qualifiers, and count how many of each there is. Output is a tab-delimited text file."""
import xml.etree.ElementTree as ET
def xml_prompt():
"""Prompts user for PubMed XML file."""
... |
import os
from datetime import datetime
from enum import Enum
from mongoengine import (
DateTimeField,
Document,
DoesNotExist,
IntField,
ListField,
ReferenceField,
StringField,
signals,
)
from stpmex.resources import Orden
from speid import STP_EMPRESA
from speid.exc import MalformedOr... |
import re
from stdnum import verhoeff
from stdnum.util import clean
from django.core.exceptions import ValidationError
def validate_name(value):
""" Validates name of any entity """
if not value.replace(" ", "").isalpha():
raise ValidationError(
'%(value)s is not a valid name. It should co... |
# -*- coding: utf-8 -*-
"""
Created on 2020-01-07 13:13
@author: a002028
"""
import datetime
try:
import pyodbc
except ModuleNotFoundError:
print('Could not import pyodbc')
import json
import pandas as pd
def get_pyodbc_engine(server):
with open('//winfs-proj/proj/havgem/SHARKtools/settings_info/srv_inf... |
"""
Solver D3Q6^4 for a Poiseuille flow
d_t(p) + d_x(ux) + d_y(uy) + d_z(uz)= 0
d_t(ux) + d_x(ux^2) + d_y(ux*uy) + d_z(ux*uz) + d_x(p) = mu (d_xx+d_yy+d_zz)(ux)
d_t(uy) + d_x(ux*uy) + d_y(uy^2) + d_z(uy*uz) + d_y(p) = mu (d_xx+d_yy+d_zz)(uy)
d_t(uz) + d_x(ux*uz) + d_y(uy*uz) + d_z(uz^2) + d_z(p) = mu (d_xx+d_y... |
import numpy as np
#initalize parameters
#layer_dims = katmanların nöron sayılarını tutan liste (özellikler dahil)
def initilaize_parameters(layer_dims):
np.random.seed(1)
parameters = {}
L = len(layer_dims)
for l in range(1,L):
#np.sqrt(layer_dims[l-1]) sayesinde W parametresini daha küçük sa... |
import pandas as pd
import scipy as sp
import numpy as np
import warnings
class PartitionExplainer():
def __init__(self, model, masker, clustering):
""" Uses the Partition SHAP method to explain the output of any function.
Partition SHAP computes Shapley values recursively through a hierarchy... |
# vim: expandtab:ts=4:sw=4
import numpy as np
import cv2
def crop_to_shape(images, patch_shape):
"""Crop images to desired shape, respecting the target aspect ratio.
Parameters
----------
images : List[ndarray]
A list of images in BGR format (dtype np.uint8)
patch_shape : (int, int)
... |
import os
import time
import multiprocessing
import heapq
from coilutils.experiment_schedule import get_gpu_resources, allocate_gpu_resources, \
mount_experiment_heap
from coilutils.general import create_exp_path, create_log_folder, erase_wrong_plotting_summaries, erase_validations
from logger import printer, moni... |
import json
import os
import shlex
import shutil
import subprocess
import tarfile
import glob
from pathlib import Path
from typing import List
import wget
from pesto.cli import PROCESSING_FACTORY_PATH
from pesto.cli.core.build_config import BuildConfig
from pesto.cli.core.config_loader import ConfigLoader
from pesto.... |
# encoding: utf-8
import os
import re
import time
import datetime
import mimetypes
import locale
try:
import chardet
except ImportError:
chardet = None
from pygments import highlight
from pygments.lexers import get_lexer_for_filename, guess_lexer, ClassNotFound, TextLexer
from pygments.formatters import HtmlFo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.