text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
#
# utils.py
"""
Utility functions.
"""
#
# Copyright © 2020 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including with... |
"""
##########################
marketsight.exceptions
##########################
Implements the exceptions that can be raised by the **MarketSight API Library**.
"""
from typing import Optional
from validator_collection import validators
from marketsight._compat import json
class MarketSightError(Exception):
"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Pre/Post Processing for createstubs.py"""
import argparse
import itertools
import re
import sys
from optparse import Values
from pathlib import Path
# Pyminifier Dep
token_utils = None
minification = None
try:
from pyminifier import token_utils, minification
except... |
# -*- coding: utf-8 -*-
import math
from typing import Union
import pandas as pd
from sqlalchemy import exists, and_, func
from sqlalchemy.orm import Query
from zvt.domain import SecurityType, Stock, Index, ReportPeriod, StoreCategory, \
StockIndex
from zvt.domain import get_db_session, CompanyType, TradingLevel... |
import os
import sys
from asyncio import StreamReader
from typing import Dict, List
import configargparse
from core_service import Service, requirements, listener
from eth_account import Account
from sarafan.bundle.bundle import ContentBundle
from sarafan.contract import ContractService
from sarafan.contract.announce... |
from abc import ABC, abstractmethod
from bson.objectid import ObjectId
from typing import List, Set, Dict, Iterable, Optional, TypeVar
from datacentric.platform.storage.data_set_flags import DataSetFlags
from datacentric.platform.storage.db_name import DbNameKey
from datacentric.types.record import RootRecord, TypedKe... |
#from gen_utils import *
import squeezedet as nn
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
import pickle
import random
IOU_THRESH = 0.5
NN_PROB_THRESH = 0.5
def get_area_cap(b1, b2):
x1_c, y1_c, l1, w1 = b1
x2_c, y2_c, l2, w2 = b2
lef... |
#!/usr/bin/env python3
import re
import string
# Indices
# =======
# `well`
# A string naming a well, e.g. "A1" or "A01". Note that columns count from
# 1. Rows beyond "Z" can be specified using multiple letters, e.g. "AA".
#
# `well0`
# The same as `well`, but with the column numbers padded with leading z... |
import numpy as np
def img2col_index(x_shape, k_size, stride=1):
in_c, in_h, in_w = x_shape
out_h, out_w = (in_h - k_size) // stride + 1, (in_w - k_size) // stride + 1
n_rows = out_h*out_w
c_idices = np.tile(np.repeat(np.arange(in_c), k_size*k_size), (n_rows, 1))
h_off_set = np.repeat(np.arange(0, in_h - k... |
# ---------------------------------------------------------------------
# Project "Track 3D-Objects Over Time"
# Copyright (C) 2020, Dr. <NAME> / Dr. <NAME>.
#
# Purpose of this file : Process the point-cloud and prepare it for object detection
#
# You should have received a copy of the Udacity license together with th... |
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as d... |
"""
MIT License
Copyright (c) 2019 RookiePC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Written by feymanpriv
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn i... |
"""
Derived from: https://github.com/ry/tensorflow-resnet
"""
import tensorflow as tf
import numpy as np
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.training import moving_averages
NUM_BLOCKS = {
50: [3, 4, 6, 3],
101: [3, 4, 23, 3],
152: [3, 8, 36, 3]
}
CONV_WEIGHT_DECAY = 0... |
from collections import defaultdict
import logging
from functools import reduce
from math import gcd
import pandas
from kf_lib_data_ingest.common.concept_schema import concept_set
from kf_lib_data_ingest.common.misc import clean_up_df
from kf_lib_data_ingest.common.type_safety import (
assert_safe_type,
is_fu... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import datetime
import os
import zipfile
from ly_test_tools.image.screenshot_compare_qssim import qssim as com... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Implements several popular block and stream ciphers.
"""
import abc
from typing import (
Any,
ByteString,
ClassVar,
Iterable,
Optional,
Tuple,
Type,
)
from refinery.lib.crypto import (
CipherObjectFactory,
CipherInterface,
)
from re... |
from datetime import datetime
from unittest import TestCase
from hades_logs.parsing import RadiusLogEntry, parse_vlan, attrlist_to_dict, \
ParsingError, reduce_to_first_occurrence
class UnauthTrafficEntryTestCase(TestCase):
def setUp(self):
super().setUp()
self.timestamp = 1501623826.391414
... |
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
import logging
import numpy as np
import copy
from typing import List, Optional
from autoconf import cached_property
from autoarray.dataset.abstract_dataset import AbstractWTilde
from autoarray.dataset.abstract_dataset import AbstractSettingsDataset
from autoarray.dataset.abstract_dataset import AbstractData... |
"""Calculate forces for individuals and groups"""
import re
from abc import ABC, abstractmethod
import numpy as np
from pysocialforce.potentials import PedPedPotential, PedSpacePotential
from pysocialforce.fieldofview import FieldOfView
from pysocialforce.utils import Config, stateutils, logger
def camel_to_snake(c... |
#!/usr/bin/env python
"""Small script to send notifications for song change in Radio paradise.
config is stored in ~/.config/paradise_player/config.cfg
System requirements:
* notify-send
* ffplay or vlc or mplayer...
"""
import argparse
import configparser
import logging
import os
import subprocess
import time
import... |
import os
import shutil
import pickle
import jsonlines
import json
import csv
import numpy as np
from operator import itemgetter
from itertools import groupby
from preprocessing.stat_corpus import count_doc, count_words, plot_hist, analyze_text_passages
from preprocessing.dpr_preprocessing import corpus_to_ct... |
# Copyright 2018 The TensorFlow 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 applica... |
""" Web runtime based on a chrome/chromium.
It is possible to make a chrome app with a custom icon on Windows (because
it uses the (initial) favicon of the page) and OS X (because how apps work).
I tried hard to make it work on Linux via a .desktop file, but the problem
is that Chome explicitly sets its icon (Chromium... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. 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... |
# Reminders
import random, sqlite3, time
from collections import namedtuple
from datetime import timedelta
from dateutil.relativedelta import *
from pytz import timezone
import util
from user import User
OK = ["Ok!", "Gotcha.", "Sure thing!", "Alright.", "You bet.", "Got it."]
INTERVAL_MINUTE = "minute"
INTERVAL_HO... |
from collections import defaultdict
from multiprocessing import Pool
from os.path import basename, dirname, splitext, join, isdir, isfile, getmtime
from os import utime, walk
from io import BytesIO
import itertools
import hashlib
import lxml.etree as etree
from time import time as unixtime
from tqdm import t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 14 12:04:29 2021
@author: nmei
"""
import os
import numpy as np
from glob import glob
from tqdm import tqdm
from nibabel import load as load_fmri
import torch
from torch import nn,no_grad
from torch.utils import data
from torch.nn ... |
# -*- coding: utf-8 -*-
"""
oss2.xml_utils
~~~~~~~~~~~~~~
XML处理相关。
主要包括两类接口:
- parse_开头的函数:用来解析服务器端返回的XML
- to_开头的函数:用来生成发往服务器端的XML
"""
import xml.etree.ElementTree as ElementTree
from .models import (SimplifiedObjectInfo,
SimplifiedBucketInfo,
PartInfo,
... |
__author__ = '<NAME>, <NAME>'
import math
import csv
import numpy as np
class NetworkDevice:
"""Network device, needed for inheritance"""
def __init__(self):
self.x = 0
self.y = 0
class UE(NetworkDevice):
"""UE"""
def __init__(self):
self.ID = 0
self.connectedToBS = 0
... |
import numpy as np
from astropy.io import ascii
import astropy.io.fits as pf
def read_spec(specFiles, errors=True, negtonan=False, linear=False, ext=0, verbose=True, header=False):
'''
(by <NAME> |uacute| |ntilde| ez, <NAME>)
Read spectral data from fits or ascii files. It returns a list of numpy arrays w... |
from models.common import DeclEnum
class GroupRoundType(DeclEnum):
"""
Enumerated names of rounds in group stages of football competitions.
"""
group_stage = "Group Stage", "Group Stage"
first_round = "First Round", "First Round"
second_round = "Second Round", "Second Round"
third_round = ... |
import argparse
import copy
import math
import sys
import os
import time
import pdb
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
from tqdm import tqdm
from utils import AverageMeter
import t... |
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from pathlib import Path
sns.set(style="whitegrid", font_scale=1.1)
def plot_force_space():
fig = plt.figure(figsize=(7, 7), tight_layout=True, constrained_layout=False)
ax = plt.axes(projection="3d", proj_type="orth... |
import h5py
import numpy as np
import matplotlib.pylab as plt
import pandas as pd
import os
from matplotlib import ticker
from heat_flux_adi import simulate_adi_temp
from scipy.signal import savgol_filter
import matplotlib as mpl
import json
import ir_thermography.thermometry as irt
import re
import shutil
import pla... |
# coding=utf-8
# Copyright 2022 <NAME>
# 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
#
# Unl... |
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME> and <NAME>
# --------------------------------------------------------
# Edited by <NAME>, UNC-<NAME>
import numpy as np
import yaml
fr... |
from avro.schema import (
ARRAY, ArraySchema, BOOLEAN, BYTES, DOUBLE, ENUM, EnumSchema, Field, FIXED, FixedSchema, FLOAT, INT, LONG, MAP,
MapSchema, NamedSchema, Names, NULL, RECORD, RecordSchema, Schema, SchemaFromJSONData, STRING, UNION, UnionSchema
)
from copy import copy
from enum import Enum
from typing im... |
import math
import pickle as pickle
from settings import *
import sys
import time
class Sandbox(object):
def __init__(self, width, height):
self.height, self.width = height, width
self.grid = self.generate_empty_grid()
# using sets seems to work just as fast as lists here. The big benefit is that you can che... |
import math
import loguru
import msgpack
import json
from abc import ABC, abstractmethod
from loguru._get_frame import get_frame
from jumpscale.core.exceptions import Value
from jumpscale.loader import j
LEVELS = {
10: "DEBUG",
20: "INFO",
30: "WARNING",
40: "ERROR",
50: "CRITICAL",
}
# init i... |
import yaml
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser(description='Detect Cars in Image')
parser.add_argument('file', metavar='FILE', help='file path to run detection on')
parser.add_argument('fyaml', metavar='FILE', help='file path of yml')
args = parser.parse_args()
# ... |
"""A set of reward utilities written by the authors of dm_control"""
from multiprocessing import Value
import numpy as np
# The value returned by tolerance() at `margin` distance from `bounds` interval.
_DEFAULT_VALUE_AT_MARGIN = 0.1
def _sigmoids(x, value_at_1, sigmoid):
"""Returns 1 when `x` == 0, between 0 a... |
import os
import torch
from tqdm import tqdm
from copy import deepcopy
from .early_stop import EarlyStopping
from .checkpoint import Checkpoint
from metric.metric import Metric, MetricList
from torch.optim.lr_scheduler import ReduceLROnPlateau
class Trainer:
def __init__(
self,
model,
num_... |
"""
Adapted from pgmpy library: https://github.com/pgmpy/pgmpy
A collection of methods for sampling from continuous models
-- <EMAIL>
"""
# pylint: disable=invalid-name
# pylint: disable=no-self-use
# pylint: disable=arguments-differ
from __future__ import division
from math import sqrt
import numpy as np
fro... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# Import all needed Python packages and functions
from azureml.core import Run, Dataset, Workspace
from azureml.core.authentication import InteractiveLoginAuthentication
from azureml.core.run import _OfflineRun
impor... |
"""Test the accuracy of the MCMC kernels."""
import functools
import itertools
import chex
import jax
import jax.numpy as jnp
import jax.scipy.stats as stats
import numpy as np
from absl.testing import absltest, parameterized
import blackjax.diagnostics as diagnostics
import blackjax.hmc as hmc
import blackjax.nuts a... |
import platform
import time
import numpy as np
import scipy.sparse
from tensorpack import PredictConfig, get_model_loader, OfflinePredictor
from config import config as cfg
from tracking.argmax_tracker import PrecomputingReferenceTracker
from tracking.util import resize_and_clip_boxes, generate_colors, xyxy_to_cxcywh_... |
# Visualizes the rendered audio using Dynamic FFT
# We use a 31-band visualizer, though the last two frequency bands are not shown
# The audio file is rendered in AudioRender.py
import pygame
from pygame import mixer
import AudioRender as Audio
import time
import numpy as np
import math
import random
from Interpolat... |
from typing import List, Mapping, Tuple
import typing
import math
import collections
import itertools
import attr
import numpy as np
import msprime
import demes
def to_msprime(graph: demes.Graph):
"""
Convert a demes graph to an msprime demography.
:param graph: the demes graph to convert.
:type gr... |
# Copyright 2017 The TensorFlow 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 applica... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
from threading import Thread, Timer
from qxsite.settings import ROOM_TTL
import channels.layers
from asgiref.sync import async_to_sync
from django.core.cache import cache
from enum import Enum, unique
import asyncio
import random
import math
from asyncio import get_event_loop
from cardgame.log import log
from cardgame.... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 3 18:28:30 2019
@author: Any
"""
import pomegranate as pg
import pandas as pd
import numpy as np
from scipy.special import erfinv
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
d... |
import functools
import os
from enum import Enum, unique
from typing import Any, Callable, Dict, List, Optional
import unicorn
import cemu.core
import cemu.utils
from cemu.log import dbg, error, info, log
from .arch import (Syntax, is_aarch64, is_arm, is_arm_thumb, is_mips,
is_mips64, is_ppc, is_s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Utilities for dealing with inventory objects.
:copyright:
<NAME> (<EMAIL>), 2015
:license:
BSD 3-Clause ("BSD New" or "BSD Simplified")
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import coll... |
"""ML-ENSEMBLE
:author: <NAME>
:copyright: 2017-2018
:licence: MIT
Correlation plots.
"""
from __future__ import division, print_function
import numpy as np
from scipy.stats import pearsonr
import warnings
try:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from seaborn impor... |
from __future__ import print_function
import os
import numpy as np
import torch
import pickle
from datasketch import MinHashLSHForest
from datasketch import MinHash
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from scipy.spatial.distance import pdist, cdist, squareform
... |
from spacy.attrs import ORTH
from spacy import displacy
import webcolors
from pathlib import Path
from utilities_cbc import circle_abbrev_from_path
from spacy.matcher import PhraseMatcher
from spacy.lang.en import English
from spacy.tokens import Span
from spacy.util import filter_spans
def build_phrase_matcher(nlp,... |
from collections.abc import Iterable
import os
from random import randint
from astropy.io import fits
import cv2
from lacosmic import lacosmic
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image
from scipy import interpolate
from skimage import filters
from skimage.morphology import disk
fro... |
import numpy as np
import scipy
import matplotlib.pyplot as plt
import statsmodels.api as sm
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import matplotlib.gridspec as gridspec
from hydroDL import utils
import string
import os
# manually add package
# os.environ[
# 'PR... |
import plotly.graph_objects as go
import numpy as np
import qcelemental as qcel
import glob
from ..figure.layouts import surface_materials
def get_volume(cube, spacing, origin, iso, opacity, color):
x, y, z = np.mgrid[:cube.shape[0], :cube.shape[1], :cube.shape[2]]
x_r = x * spacing[0] + origin[0]
y_r =... |
import itertools
import time
from dataclasses import dataclass, asdict
from typing import List, Dict, Optional, Tuple
import numpy as np
from geneticalgorithm2 import geneticalgorithm2 as ga, geneticalgorithm2
from hwmapping.calculations import sum_fet, calculate_requirements, calculate_diff_entropy
from hwmapping.de... |
#!/usr/bin/python3
# Copyright 2019 Adobe. All rights reserved.
# This file is licensed to you 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 requir... |
import math
import numpy as np
import torch
import torch.nn as nn
from .extra_layers import WeightDropout, RNNDropout, EmbeddingDropout
class GradReverse(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
r... |
# Copyright 2020 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import os
import sys
import numpy as np
import pandas as pd
import cv2
import matplotlib
import matplotlib.pyplot as plt
from config import Config
import utils
import model as modellib
import visualize
from model import log
from tqdm import tqdm
from skimage.io import imread, imshow, imread_collection, concatenate_ima... |
# Copyright 2021 MosaicML. All Rights Reserved.
"""Engine is a coordinator for running algorithms and resolving ordering conflicts among them for composition.
.. currentmodule:: composer
The order in which algorithms are run matters significantly during composition. For example,
:class:`~.SelectiveBackprop` algorith... |
#!/usr/bin/env python3
import socket
import re
import threading
import time
import select
import subprocess
from _thread import *
def encrypt(text,s):
result = ""
# traverse text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters
if (char.isupp... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import numpy as np
import numpy.random as npr
import scipy as sc
from scipy import stats
from sds.models import RecurrentAutoRegressiveHiddenMarkovModel
from sds.utils.envs import sample_env
from joblib import Parallel, delayed
import multiprocessing
nb_cores = multiprocessing.cpu_count()
def create_job(train_obs... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import os
import requests
from requests_ntlm import HttpNtlmAuth
import json
import subprocess
import time
import threading
import random
user = 'fetia'
with open(r'C:\Users\fetia\pwd','r') as f:
pwd=f.read()
vc_maps={'eu1':'nextmsra',
'eu2':'gfs',
'sc3':'resrchprojvc3',
'wu2... |
import numpy as np
from mpi4py import MPI
import matplotlib.pyplot as plt
from pySDC.helpers.stats_helper import filter_stats, sort_stats
from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right
from pySDC.implementations.collocation_classes.gauss_lobatto import CollGaussLobatto
fro... |
# Copyright 2019 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... |
#!/usr/bin/env python
import os
import sys
import time
import multiprocessing
try:
from scripts import my_utils
except ImportError:
import my_utils
tab = '\t'
endl = '\n'
arg = sys.argv[1:]
usage = 'python ' + __file__ + ' ' + '<input_bam_file> <out_dir> <out_del_call_file> <n_threads> <ref_fasta> <fermiki... |
#!/usr/bin/env python
"""A module for working with extended file stat collection.
This module will try to collect as detailed stat information as possible
depending on platform capabilities (e.g. on Linux it will use `statx` [1] call.
[1]: https://www.man7.org/linux/man-pages/man2/statx.2.html
"""
import ctypes
impor... |
from datetime import datetime
from typing import Union, Any
import pandas
import pyttman
from mongoengine import QuerySet
from pyttman.core.communication.models.containers import Message, Reply, \
ReplyStream
from pyttman.core.intent import Intent
from pyttman.core.parsing import identifiers
from pyttman.core.pars... |
"""Main module."""
import json
from logging import error
def clean_path(directory_path) -> str:
"""
Will ensure the path supplied DOES end with / so we can join to a filename without worry
"""
if str(directory_path):
if directory_path[-1:] != "/":
directory_path = directory_p... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
from xarray import Dataset, DataArray, Variable
from xarray.core import indexing
from . import TestCase, ReturnItem
class TestIndexers(TestCase):
def set_to_zero(sel... |
import pygame
import assistant as assistant
import numpy as np
import random
WIDTH = 900
HEIGHT = 900
#pos is relating to board so [1,1]penis
#pix is relating to window in pixels so [30,30]
class Board:
def __init__(self,width,height,segment):
self.pixwidth = width#300#line 11 to 16 is taking how big the w... |
#!/usr/bin/env python
# _*_ coding: UTF-8 _*_
import math
import torch
import torch.nn as nn
from .network_common_module import variable_activate, DownSample2d, expend_params
class HPResNet2D(nn.Module):
def __init__(
self, block_num=2, in_channels=64, hidden_channels=64, split_num=8, kernel_size=3, s... |
#!/usr/bin/python
#
# Copyright (c) 2021 <NAME>(@techcon65)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: azure_rm_privatednszonelink
version_added: "... |
import gym
from scipy.interpolate import griddata
from scipy.stats import multivariate_normal
import time
import math
import random
import numpy as np
import matplotlib.pyplot as plt
class BeliefSpace():
OBSERVATION_CONFIDENCES = 0.95
ENTROPY_PER_SECOND = 0.003
def __init__(self, xdim, ydim):
x,y =... |
#!/usr/bin/env python3
"""
Part of speech tagging using sklearn CRF suite.
Credit to: https://towardsdatascience.com/pos-tagging-using-crfs-ea430c5fb78b
"""
import argparse
import logging
import pickle
import string
import typing
from pathlib import Path
import sklearn_crfsuite
from sklearn_crfsuite import metrics
_... |
import os
from pathlib import Path
import numpy as np
import pytest
from uncertainties import ufloat
import openmc
from openmc.stats import Discrete, Point
from tests import cdtemp
@pytest.fixture
def model():
openmc.reset_auto_ids()
model = openmc.Model()
# materials (M4 steel alloy)
m4 = openmc.M... |
def run_samtools(samfile, cleanup=False):
# samfile is full path to sam file
print('Starting samtools converting sam to sorted indexed bam')
import os
import subprocess
path, sam = os.path.split(samfile)
bamfile = '.'.join(samfile.split('.')[:-1] + ['bam'])
sortbamfile = '.'.join(sa... |
#!/usr/bin/env python2.7
import os
import argparse
import git
import sys
from datetime import datetime
import re
def GetVersion(backupFile, label=''):
"""As getLongVersion(), but only return the leading *.*.* value."""
raw = GetLongVersion(backupFile, label)
# Just return the first 3 parts of the ver... |
#
# Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
# This module is free software, and you may redistribute it and/or modify
# under the same terms as Python, so long as this copyright message and
# disclaimer are retained in their original form.
#
# IN NO EVENT SHALL BIZAR SOFTWARE PTY LT... |
"""Component to embed TP-Link smart home devices."""
from __future__ import annotations
from datetime import timedelta
import logging
import time
from typing import Any
from pyHS100.smartdevice import SmartDevice, SmartDeviceException
from pyHS100.smartplug import SmartPlug
import voluptuous as vol
from homeassistan... |
import numpy as np
import pandas as pd
import seaborn as sns
import pickle
import warnings
from tqdm import tqdm
import os
from collections import defaultdict
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
pd.set_option('display.max_columns', 500)
warnings.filterwarnings('ignore')... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_outliers(ax, axr, ALR):
if ALR.with_y_errors:
x_out, y_out, err_y_out = ALR.x_outliers, ALR.y_outliers, ALR.err_y_outliers
else:
x_out, y_out = ALR.x_outliers, ALR.y_outliers
ax.plot(x_out, y_out, 'or',marker... |
"""
records.assessment.edx.numeric_response_records.py
"""
from dlkit.json_.osid.metadata import Metadata
from dlkit.json_.osid import objects as osid_objects
from dlkit.json_.id.objects import IdList
from dlkit.abstract_osid.osid.errors import IllegalState,\
InvalidArgument, NotFound
from .item_records import e... |
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QSizePolicy, QLabel, QListWidget, QListWidgetItem, QGridLayout, QSpinBox
from PyQt5.QtCore import QTimer, Qt, pyqtSlot, QObject, QPoint, QPointF, QRect, QRectF, QSize
from PyQt5.QtGui import QResizeEvent, QPixmap, QPainter, QPen, ... |
import datetime
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView, LogoutView
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redir... |
import os
from PIL import Image
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.mail import EmailMessage
from .choices import *
def user_directory_path(instance, filename):
return 'uploads/users/{0}/{1}'.format(instance.user.usernam... |
from collections import defaultdict
from shared.db_classes import TableDb, GeneralDb
import json
import time
ORACLE_FILE = 'oracle.db'
class KeyValue(TableDb):
table_name = 'key_value'
create_sql = 'create table {0} ( \
id integer primary key autoincrement, \
section varchar(255) not null, \
ke... |
"""
Copyright 2019 Software Reliability Lab, ETH Zurich
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 i... |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Custom loss functions."""
from __future__ import annotations
import warnings
from typing import Optional
import torch
from torch import Tensor
from torch.nn import functional as F
from composer.loss.utils import ensure_targets_one_... |
import io
import tarfile
import subprocess
import json
import re
import os
import termcolor
import progressbar
from pkg_resources import parse_version
import requests
from toposort import toposort_flatten
import ccr
from chaser import pacman, prompt
BUILD_DIR = "/tmp/chaser"
def get_source_files(args, workingdir=No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.