filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_21843
""" Prepares documentation and sets up a Jekyll project into which the documentation goes. Functions ========= add_frontmatter(file_name, title, makenew=False) Adds basic frontmatter to a MarkDown file that will be used in a Jekyll project. """ #def make_project def add_frontmatter(file_name, title, makenew=Fals...
the-stack_106_21844
from typing import cast, Dict, Set, Optional, Union from spec_random import SPEC_RANDOM from spec_basis import Rand, Kobj, KindSend, Lego, Syscall, Program, Executable from spec_pack import pack_int from spec_lego_simple import LegoSimple from spec_lego_pointer import LegoPointer from spec_lego_vector import RandVecto...
the-stack_106_21846
import unittest from itertools import combinations import json import mock import pytest import uuid from mlflow.protos.model_registry_pb2 import CreateRegisteredModel, \ UpdateRegisteredModel, DeleteRegisteredModel, ListRegisteredModels, \ GetRegisteredModel, GetLatestVersions, CreateModelVersion, UpdateMode...
the-stack_106_21847
import tensorflow as tf EMB_SIZE = 10 def gen_conv(batch_input, out_channels, kernel_size, a): # [batch, in_width, in_channels] => [batch, out_width, out_channels] initializer = tf.random_normal_initializer(0, 0.02) return tf.layers.conv1d(batch_input, out_channels, kernel_size=kernel_size, strides=1, pa...
the-stack_106_21848
''' Original Code: https://github.com/yysijie/st-gcn/blob/master/processor/io.py ''' #!/usr/bin/env python # pylint: disable=W0201 import sys import argparse import yaml import numpy as np # torch import torch import torch.nn as nn # torchlight import torchlight from torchlight import str2bool from torchlight import ...
the-stack_106_21850
import json from datetime import datetime import pandas as pd import scrapy class PlayerSpider(scrapy.Spider): # set the attributes for the spider name = "player" def __init__(self, **kwargs): """initialize the data""" super().__init__(**kwargs) # create player data frame ...
the-stack_106_21851
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # @Author : Bismarckkk # @Site : https://github.com/bismarckkk # @File : rosNode.py import sys import logging import cv2 import numpy as np import rospy from sensor_msgs.msg import Image from radar_msgs.msg import points, point, view_control from hp_limit_helper.m...
the-stack_106_21854
# Copyright (c) 2014 Olli Wang. All right reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
the-stack_106_21856
# 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...
the-stack_106_21857
"""Support for mobile_app push notifications.""" import asyncio import logging import async_timeout from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, ATTR_TITLE, ATTR_TITLE_DEFAULT, BaseNotificationService, ) from homeassistant.const import ( HTTP_ACCEPTED...
the-stack_106_21858
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # 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...
the-stack_106_21859
# coding: utf-8 # Like v2, and in contrast to v1, this version removes the cumprod from the forward pass # In addition, it uses a different conditional loss function compared to v2. # Here, the loss is computed as the average loss of the total samples, # instead of firstly averaging the cross entropy inside each tas...
the-stack_106_21864
from datetime import datetime, timedelta from time import sleep import requests import napalm from napalm.base.exceptions import NapalmException import yaml import socket import time import re MONITOR_INTERVAL = 15 DISCOVERY_INTERVAL = 300 def get_version(device, facts): if device["os"] == "iosxe": re_...
the-stack_106_21866
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0010_change_page_owner_to_null_on_delete'), ] operations ...
the-stack_106_21867
""" ================================ LASA Handwriting with ProMPs ================================ The LASA Handwriting dataset learned with ProMPs. The dataset consists of 2D handwriting motions. The first and third column of the plot represent demonstrations and the second and fourth column show the imitated ProMPs ...
the-stack_106_21868
import argparse import os from dataManipulation import * from utils import summary, summary_raw, get_support_from_mcmc from vbpi import VBPI from utils import namenum import time import torch import numpy as np import datetime import math parser = argparse.ArgumentParser() ######### Load arguments parser.add_argume...
the-stack_106_21869
#!/usr/bin/env python3 # ver 0.1 - coding python by Hyuntae Jung on 4/1/2018 import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='average files from .npy or text files which are the same size like (value, *)s' ) ## args parser.add_argument(...
the-stack_106_21870
#!/usr/local/bin/python3 """ Unicoder Version: 1.0.1 Copyright: 2019, Tony Smith (@smittytone) License: MIT (terms attached to this repo) """ ########################################################################## # Program library imports # ###########...
the-stack_106_21871
# PyChain Ledger ################################################################################ # You’ll make the following updates to the provided Python file for this # Challenge, which already contains the basic `PyChain` ledger structure that # you created throughout the module: # Step 1: Create a Record Data Cl...
the-stack_106_21872
from typing import Tuple, FrozenSet from pysmt.environment import Environment as PysmtEnv from pysmt.fnode import FNode import pysmt.typing as types from utils import symb_to_next from hint import Hint, Location def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, ...
the-stack_106_21874
#!/usr/bin/env python3 """tests for rummikub.py""" import os import re import random import string from subprocess import getstatusoutput prg = './rummikub.py' # -------------------------------------------------- def test_exists(): """exists""" assert os.path.isfile(prg) # -------------------------------...
the-stack_106_21876
# Copyright 2016 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Lease management for machines leased from the Machine Provider. Keeps a list of machine types which should be leased from the Machine Provider...
the-stack_106_21878
# -*- coding: utf-8 -*- from __future__ import unicode_literals import io from nslocalized import * def test_read_utf8_no_bom(): """Test that we can read UTF-8 strings files.""" data='''\ /* Test string */ "åéîøü" = "ÅÉÎØÜ"; '''.encode('utf-8') with io.BytesIO(data) as f: st = StringTable.read...
the-stack_106_21879
# # Copyright (c) 2021 Citrix 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
the-stack_106_21880
import numpy as np import math import time def fastLms(signalInput, desiredOutput, M, step=0.1, forgetness=0.9): blocks = int(math.ceil(1.0 * signalInput.size/M)) coefficients = np.random.rand(2*M) P = np.ones(2*M) totalOut = [] startTime = time.time() for i in range(blocks): des = de...
the-stack_106_21886
from typing import Type, Tuple, Union import numpy as np from autoconf import cached_property from .abstract import AbstractMessage from .transform import AbstractDensityTransform class TransformedMessage(AbstractMessage): _Message: Type[AbstractMessage] _transform: Union[AbstractDensityTransform, Type[Abst...
the-stack_106_21887
#!/usr/bin/env python # # Copyright (c) 2019, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information # see the Pycom Licence v1.0 document supplied with this file, or # available at https://www.pycom.io/opensource/licensing ...
the-stack_106_21890
# Copyright The PyTorch Lightning team. # # 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...
the-stack_106_21891
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ========================================================================= Program: Visualization Toolkit Module: TestNamedColorsIntegration.py Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www....
the-stack_106_21892
#!/usr/bin/python3 ''' --- Day 1: Report Repair --- After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you. The tropical island has its own currency and is entirely cash-only. The gold coins used there have a littl...
the-stack_106_21893
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 2 19:55:38 2018 @author: saschajecklin """ import sys sys.path.append("..") import random import numpy as np from collections import deque from keras.models import Model from keras.layers import Dense, Flatten, Input, Conv2D from keras.optimizers ...
the-stack_106_21895
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import given, assume import hypothesis.strategies as st from itertools import izip from caffe2.python import core, cnn import caffe2.python.hypothesis_test_util as hu class...
the-stack_106_21896
# 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...
the-stack_106_21899
import os from typing import Callable, Optional, Dict import dill from easypl.datasets.base import PathBaseDataset class DirDatasetClassification(PathBaseDataset): """ Dataset implementation for images in directory on disk (stored images paths in RAM). Require root_path/.../image_path structure. Att...
the-stack_106_21900
# Calculate weignted average of coins from coinmarketcap.com from requests import Request, Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects import json from influxdb import InfluxDBClient url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' parameters = { 'st...
the-stack_106_21901
import numpy as np import pdb def muscleVolumeCalculator(subjectHeight,subjectMass): # This function calculates subject's muscle volume based on its height (in meters) and mass (in kg). # Import OpenSim Libraries # import org.opensim.modeling.* # filename = 'muscleData.xlsx'; # [pathstr,~,~] = filep...
the-stack_106_21902
import os import pprint import argparse import wandb import torch import numpy as np from dataset import ShapeNet15k from models.networks import SetTransformer, Generator from models.pct import PCT from trainers.losses import DSMLoss, AnnealedDSMLoss from trainers.samplers import LangevinSampler, AnnealedLangevinSamp...
the-stack_106_21905
# coding=utf-8 # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. 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/...
the-stack_106_21908
import numpy import six from chainer import cuda def get_conv_outsize(size, k, s, p, cover_all=False): if cover_all: return (size + p * 2 - k + s - 1) // s + 1 else: return (size + p * 2 - k) // s + 1 def get_deconv_outsize(size, k, s, p, cover_all=False): if cover_all: return s...
the-stack_106_21910
# Copyright (c) 2018, Arm Limited and affiliates. # SPDX-License-Identifier: Apache-2.0 # # 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 # # ...
the-stack_106_21914
## # Copyright (c) 2012-2017 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
the-stack_106_21915
import numpy as np #シグモイド関数の実装 def sigmoid(x): return 1 / (1 + np.exp(-x)) #恒等関数(入力したものに対して何も手を加えずに出力する関数) def identity_function(x): return x #重みとバイアスの初期化 def init_network(): network = {} network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]) network['b1'] = np.array([0.1, 0.2, 0.3]) ne...
the-stack_106_21916
''' The static grains, these are the core, or built in grains. When grains are loaded they are not loaded in the same way that modules are loaded, grain functions are detected and executed, the functions MUST return a dict which will be applied to the main grains dict. This module will always be executed first, so tha...
the-stack_106_21919
import time import threading import config from config import * class IBlock: def __init__(self): self.cells = 4 # Number of cells occupied by the block config.block_count += 1 config.item_id["blocks"][f"{config.block_count}"] = {} # Add a new key to dictionary to add block IDs ...
the-stack_106_21920
import numpy as np from scipy.signal import find_peaks __all__ = ['bls_peakfinder'] def bls_peakfinder(results): """ Find peaks in a Box Least Squares spectrum. Parameters ---------- results : `~astropy.timeseries.BoxLeastSquaresResults` BLS results Returns ------- inds : `~...
the-stack_106_21921
import cv2 import keras import math import matplotlib.pyplot as plt import numpy as np import random import warnings from generators.utils import get_affine_transform, affine_transform from generators.utils import gaussian_radius, draw_gaussian, gaussian_radius_2, draw_gaussian_2 class Generator(keras.utils.Sequence...
the-stack_106_21922
from pathlib import Path def mkdir(out_dir): out_dir = Path(out_dir) if not out_dir.exists(): out_dir.mkdir(parents=True, exist_ok=True) def load_current_env(): '''获取当前目录的决对路径,且添加 Python 环境''' import os # 获取根目录 try: # colab 目录 from google.colab import drive root = '/...
the-stack_106_21924
#!/usr/bin/env python3 import argparse import jinja2 import os import yaml import pnrg.filters from distutils import dir_util import logging, sys class OutputFormat(object): def __init__(self, arg_name, template_extension, output_suffix): self.arg_name = arg_name self.template_extension = template...
the-stack_106_21925
from datetime import ( date, datetime, ) import subprocess import sys import numpy as np import pytest import pandas._config.config as cf import pandas.util._test_decorators as td from pandas import ( Index, Period, Series, Timestamp, date_range, ) import pandas._testing as tm from pand...
the-stack_106_21926
unconfirmed_users = ['alice', 'brain', 'candace'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: "+current_user.title()) confirmed_users.append(current_user) print("\nThe following users have been confirmed:") for confirmed_user in confirmed_use...
the-stack_106_21929
import pytest from cactusbot.handlers import SpamHandler from cactusbot.packets import MessagePacket async def get_user_id(_): return 0 class MockAPI: async def get_trust(self, _): class Response: status = 404 return Response() spam_handler = SpamHandler(MockAPI()) @pytest....
the-stack_106_21931
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_106_21932
""" This file offers the methods to automatically retrieve the graph Devosia crocina. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein associ...
the-stack_106_21935
import argparse import tensorflow as tf tf.random.set_seed(10) import numpy as np np.random.seed(15) import matplotlib.pyplot as plt from surrogate_models import coefficient_model from optimizers import surrogate_optimizer from utils import shape_return if __name__ == '__main__': ''' Usage: python nn_opt.py...
the-stack_106_21937
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from nipype.pipeline import engine as pe from fmriprep.workflows.bold.base import _get_wf_name class FactoryContext: def __init__(self, workdir, spec, bidsdatabase, workflow,...
the-stack_106_21938
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # 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 # ...
the-stack_106_21939
# -*- coding: utf-8 -*- # Questo è Sensorberry # File principale # È stato costruito da Alessandro Massarenti # V 2.0 import threading import time import serial from telepot.loop import MessageLoop from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton from config import * from funzioni import * from pl...
the-stack_106_21940
#!/usr/bin/env python3 """ Copyright (C) 2018-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applic...
the-stack_106_21944
import requests import json import smtplib URL = 'https://min-api.cryptocompare.com/data/price?fsym=DOGE&tsyms=INR' def getDogePrice(): response = requests.request('GET', URL) response = json.loads(response.text) f = open(r'C:\Users\Mittu\Desktop\DogeAlert\value_change.txt', 'r') previous_value = f.r...
the-stack_106_21945
"""Definition of HLO Instructions""" from collections import defaultdict from enum import Enum, auto import numpy as np from common import compute_bytes, append_flatten_elements, transpose_flatten, reshape_flatten class ShardingSpecType(Enum): REPLICATED = auto() MAXIMAL = auto() OTHER = auto() TUP...
the-stack_106_21946
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. HERO for Video Question Answering Tasks, shared by: 1. TVQA 2. How2QA """ from collections import defaultdict import copy import torch from torch import nn from torch.nn import functional as F from .model import HeroModel from .layers import ML...
the-stack_106_21947
from collections import deque import time import gym import tensorflow as tf import numpy as np from mpi4py import MPI from stable_baselines.common import Dataset, explained_variance, fmt_row, zipsame, ActorCriticRLModel, SetVerbosity, \ TensorboardWriter from stable_baselines import logger import stable_baseline...
the-stack_106_21948
###################################################################################################################### # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
the-stack_106_21949
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- ...
the-stack_106_21951
# -*- coding: UTF-8 -*- # Copyright (c) 2021 PaddlePaddle 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 # # ...
the-stack_106_21954
"""Module containing common scenarios that can be used for writing tests with less boiler-plate.""" from typing import List, Dict, Any import unittest import time from vega_client import vegaClient from suite import vegaNetwork, ProcessOutput, ProcessExitResult from requests.exceptions import ConnectionError RETRIES...
the-stack_106_21955
from __future__ import print_function import argparse import av arg_parser = argparse.ArgumentParser() arg_parser.add_argument('output') args = arg_parser.parse_args() of = av.open(args.output, 'w') print(of) for codec_name in 'aac', 'vorbis': try: os = of.add_stream(codec_name) except Exception as...
the-stack_106_21956
import logging import contextlib import io import sys import json import os from unittest import TestCase, mock from google.cloud import logging_v2 import bigflow.log class LoggerTestCase(TestCase): def configure_mocked_logging(self, project_id, log_name, workflow_id=None): self.gcp_handler = mock.Moc...
the-stack_106_21957
# -*- coding: utf-8 -*- """ cleaning up the different parts """ import os import glob import pandas as pd # load data path = 'data/' all_files = glob.glob(os.path.join(path, "*.csv")) df = (pd.read_csv(f) for f in all_files) tracks = pd.concat(df, ignore_index=True) # get rid of sloppiness before ...
the-stack_106_21958
import sys import json from collections import OrderedDict TERMINATORS = ["jmp", "br", "ret"] def form_blocks(instrs): cur_block = [] for instr in instrs: if "op" in instr: # instruction cur_block.append(instr) if instr["op"] in TERMINATORS: if cur_block: ...
the-stack_106_21962
import inspect import json import math import numbers from textwrap import TextWrapper import mmap import time import numpy as np from asciitree import BoxStyle, LeftAligned from asciitree.traversal import Traversal from collections.abc import Iterable from numcodecs.compat import ensure_ndarray, ensure_text from numc...
the-stack_106_21964
# Copyright 2016 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...
the-stack_106_21965
import gpflow import numpy as np from gpflow.mean_functions import Identity, Linear, Zero from .layers import SVGPLayer def init_layers_linear(X, Y, Z, kernels, layer_sizes, mean_function=Zero(), num_outputs=None, Layer=SVGPLayer, whiten=False): num_outputs = num_outputs or Y.shape[1] ...
the-stack_106_21966
from torch_sparse import SparseTensor class ToSparseTensor(object): r"""Converts the :obj:`edge_index` attribute of a data object into a (transposed) :class:`torch_sparse.SparseTensor` type with key :obj:`adj_.t`. Args: remove_faces (bool, optional): If set to :obj:`False`, the :o...
the-stack_106_21970
"""A collections of functions to facilitate analysis of HiC data based on the cooler and cooltools interfaces.""" import warnings from typing import Tuple, Dict, Callable import cooltools.expected import cooltools.snipping import pandas as pd import bioframe import cooler import pairtools import numpy as np ...
the-stack_106_21971
# Once for All: Train One Network and Specialize it for Efficient Deployment # Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han # International Conference on Learning Representations (ICLR), 2020. import torch.nn.functional as F import torch.nn as nn import torch from torch.nn.parameter import Parameter from...
the-stack_106_21975
import datetime from django.conf import settings from django.db import models from django.db.models import Q from django.utils.html import strip_tags from django.utils.text import Truncator from wagtail.admin.edit_handlers import FieldPanel, FieldRowPanel, StreamFieldPanel from wagtail.core.fields import RichTextField...
the-stack_106_21977
import sys import subprocess from Tkinter import Tk, Frame, Button, LEFT, FLAT import logging def set_config(logger, logdir=""): if logdir != "": handler = logging.FileHandler(logdir) else: handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)...
the-stack_106_21978
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import itertools import json import math import os import sys from enum import Enum from typing import List import numpy as np import torch import torch.nn as nn from pytext.common.constants import Stage from pytext.config im...
the-stack_106_21980
# Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug # Copyright: (c) <spug.dev@gmail.com> # Released under the AGPL-3.0 License. from git import Repo, RemoteReference, TagReference, InvalidGitRepositoryError, GitCommandError from tempfile import NamedTemporaryFile import shutil import os class Gi...
the-stack_106_21981
#!/usr/bin/env python # -*- coding:utf-8 -*- import logging import os import logging import traceback import six logger = logging.getLogger(__name__) DATE_FORMATS = {1: "%Y:%m:%d-%H:%M:%S", 2: "%Y/%m/%d %H:%M:%S", 3: "%Y/%m/%d %H:%M:%S"} def conv_resol(resolution): return resolution def conv_datetime(dt, ver...
the-stack_106_21982
""" In this module, there are NN that use siamese neural network and receive pairs. """ import logging import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import ModuleList, Sequential, Linear from model.basic_module import MultilayerDense, meanVector def computeListOutputSize(encoders)...
the-stack_106_21984
"""RoomMessagePosterFunction Allows posting a message to a room. Returns the message ID of the posted message. """ from __future__ import print_function import os import json import time import hashlib import boto3 import botocore from apigateway_helpers.exception import APIGatewayException from apigateway_helpers...
the-stack_106_21985
from tensorflow.keras.preprocessing import sequence from tensorflow.keras.preprocessing.text import Tokenizer import pandas as pd import string from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split def preprocess(s): return stripPunctuation(removeBr(s.lower())) def st...
the-stack_106_21986
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
the-stack_106_21989
# coding=utf-8 import os import shutil import sys import time import logging import cv2 import numpy as np import tensorflow as tf sys.path.append(os.getcwd()) from nets import model_train as model from utils.rpn_msr.proposal_layer import proposal_layer from utils.text_connector.detectors import TextDetector logging...
the-stack_106_21991
from .base import DiscordModelsBase from quart import current_app import discord from .. import configs class Guild(DiscordModelsBase): """Class representing discord Guild the user is part of. Operations ---------- x == y Checks if two guild's are the same. x != y Checks if two g...
the-stack_106_21992
"""Install SciencePlots. This will copy the *.mplstyle files into the appropriate directory. This code is based on a StackOverflow answer: https://stackoverflow.com/questions/31559225/how-to-ship-or-distribute-a-matplotlib-stylesheet """ import atexit import glob import os import shutil import matplotlib from setu...
the-stack_106_21998
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_bzoinq ---------------------------------- Tests for `bzoinq` module. """ import pytest from bzoinq import bzoinq # @pytest.fixture # def response(): # """Sample pytest fixture. # See more at: http://doc.pytest.org/en/latest/fixture.html # """ # ...
the-stack_106_21999
import os import sys import glob import math from random import shuffle import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import nibabel as nib import torch import torch.nn as nn import util from model im...
the-stack_106_22000
import editor from common import msg, utils, shared as G from collections import defaultdict vim = None # Foreground: background COLORS = ( ('white', 'red'), ('black', 'yellow'), ('black', 'green'), ('white', 'blue'), ) HL_RULES = ['ctermfg=%s ctermbg=%s guifg=%s guibg=%s' % (fg, bg, fg, bg) for fg, ...
the-stack_106_22001
data = [[float(y) for y in x.strip().split(', ')] for x in open('block_datadump.csv').readlines()] for i in range(0, 2283416, 200000): print('Checking 200k blocks from %d' % i) dataset = [] totuncles, totuncreward = 0, 0 totbs = [0 for j in range(40)] totus = [0 for j in range(40)] for num, unc...
the-stack_106_22003
# encoding: utf-8 import re import subprocess import sys import tempfile from textwrap import dedent from bpython import args from bpython.test import (FixLanguageTestCase as TestCase, unittest) try: from nose.plugins.attrib import attr except ImportError: def attr(*args, **kwargs): def identity(func...
the-stack_106_22005
# ================================================================= # # Authors: Ian Edwards # # Copyright (c) 2020, OpenCDMS Project # # 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...
the-stack_106_22006
import torch import torch.nn.functional as F from torch.autograd import Variable def get_laststep(model, lens): shape = model.size() idx = (lens - 1).view(-1, 1).expand(shape[0], model.size(2)).unsqueeze(1) model = model.gather(1, Variable(idx)).squeeze(1) return model def pooled_output(model): ...
the-stack_106_22007
# coding=utf-8 # Copyright 2021 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
the-stack_106_22009
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import operator import os from shutil import rmtree import string import tempfile from typing import Any, Callable, ContextManager, List, Optional, Type, Union, cast imp...
the-stack_106_22012
""" This example demonstrates the use of the progress reporting feature in RPC calls. It (ab)uses the feature to download a file from the server (server.py) in chunks to a temporary directory. The file path parameter should be a path relative to the directory where the server is serving files from. """ import logging...
the-stack_106_22013
# stdlib from urllib.parse import urljoin # 3rd Party import requests import json # project from checks import AgentCheck SERVICE_CHECK_NAME = 'burrow.can_connect' DEFAULT_BURROW_URI = 'http://localhost:8000' CLUSTER_ENDPOINT = '/v3/kafka' CONFIG_ENDPOINT = '/v3/config' CHECK_TIMEOUT = 10 class BurrowCheck(Agen...
the-stack_106_22014
# -*- coding: utf-8 -*- """Deletion functions to supplement :mod:`pybel.struct.mutation.expansion`.""" import logging import typing from collections import Counter, defaultdict from typing import Collection, Iterable, Optional, Tuple import pybel.struct.mutation.expansion.neighborhood from pybel import BELGraph from...