filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_10871 | # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
from datadog_api_client.v1.model_uti... |
the-stack_0_10873 | import logging
import moderngl
from moderngl_window.loaders.base import BaseLoader
from moderngl_window.opengl import program
from moderngl_window.exceptions import ImproperlyConfigured
logger = logging.getLogger(__name__)
class Loader(BaseLoader):
kind = "single"
def load(self) -> moderngl.Program:
... |
the-stack_0_10874 | from datetime import date, datetime, time
from typing import Any, Dict, Optional
from flask import url_for
from flask_frozen import UrlForLogger
from git import Repo
from naucse import views
from naucse.models import Course
from naucse.utils.views import page_content_cache_key, get_edit_info
def get_course_from_slu... |
the-stack_0_10875 | """
Test the optimization of transfers, generating a few simplified scenarios
and checking that the optimizer finds the expected outcome.
"""
from unittest import mock
from operator import itemgetter
from airsenal.framework.squad import Squad
from airsenal.framework.optimization_utils import (
get_discount_factor,... |
the-stack_0_10878 | import numpy as np
from sklearn import datasets
from lightgbm.sklearn import LGBMRegressor
from hummingbird.ml import convert
import onnxruntime
import torch
x, y = datasets.load_wine(return_X_y=True)
x = x.astype(np.float32)
model = LGBMRegressor(n_estimators=10)
model.fit(x, y)
preds = model.predict(x)
pytorch_mod... |
the-stack_0_10879 | # Copyright 2022 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, s... |
the-stack_0_10881 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
the-stack_0_10884 | # -*- coding:utf-8 -*-
import os
from concurrent.futures.thread import ThreadPoolExecutor
from flask_restful import Resource, reqparse, request
from flask import g, app
from common.log import loggers
from common.audit_log import audit_log
from common.db import DB
from common.utility import uuid_prefix, salt_api_for_pr... |
the-stack_0_10885 | # 3_cmakefile_gen.py - helper to create CMakeLists.txt files
# for directory tree of IDL files, to build as merged typesupport static library
# Started 2020Nov09 Neil Puthuff
import sys
import os
file_header = '''# Copyright 2020 Real-Time Innovations
#
# Licensed under the Apache License, Version 2.0 (th... |
the-stack_0_10886 | import sys
import os
import pdb
import pathlib
import time
import base64
sys.path.append(os.path.join(str(pathlib.Path(__file__).parent.resolve()),'../../lib'))
from module import Module
class Exfiltration(Module):
description = 'This module downloads the specified files on victim to the attacker'
@classmethod
de... |
the-stack_0_10887 | from typing import Sequence
from ..types import TealType, require_type
from ..errors import TealInputError
from ..ir import TealOp, Op, TealSimpleBlock
from .expr import Expr
class NaryExpr(Expr):
"""N-ary expression base class.
This type of expression takes an arbitrary number of arguments.
"""
... |
the-stack_0_10889 | # 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_0_10891 | # Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
the-stack_0_10892 | import os
import json
from pytesseract import image_to_data, image_to_string, Output
from ocr_utils import list_files_path, get_files_list
from eval_utils import get_accuracy
from PIL import Image, ImageDraw, ImageFont
class ocr:
def __init__(self, input_dir, output_dir):
self.input_dir = input_dir
... |
the-stack_0_10893 | # -*- coding: utf-8 -*-
#
# 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
#... |
the-stack_0_10895 | # Copyright 2018 The Cornac 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 applicable ... |
the-stack_0_10896 | ##########################################################################
#
# Copyright (c) 2012, John Haddon. All rights reserved.
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that ... |
the-stack_0_10897 | import requests
import logging
from .config import Config
from prometheus_client.core import Gauge
import base64
CONF = Config()
class SonarQubeClient:
def __init__(self, url, user_token, **kwargs):
if url.endswith("/"):
url = url[:-1]
self._url = url
self._user_token = user_... |
the-stack_0_10898 | import torch
import torch.nn as nn
import math
from torch.autograd import Variable
def make_mlp(dim_list, activation='relu', batch_norm=True, dropout=0):
layers = []
# batch_norm=True
dropout=0.25
for dim_in, dim_out in zip(dim_list[:-1], dim_list[1:]):
layers.append(nn.Linear(dim_in, dim_out))... |
the-stack_0_10899 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
the-stack_0_10900 | from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.core.mail import send_mail
from django.conf import settings
from .authentication i... |
the-stack_0_10901 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
__version__ = '1.29.7'
# -----------------------------------------------------------------------------
import asyncio
import concurrent
import socket
import certifi
import aiohttp
import ssl
import sys
import yar... |
the-stack_0_10902 | import scipy.stats as st
import math
import torch
import numpy as np
import torch.nn as nn
from functools import partial
# Target function definition
def f(input_):
r"""
Bimodal function
:param x:
:return:
"""
x = input_ + 0.5
y_left = st.skewnorm(a=4, loc=.3, scale=.7).pdf(3 * x) / 1.6
... |
the-stack_0_10905 | # TODO: This code is comparing HyperparameterRanges_CS with HyperparameterRanges.
# If the latter code is removed, this test can go as well.
import numpy as np
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
from numpy.testing import assert_allclose
from autogluon.core.searcher import \
Hyperpa... |
the-stack_0_10906 | #!/usr/bin/env python
#
# toolbar.py - FSLeyes toolbars
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module provides the :class:`FSLeyesToolBar` class, the base class
for all toolbars in *FSLeyes*.
"""
import logging
import wx
import wx.lib.newevent as wxevent
import numpy as np
import fsleyes.pane... |
the-stack_0_10908 | _base_ = "finetune-eval-base.py"
# dataset settings
data_source_cfg = dict(
type="ImageListMultihead",
memcached=False,
mclient_path='/no/matter',
# this will be ignored if type != ImageListMultihead
)
data_train_list = "data/xview/meta/train-1000.txt"
data_train_root = 'data/xview'
data_val_li... |
the-stack_0_10909 | '''
Created on 8 mrt. 2011
.. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
epruyt <e.pruyt (at) tudelft (dot) nl>
'''
from __future__ import (division, unicode_literals, print_function,
absolute_import)
from math import exp
from ema_workbench.em_framework import (... |
the-stack_0_10910 | class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
# sold[i] selling at day i or do nothing
# sold[i] = max( sold[i-1], hold[i-1] + prices[i] - fee)
# hold[i] buying at day i or do nothing
# hold[i] = max( hold[i-1], sold[i-1] - prices[i])
N = len(prices... |
the-stack_0_10911 | # 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... |
the-stack_0_10913 | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The MicroBitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test that we reject low difficulty headers to prevent our block tree from filling up with useless ... |
the-stack_0_10916 | import os
from . import configs
from flask import Flask
from flask_cors import CORS
from flask_redis import FlaskRedis
import psycopg2
redis_store = FlaskRedis()
root_dir = os.path.dirname(os.path.abspath(__file__))
conn = psycopg2.connect(
database=os.environ.get("DB_NAME", os.getenv("DB_NAME")),
user=os.env... |
the-stack_0_10919 | #MIT License
#Copyright (c) 2021 SUBIN
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distr... |
the-stack_0_10922 | import logging
import torch
from ..datasets import build_loader
from ..tasks import build_task
from ..utils import get_default_parser, env_setup, \
Timer, get_eta, dist_get_world_size
def add_args(parser):
## Basic options
parser.add_argument('--dataset', type=str, default='CIFAR10',
... |
the-stack_0_10924 | """collection of methods for generating merger populations and rates"""
import utils
import sfh
from astropy.cosmology import Planck15 as cosmo
from astropy import units as u
import numpy as np
from tqdm import tqdm
def get_mergers(zbins, mets, metallicities, alpha, z_interp, downsample):
met_weights = sfh.get_m... |
the-stack_0_10926 | import ctypes
import enum
import numpy as np
from astropy import units as u
from panoptes.pocs.camera.sdk import AbstractSDKDriver
from panoptes.utils import error
from panoptes.utils import get_quantity_value
####################################################################################################
#
# Ma... |
the-stack_0_10927 | # -*- coding: utf-8 -*-
# This code is part of Ansible, but is an independent component
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own lic... |
the-stack_0_10928 | import tensorflow as tf # noqa
import copy
import os
import cPickle as pickle
import numpy as np
import hashlib
from ..data import helpers as helpers
from ..utils import misc as misc
from ..data import batch_fetcher as bfetchers
from ..experiments import experiment
from ..experiments import config as econfig
from ..mo... |
the-stack_0_10929 | import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram, plot_bloch_multivector
warnings.filterwarnings("ignore",... |
the-stack_0_10932 | # 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
#
# Unless required by appli... |
the-stack_0_10937 | import json
import logging
import os
import click
import google.auth.transport.grpc
import google.auth.transport.requests
import google.oauth2.credentials
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from assistant import Assistant
ASSISTANT_API_ENDPOINT = 'embeddedassistant.googleapis.com'
DEFAULT_GRPC_DE... |
the-stack_0_10938 | # File: wmi_consts.py
#
# Copyright (c) 2016-2022 Splunk 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 applica... |
the-stack_0_10939 | import logging
import os
import tempfile
from galaxy.tool_shed.galaxy_install.tool_dependencies.env_manager import EnvManager
from galaxy.tool_shed.galaxy_install.tool_dependencies.recipe.env_file_builder import EnvFileBuilder
from galaxy.tool_shed.galaxy_install.tool_dependencies.recipe.install_environment import Ins... |
the-stack_0_10940 | from torchio import RandomNoise
from ...utils import TorchioTestCase
class TestRandomNoise(TorchioTestCase):
"""Tests for `RandomNoise`."""
def test_no_noise(self):
transform = RandomNoise(mean=0., std=0.)
transformed = transform(self.sample_subject)
self.assertTensorAlmostEqual(
... |
the-stack_0_10941 | import logging, math
from gi.repository import Gst, Gtk
class AudioLevelDisplay(object):
""" Displays a Level-Meter of another VideoDisplay into a GtkWidget """
def __init__(self, drawing_area):
self.log = logging.getLogger('AudioLevelDisplay[%s]' % drawing_area.get_name())
self.drawing_area = drawing_area
... |
the-stack_0_10942 | from pynput import keyboard
import time
import BarcodeScanner as BB
def on_press(a):
#try:
global count
global s
if a!=keyboard.Key.shift and a!=keyboard.Key.enter :
#print('{0}'.format(a))
count = count+1
s = s+str(a.char)
if count==4:
return False
... |
the-stack_0_10945 | import pandas as pd
from sklearn.metrics import mean_squared_error
import matplotlib
matplotlib.use('Agg') # for saving figures
import matplotlib.pyplot as plt
series = pd.read_csv('daily-users.csv', header=0, parse_dates=[0], index_col=0, squeeze=True)
from statsmodels.tsa.arima_model import ARIMA
f, axarr = plt.su... |
the-stack_0_10946 | import gym
from torch import nn as nn
from rlkit.exploration_strategies.base import \
PolicyWrappedWithExplorationStrategy
from rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy
from rlkit.policies.argmax import ArgmaxDiscretePolicy
from rlkit.torch.vpg.ppo import PPOTrainer
from rlkit.torch.network... |
the-stack_0_10947 | """Command to set a metadata attribute."""
import asyncio
from typing import Optional
import click
from astoria.astctl.command import Command
from astoria.common.ipc import MetadataSetManagerRequest
loop = asyncio.get_event_loop()
@click.command("set")
@click.argument("attribute")
@click.argument("value")
@click.o... |
the-stack_0_10948 | from __future__ import print_function
from __future__ import division
from six.moves import xrange
import os
import time
import tensorflow as tf
import numpy as np
from sklearn.preprocessing import StandardScaler
from lib.datasets import MNIST as Data
from lib.model import Model as BaseModel
from lib.segmentation im... |
the-stack_0_10949 | from __future__ import division
import torch
from ignite.metrics.metric import Metric
from ignite.exceptions import NotComputableError
from ignite.metrics.metric import sync_all_reduce, reinit__is_reduced
class TopKCategoricalAccuracy(Metric):
"""
Calculates the top-k categorical accuracy.
- `update` m... |
the-stack_0_10950 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import logging
import mock
import pytest
import uuid
from collections import namedtuple
from datetime import datetime, timedelta
from django.utils import timezone
from time import time
from sentry.app import tsdb
from sentry.constants im... |
the-stack_0_10951 | try:
from django.contrib.auth import get_user_model as auth_get_user_model
except ImportError:
auth_get_user_model = None
from django.contrib.auth.models import User
from account.conf import settings
AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User")
def get_user_model(*args, **kwargs)... |
the-stack_0_10952 | from ...Core.registers import Registers
from ...Core.commands import Commands
from ...Core.types import Types
from ...Runtime.gc import GC
""" Map: arithmetic operator in programming language = arithmetic operator in ASM """
binop_compare_map = {
'+': {
'operator': Commands.ADD,
'operands': [Regist... |
the-stack_0_10953 | from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(
verbose_name='title',
max_length=255,
help_text="The page title as you'd like it to be seen by the public",
)
body = models.TextField(
verbose_name='content bod... |
the-stack_0_10955 | from tkinter import *
import random
class Window:
def __init__(self, master):
self.master = master
self.guess_number = None
self.cows = 0
self.bulls = 0
master.title("Bulls and Cows")
self.label = Label(master, text="Let`s play Bulls and Cows game!")
self.... |
the-stack_0_10958 | # 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, ... |
the-stack_0_10960 | # -*- encoding: utf-8 -*-
import re
import sys
from svb.multipart_data_generator import MultipartDataGenerator
from svb.test.helper import SvbTestCase
class MultipartDataGeneratorTests(SvbTestCase):
def run_test_multipart_data_with_file(self, test_file):
params = {
"key1": b"ASCII value",
... |
the-stack_0_10962 | import plotly.graph_objects as go
def pad_list(l, n):
pad = [1] * (n - len(l))
return l + pad
def overlaid_area(df, x_column, y_column, filename, category):
df = df.sort_values(x_column)
dose_1 = df[df[category] == 'Primeira dose']
x_dose_1 = dose_1[x_column].tolist()
y_dose_1 = dose_1[y_co... |
the-stack_0_10963 | from gluoncv.data import COCOInstance, COCOSegmentation
from pycocotools.coco import COCO
import numpy as np
from PIL import Image, ImageOps
import os
import pickle
import random
from io import BytesIO
def randomJPEGcompression(image, min_quality=75):
qf = random.randrange(min_quality, 100)
outputIoStream = B... |
the-stack_0_10966 | """Important Bodies.
Contains some predefined bodies of the Solar System:
* Sun (☉)
* Earth (♁)
* Moon (☾)
* Mercury (☿)
* Venus (♀)
* Mars (♂)
* Jupiter (♃)
* Saturn (♄)
* Uranus (⛢)
* Neptune (♆)
* Pluto (♇)
and a way to define new bodies (:py:class:`~Body` class).
Data references can be found in :py:mod:`~einsteinpy... |
the-stack_0_10968 | import re
import typing
import pytest
from dagster import (
Any,
DagsterInvalidConfigDefinitionError,
DagsterInvalidConfigError,
DagsterInvalidDefinitionError,
Field,
Float,
Int,
List,
ModeDefinition,
Noneable,
Permissive,
PipelineDefinition,
ResourceDefinition,
... |
the-stack_0_10971 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# 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
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
the-stack_0_10973 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
the-stack_0_10975 | __author__ = 'ipetrash'
# https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files
# http://pythonworld.ru/tipy-dannyx-v-python/fajly-rabota-s-fajlami.html
if __name__ == '__main__':
# Открыть файл в режиме записи
with open('foo.txt', mode='w') as f:
f.write('123\n')
f.... |
the-stack_0_10980 | import re as _re
import numpy as _np
import copy as _copy
import gdspy as _gdspy
import os as _os
import time as _time
from . import utils
from . import geometry
_PRINT_LIT_REDUCTION = False
class CallTree:
_operators = [['make'], ['.'], ['^'], ['*', '/'], ['-', '+'], ['pstart', 'pend'],
['psep'], ... |
the-stack_0_10982 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import inspect
from pandapower.auxiliary import _check_bus_index_and_print_warning_if_high, \
_check_gen_index_and_print_warn... |
the-stack_0_10983 | """
Given an integer array with all positive numbers and no duplicates, find the
number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
... |
the-stack_0_10985 | import numpy
from chainer.functions.connection import bilinear
from chainer import link
class Bilinear(link.Link):
"""Bilinear layer that performs tensor multiplication.
Bilinear is a primitive link that wraps the
:func:`~chainer.functions.bilinear` functions. It holds parameters ``W``,
``V1``, ``V... |
the-stack_0_10986 | import sublime
import sublime_plugin
import subprocess
from .path_utils import path_for_view
SCRIPT_PATH = 'Packages/SublimeConfig/src/commands/open_current_directory_in_terminal.applescript'
def osascript(
*,
script,
args=[]
):
cmd = ['osascript', '-'] + args
proc = subprocess.Popen(
c... |
the-stack_0_10987 | # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2013-2014 Google, Inc.
# Copyright (c) 2013 buck@yelp.com <buck@yelp.com>
# Copyright (c) 2014-2017 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Brett Cannon <brett@python.org>
# Copyright (c) 2014 Arun Persaud <aru... |
the-stack_0_10988 | """Splash_screen module."""
from PyQt6 import QtGui, QtCore, QtWidgets # type: ignore
from pineboolib.core.utils.utils_base import filedir
from pineboolib.core import settings
class SplashScreen(object):
"""Show a splashscreen to inform keep the user busy while Pineboo is warming up."""
_splash: "QtWidgets.... |
the-stack_0_10989 | import torch
import torch.nn as nn
import torch.nn.functional as F
import src.data.data as data
import src.data.config as cfg
import src.models.utils as model_utils
import src.evaluate.utils as eval_utils
import src.train.batch as batch_utils
def make_sampler(sampler_type, opt, *args, **kwargs):
print("Initializ... |
the-stack_0_10990 | #!/usr/bin/env python
# Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
the-stack_0_10992 | import numpy as np
import torch
import torch.nn as nn
class CNNCTC(nn.Module):
def __init__(self, class_num, mode='train'):
super(CNNCTC, self).__init__()
feature = [
nn.Conv2d(3, 50, stride=1, kernel_size=3, padding=1),
nn.BatchNorm2d(50),
nn.ReLU(inplace=True)... |
the-stack_0_10993 | # Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
# See: https://spdx.org/licenses/
import typing as ty
import numpy as np
import numpy.typing as npt
class CoefficientTensorsMixin:
def __init__(self, *coefficients: ty.Union[ty.List, npt.ArrayLike]):
"""Coefficients for a sca... |
the-stack_0_10994 |
"""Utilities for downloading data from WMT, tokenizing, vocabularies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import re
import tarfile
from six.moves import urllib
import numpy as np
from tensorflow.python.platform import ... |
the-stack_0_10996 | import logging
import logconfig
logconfig.logconfig(filename=None)
logconfig.loglevel(logging.INFO)
import squaregrid
from sde import *
def test_sde():
def c(z):
return 2.0*z*z*z - 1j*z + 0.2
gr = squaregrid.SquareGrid(3.0,255)
def report(Q):
"""Print data about solution in SelfDualityEq... |
the-stack_0_10997 | import numpy as np
import os
import pytest
import tempfile
import torch
from mmcv.parallel import MMDataParallel
from os.path import dirname, exists, join
from mmdet3d.apis import (convert_SyncBN, inference_detector,
inference_mono_3d_detector,
inference_multi_modali... |
the-stack_0_10999 | ### @export "setup"
import fake_input
input, input = fake_input.create(['', 'Mary had a little lamb',
'Its fleece was white as snow',
'It was also tasty'])
### @export "code"
from sys import argv
script, filename = argv
print(f"We're going to eras... |
the-stack_0_11001 | from __future__ import print_function, division
from sympy import (
Basic,
sympify,
symbols,
Dummy,
Lambda,
summation,
Piecewise,
S,
cacheit,
Sum,
exp,
I,
Ne,
Eq,
poly,
series,
factorial,
And,
)
from sympy.polys.polyerrors import PolynomialError
... |
the-stack_0_11002 | from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
"""Test waiting for db when db is available"""
with patch('django.db.utils... |
the-stack_0_11003 | # Copyright 2020 ByteDance 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 writin... |
the-stack_0_11005 | import json
from django.db import connection
from elasticsearch import Elasticsearch
from jobs.models import Job
es_client = Elasticsearch('http://localhost:9200')
def run():
# Create Index
es_client.indices.create(index='jobs')
# Put Mapping
with open("jobs/job.json", "r") as fp:
es_clien... |
the-stack_0_11006 | from pandas import DataFrame
excluded = [
'01 Buster',
'838 Spyder',
'Aqua Blaster',
'B.O.X.',
'B.R.1.C.K',
'CHMP',
'Droid Ravager',
'Drumstick',
'Grumpii',
'HBB Renegade',
'MegaBoidz',
'Meta',
'Order 66',
'Puff Boxer',
'R.E.X. 02',
'Red Steel',
'SB S... |
the-stack_0_11010 | #!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Unlimited developers
import asyncio
import time
from test_framework.util import assert_raises_async, waitFor
from test_framework.test_framework import BitcoinTestFramework
from test_framework.loginit import logging
from test_framework.electrumutil import (Electru... |
the-stack_0_11011 | from datetime import datetime, timedelta
from http import HTTPStatus
from backend.extensions import db
from backend.models import User, JWTToken
from backend.serializers.login_serializer import LoginSchema
from flask import request
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
... |
the-stack_0_11012 | from __future__ import division
import torch
from onmt.translate import penalties
class Beam(object):
"""
Class for managing the internals of the beam search process.
Takes care of beams, back pointers, and scores.
Args:
beam_size (int): Number of beams to use.
pad (int): Magic integ... |
the-stack_0_11013 | from .BaseRequest import BaseRequest
class UpdateDataAlertRequest(BaseRequest):
"""
Update site request for generating API requests to Tableau Server.
:param ts_connection: The Tableau Server connection object.
:type ts_connection: class
:param subject: (Optional) The str... |
the-stack_0_11015 | import pyodbc
driver = '{Microsoft Access Driver(*.mdb,*.accdb)}'
filepath = r'C:\Users\weidongc\Desktop\Booking\2020\2020 CN Ads Booking v12.accdb'
myDataSource = pyodbc.dataSources()
access_drive = myDataSource['MS Access Database']
cnxn = pyodbc.connect(driver=access_drive,dbq=filepath,autocommit=True)
crsr = cnx... |
the-stack_0_11017 | """ ConViT Model
@article{d2021convit,
title={ConViT: Improving Vision Transformers with Soft Convolutional Inductive Biases},
author={d'Ascoli, St{\'e}phane and Touvron, Hugo and Leavitt, Matthew and Morcos, Ari and Biroli, Giulio and Sagun, Levent},
journal={arXiv preprint arXiv:2103.10697},
year={2021}
}
P... |
the-stack_0_11019 | import collections
import datetime
import logging
from celery import shared_task
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.db.m... |
the-stack_0_11020 | #
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... |
the-stack_0_11021 | import requests
from django.contrib.gis.geos import Point
from georiviere.observations.models import Station, StationProfile, Parameter, ParameterTracking, Unit
from . import BaseImportCommand
class Command(BaseImportCommand):
help = "Import physico-chemical quality stations from Hub'Eau API"
api_url = "https... |
the-stack_0_11026 | # Copyright 2018-2021 Xanadu Quantum Technologies 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_0_11027 | # CSC 321, Assignment 4
#
# This is the main training file for the CycleGAN part of the assignment.
#
# Usage:
# ======
# To train with the default hyperparamters (saves results to samples_cyclegan/):
# python cycle_gan.py
#
# To train with cycle consistency loss (saves results to samples_cyclegan_cycle/):
... |
the-stack_0_11028 | import os
import flask
from flask import send_from_directory
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from backend.utils import CustomJsonEncoder
app = flask.Flask(__name__)
app.json_encoder = CustomJsonEncoder
app.config["DEBUG"] = os.environ.get("DEBUG")
app.config['SQLALCHEMY_DATA... |
the-stack_0_11030 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
from telemetry.core import util
def Run(project_config, no_browser=False,
disable_cloud_storage_io_during_t... |
the-stack_0_11031 | import argparse
import shutil
from pathlib import Path
import time
from pyimzml.ImzMLParser import ImzMLParser
import numpy as np
from matplotlib import pyplot as plt
from sm.browser import utils, mz_search, split_sort
TMP_LOCAL_PATH = Path("/tmp/imzml-browser")
TMP_LOCAL_PATH.mkdir(parents=True, exist_ok=True)
de... |
the-stack_0_11034 | #30 min with 52cpus in LMEM1
#the script uses a maximum of 40GB mem
#%reset -f
import numpy as np
import matplotlib.pyplot as plt
import xarray as xr
import dask as da
import glob
import time
from tqdm import tqdm #to see progressbar for loops
from scipy.interpolate import interp1d #1d interp
import xesmf as xe #for s... |
the-stack_0_11035 | import matplotlib.pyplot as plt
import h5py
import glob
from natsort import natsorted
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input-path',type=str,help='input for .h5')
parser.add_argument('--output-path',type=str,help='output for png')
args = parser.parse_args()
image_list... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.