text stringlengths 3.07k 12.6k |
|---|
import re
from functools import partial
from typing import Any, Optional, Tuple
import torch.nn as nn
from torchvision.prototype.transforms import ImageClassificationEval
from torchvision.transforms.functional import InterpolationMode
from ...models.densenet import DenseNet
from ._api import WeightsEnum, Weights
from... |
#!/usr/bin/python
import sys
import klampt
from klampt.vis.glinterface import GLPluginInterface
from klampt import vis
from klampt.math import vectorops
from klampt.model.robotinfo import RobotInfo
from klampt.control import StepContext,RobotInterfaceBase,RobotInterfaceCompleter,TimedLooper
from klampt.control.robotin... |
import os
import logging
from pathlib import Path
from typing import Any, Text, Type
from unittest import mock
import pytest
from rasa.core.agent import Agent
from rasa.nlu.classifiers.diet_classifier import DIETClassifier
import rasa.utils.common
from rasa.utils.common import (
RepeatedLogFilter,
find_unavai... |
#Copyright 2017 Google 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 law or agree... |
import unittest
import pylagrit
import glob
import sys
import os
from contextlib import contextmanager
import itertools
class TestPyLaGriT(unittest.TestCase):
'''
A PyLagriT Test
Represents a test of PyLaGriT functionality.
'''
def setUp(self):
#Sets upt a lagrit object to be used dur... |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.sites.shortcuts import get_current_site
from tracking.models import PostForm, Post, Review
from tracking.forms import SignUpForm, ProfileForm
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
im... |
import argparse
import os
import os.path as osp
from collections import defaultdict
import cv2
import mmcv
import numpy as np
from tqdm import tqdm
def parse_args():
parser = argparse.ArgumentParser(
description='VOT dataset to COCO Video format')
parser.add_argument(
'-i',
'--input',... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2020, <NAME>, <NAME>, <NAME>, <NAME>"
__credits__ = ["<NAME>", "<NAME>"]
__license__ = "MIT"
__version__ = "1.0"
__status__ = "Development"
import pickle... |
#
# detect objects in a 2-D spectra
#
# This is adopted from apextract
#
import numpy as np
import scipy.ndimage as nd
from PySpectrograph import PySpectrographError
def makeflat(data, method='median', specaxis=1):
"""Comparess a 2-D array along the spectral axis
data
"""
if method == 'median':
... |
# Copyright (c) 2018 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 applicable law or agreed to in... |
# Copyright 2015. 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 la... |
from typing import Optional
import torch
import torch.nn as nn
from ding.torch_utils import ResFCBlock, ResBlock, Flatten
from ding.utils import SequenceType
class ConvEncoder(nn.Module):
"""
Overview:
The ``Convolution Encoder`` used to encode raw 2-dim observations.
Interfaces:
``__init... |
import argparse
import datetime
from PIL import Image
from PIL.ExifTags import TAGS
import os
import shutil
import sys
PIC_SUFFIXES = (".jpg", "jpeg", ".png", ".gif", ".tif", ".tiff")
VID_SUFFIXES = (".mkv", ".mov", ".mp4") # may add more later
DATE_TAKEN_KEY = 0x9003
def img_documenter(origin_direc, des... |
"""
Training and evaluation search for link prediction with an MLP.
"""
import os
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GAE
import torch_geometric.utils as gutils
import numpy as np
import load_wiki
from sklearn.metrics import roc_auc_score, average_precision_score
import argpars... |
# Copyright 2019 DeepMind Technologies 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.org/licenses/LICENSE-2.0
#
# Unless required by ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import configparser
import ftplib
import datetime
from pathlib import Path
from . import exceptions
from . import settings
from . import wizard
from . import logger
from . import utils
_logger = logger.get_logger(__name__)
def upload_to_cloud(cwd='.', prompt=True):
... |
from torch.utils.data import Dataset
import torch
import numpy as np
from sklearn.utils import check_array
class FastTensorDataLoader:
"""
A DataLoader-like object for a set of tensors that can be much faster than
TensorDataset + DataLoader because dataloader grabs individual indices of
the dataset and... |
import time, pytest
import numpy as np
from scipy import linalg
from scipy.sparse import linalg as sparselinalg
def test_eigs():
N = 1000
k = 5
ncv = 200
A = np.random.randn(N, N)
print("\n----- test_eigs -----")
print("----- Dimension of matrix A: %d -----" % N)
print("scipy.sparse.linalg.... |
# Natural Language Toolkit: Combinatory Categorial Grammar
#
# Copyright (C) 2001-2014 NLTK Project
# Author: <NAME> <<EMAIL>>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import unicode_literals
import re
from collections import defaultdict
from nltk.ccg.api import PrimitiveCa... |
import csv
from io import BytesIO
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import FileResponse
from django.shortcuts... |
"""
:codeauthor: <NAME> <<EMAIL>>
"""
import pytest
import salt.states.npm as npm
from salt.exceptions import CommandExecutionError
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {npm: {"__opts__": {"test": False}}}
def test_installed():
"""
T... |
""" Stocks recovery functions """
import re
import pandas as pd
from decouple import config
from bs4 import BeautifulSoup
from app.main.config import cache, Config, logger
from app.main.model.scrapping import ChromeScrapper
from app.main.util.xpath import xpath_info
from app.main.util.data_manipulation import format_... |
from datetime import datetime
import numpy as np
import pandas as pd
from fetcher.extras.common import MaRawData
from fetcher.utils import Fields, extract_arcgis_attributes
NULL_DATE = datetime(2020, 1, 1)
DATE = Fields.DATE.name
TS = Fields.TIMESTAMP.name
def make_cumsum_df(data, timestamp_field=Fields.TIMESTAMP.... |
# Copyright 2020 Lorna 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 l... |
#!/usr/bin/env python
# -*- coding: utf-8
import logging
import os
import ansible_gen.adapter.gen_examples as gen_example
import ansible_gen.adapter.get_imp_cls_def as get_imp_cls
from ansible_gen.adapter.utils.xml_parse.xml_parser_get_xmlns import get_xmlns_info, xmlns_info_without_prefix, \
get_xml_namespace
fr... |
"""
cfg_subcmd.py
------------
General Config File Managing Utilities.
The functions below can be called via the `manim cfg` subcommand.
"""
import os
import configparser
from .config_utils import _run_config, _paths_config_file, finalized_configs_dict
from .file_ops import guarantee_existence, open_file
from rich.... |
from datetime import datetime, timedelta
from typing import List
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
def mark_highs_lows(df: pd.DataFrame, col: str, begin_with_high: bool, window_size: float, ignore_last_rows: int) -> pd.DataFrame:
"""
Marks highs... |
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
from __future__ import annotations
import logging
from copy import copy
from contextlib import suppress
from inspect import isasyncgenfunction, _empty
from typing import TYPE_CHECKING, Optional
from ..commands import Ch... |
import math
class Edge(object):
"""docstring for Edge"""
def __init__(self, node_fr, node_to, cap, cost, e_id):
super(Edge, self).__init__()
self.capacity = cap
self.node_fr = node_fr
self.node_to = node_to
self.cost = cost
self.flow = 0
self.e_id = e_id
def get_from(self):
return self.node_fr
de... |
# Gui interface used in phase diagram, please refer to the documentation
#
# Author: <NAME>
# https://github.com/alex180500/open-computational-physics
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
from PIL import ImageTk, Image
import matplotlib.pyplot as plt
import numpy as np
import cv2
... |
'''
Author : now more
Connect : <EMAIL>
LastEditors : now more
Description :
@LastEditTime: 2019-09-02 16:44:20
'''
from argparse import ArgumentParser
from os import mkdir,path
import sys
sys.path.append('..')
# import os
# print(os.getcwd())
from config import cfg
from config import *
from data.dataloader i... |
import os
import csv
import time
import logging
import threading
from waiting import wait
import pandas as pd
from parser import YamlParser
logging.basicConfig(filename='./logs/2B_final.log', format="%(asctime)s.%(msecs)06d;%(message)s", datefmt='%Y-%m-%d %H:%M:%S', filemode='w')
log = logging.getLogger("my-logger")
l... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
from pyspark.sql import SparkSession
from pyspark import SparkContext
import pyspark.ml as M
import pyspark.sql.functions as F
import pyspark.sql.types as T
import pandas as pd
import os
import numpy as np
import json
from tqdm import tqdm
from scipy import sparse
import psutil
from pathlib import Path
from sklearn.pip... |
from __future__ import absolute_import, print_function, unicode_literals
from django.contrib.auth import authenticate, get_user, login, logout
from django.contrib.auth.models import AnonymousUser
from kolibri.logger.models import UserSessionLog
from rest_framework import filters, permissions, status, viewsets
from res... |
import pathlib
import asyncio # noqa: F401
import discord # noqa: F401
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils import checks
from .utils.chat_formatting import pagify
path = 'data/announcer'
class Announcer:
"""Configureable Announcements."""
__version__ = "1.2... |
##############################################################################
# Copyright (c) 2017 ZTE Coreporation and others.
# <EMAIL>
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and... |
# 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... |
from __future__ import annotations
from abc import abstractmethod
import logging
from pathlib import Path
from typing import (
Any, cast, Iterator, Mapping, Optional,
TYPE_CHECKING, Union,
)
from PyQt5 import Qt
from .bases import (
AbstractYAMLObjectSingleton, QABC, QAbstractYAMLObj... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import pytest
import logging
import random
import os
from pathlib import Path
from functools import partial, reduce
from operator import getitem
from contextlib import contextmanager
from bert import setup_logger
import tools.bert_multi_checkpoint_validation as ... |
from ..utils import parse_input_data, parse_output_projection
from ..wcs_utils import has_celestial
from .core import healpix_to_image, image_to_healpix
from .utils import parse_coord_system, parse_input_healpix_data
__all__ = ['reproject_from_healpix', 'reproject_to_healpix']
def reproject_from_healpix(input_data, ... |
# Copyright 2022 Accenture Global Solutions Limited
#
# 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 ... |
from distutils.command.clean import clean as _clean
from distutils.dir_util import remove_tree
from distutils import log
from setuptools import setup, find_packages, Distribution
import os
import os.path
import platform
import sys
VERSION = "0.9.1"
HERE = os.path.dirname(os.path.abspath(__file__))
PYROBUF_DEFS_PXI ... |
import argparse
import os
import datetime
import logging
import time
import math
import numpy as np
from tqdm import tqdm
from collections import OrderedDict
import re
import torch
import torch.nn.functional as F
import torch.backends.cudnn
from core.configs import cfg
from core.datasets import build_dataset
from cor... |
import random
import os
import tensorflow as tf
from data.config import DIR_CROPPED_SIGNS, DIR_CROPPED_NO_SIGNS, DIR_FRAMES_NO_SIGNS
IMAGES_WITH_SIGNS_PATH = os.path.join(DIR_CROPPED_SIGNS, '*.png')
IMAGES_WITHOUT_SIGNS_CROPPED_PATH = os.path.join(DIR_CROPPED_NO_SIGNS, '*.png')
IMAGES_WITHOUT_SIGNS_PATH = os.path.j... |
from __future__ import absolute_import, division
from __future__ import unicode_literals
from collections import OrderedDict, defaultdict
from datetime import datetime
import six
from django.db.models.aggregates import Sum
from django.utils.translation import ugettext as _
from corehq.util.quickcache import quickcac... |
#!/usr/bin/env python
"""test all known suites with data from 'data' folder, where
the optional input parameter is the number of data per
problem visible in the filename, by default 10.
"""
from __future__ import division, print_function
from ast import literal_eval # safe evaluation/execution of Python code
import os... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
from contextlib import contextmanager
from enum import Enum
import infra.remote
import infra.net
import infra.path
import infra.jsonrpc
from loguru import logger as LOG
class NodeNetworkState(Enum):
stopped = 0
... |
import mediapipe as mp
import numpy as np
from tqdm import tqdm
from .openpose import hand_colors
from ..numpy.pose_body import NumPyPoseBody
from ..pose import Pose
from ..pose_header import PoseHeader, PoseHeaderComponent, PoseHeaderDimensions
mp_holistic = mp.solutions.holistic
BODY_POINTS = mp_holistic.PoseLandm... |
from __future__ import unicode_literals
import csv
import os
import re
import shutil
import subprocess
import youtube_dl
import time
formats = [3840, 2160, 1080, 720, 500]
ydl_opts = {
"format": "313",
"outtmpl": "tempvideo/trailer.webm",
}
paths = ["dataset", "tempvideo", "tempimages"] + [
f"dataset/{fo... |
import tensorflow as tf
def group_conv(x, filters=None, kernel_size=3, **kwargs):
if not isinstance(kernel_size, list):
kernel_size = [kernel_size]
n_group = len(kernel_size)
if n_group == 1:
out = [x]
else:
size = tf.keras.backend.int_shape(x)[-1]
split_size = [size //... |
# Copyright 2020 Canonical 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 agreed to in writing, s... |
from django.shortcuts import render,redirect,get_object_or_404
from . models import Profile,Image,Comment,Follow
from . forms import UploadImageForm,CreateUserForm,UpdateProfileForm,NewCommentForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from djang... |
import discord
from discord.ext import commands
import sqlite3
from coc import ClashOfClans
from creds import coctoken
from FilterAndSend import filter, league_hr_send, clanhr_ffs_send, names, player_hr_send, playerga_send, war_ga
import os
conn = sqlite3.connect(os.path.join(os.getcwd(),'ffsbot.db'))
c = conn.cursor(... |
import pytest
from bplustree.const import TreeConf, ENDIAN
from bplustree.entry import Record, Reference, OpaqueData
from bplustree.node import (Node, LonelyRootNode, RootNode, InternalNode,
LeafNode, FreelistNode, OverflowNode)
from bplustree.serializer import IntSerializer
tree_conf = Tr... |
# Copyright (c) 2019 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 app... |
import json
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_cytoscape
from demos import dash_reusable_components as drc
app = dash.Dash('')
app.scripts.config.serve_locally = True
app.css.config.serve_locally = True
# ######... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# hellolzc 20200201
""" Read features extracted by OpenSMILE, and save it in a HDF5 File.
The features are all LLDs.
Notes from OpenSMILE toolkit:
LLDs(low level descriptors)LLDs指的是手工设计的一些低水平特征,一般是在一帧语音上进行的计算,是用来表示一帧语音的特征。
HSFs(high level statistics functions)是在LLDs的基础上做一些统... |
from django.shortcuts import render
from rest_framework.generics import (
ListCreateAPIView, RetrieveUpdateDestroyAPIView, CreateAPIView, DestroyAPIView, RetrieveAPIView)
from rest_framework import status,exceptions
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, AllowAny
from .se... |
import os, torch
import numpy as np
from numba import njit, jit
from UTILS.colorful import *
from UTILS.tensor_ops import copy_clone, my_view, add_onehot_id_at_last_dim, add_obs_container_subject
import pickle
from config import GlobalConfig
from .formation_execution import main_formation
# @njit
def distance_matrix(A)... |
# -*- coding: iso-8859-1 -*-
import os
import json
import random
import stat
import common
from fpp.facepp import API
from fpp.facepp import APIError
class BaseCrawler:
def __init__(self, configurationsDictionary):
self._extractConfig(configurationsDictionary)
self.echo = common.EchoHandler(self.... |
"""
GitHub companion module for SnippetsBackup
Author: <NAME> (buildevol)
"""
import requests
from urllib.parse import urlparse, parse_qs
from datetime import datetime
from pathlib import Path
GITHUB_API_BASE_URL = "https://api.github.com"
GITHUB_API_DEFAULT_NUM_OF_PAGE_ITEMS = 30
GITHUB_API_MAX_NUM_OF_PAGE_ITEMS = 1... |
from nmigen import *
from nmigen.back.pysim import *
from nmigen_boards.upduino_v2 import *
from nmigen_soc.wishbone import *
from nmigen_soc.memory import *
from helpers import *
from spi_rom import *
import sys
# Dummy LED class for testing.
class DummyLED():
def __init__( self ):
self.o = Signal( 1, reset =... |
#!/usr/bin/env python3
import sys
import os
import argparse
import json
import ssg.rules
import ssg.utils
import ssg.rule_yaml
SSG_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-j", "--json", type=str, action=... |
import sys
def decrText(s, key, c):
ans = ""
for x in s:
if x not in c:
ans += x
continue
flag = True
for y in key:
if key[y] == x:
ans += y
flag = False
break
if flag:
ans += x
return ans
def frequency_1(s, cipher):
cipher_cnt = {}
for x in cipher:
cipher_cnt[x] = 0
for x in s... |
import bpy
import math
import numpy as np
def get_calibration_matrix_K_from_blender(camd):
f_in_mm = camd.lens
scene = bpy.context.scene
resolution_x_in_px = scene.render.resolution_x
resolution_y_in_px = scene.render.resolution_y
scale = scene.render.resolution_percentage / 100
sensor_width_in... |
import os
from datetime import datetime, timezone
from typing import Optional
from pyspark.sql import DataFrame
class ModelProfileSession:
def __init__(self, prediction_field: str, target_field: str, score_field: str):
self.prediction_field = prediction_field
self.target_field = target_field
... |
#
# voice-skill-sdk
#
# (C) 2020, Deutsche Telekom AG
#
# This file is distributed under the terms of the MIT license.
# For details see the file LICENSE in the top directory.
#
#
# SSML tag wrappers (Nuance vocalizer)
#
import re
from typing import List
from functools import reduce
DURATION = r"^(\d*\.?\d+)(s|ms)$"... |
# OBSS SAHI Tool
# Code written by <NAME>, 2020.
import glob
import json
import ntpath
import os
import pickle
import re
import urllib.request
import zipfile
from os import path
from pathlib import Path
import numpy as np
def create_dir(_dir):
"""
Creates given directory if it is not present.
"""
if... |
#!/usr/bin/env python
import numpy as np
import sys
import traceback
import pandas as pd
def customMutation(individual, attrs_list, indpb=0.2, continuous_scale=0.1, discrete_scale=0.1):
"""Mutation
Parameters
----------
indpb : float
Independent probability for each attribute to be mutated.
... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from botorch.test_functions.synthetic import (
Ackley,
Beale,
Branin,
Bukin,
Cosine8,
DixonPr... |
# Copyright 2019 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... |
import os
import mimetypes
from datetime import datetime
from django.utils import encoding
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from dj... |
"""
common sub-module of pyhail
Contains commonly used functions.
<NAME> - 15 June 2018
"""
import numpy as np
from scipy.interpolate import interp1d
import wradlib as wrl
def wbt(temp,rh):
"""
calculate wet bulb temperature from temperature and relative humidity.
Parameters:
===========
temp:... |
# Copyright 2019 ARM Limited
#
# 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... |
import math
import sys
import os
def neg_ln_to_prob(prob_inside_ln: float):
return math.exp(-1 * prob_inside_ln)
def to_fixed(fl: float):
return "{:.5f}".format(float(fl))
def floats_to_fixed(data: list):
return map(to_fixed, data)
model_length: int = 0
NUM_OF_AMINO_ACIDS: int = 20
nu: float = 2.0
... |
import numpy as np
import os, pickle
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
def smooth(curve, size=11):
return savgol_filter(curve, size, 3)
def versus_plot():
savedir = './savedir/'
ext = '.pkl'
fig, ax = plt.subplots(1,2, sharex=True)
plt.suptitle('Mean Accur... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class SpaConv(nn.Module):
def __init__(self):
super(SpaConv, self).__init__()
# (batch,64,64,2)->(batch,60,60,64)
self.conv1 = nn.Conv2d(in_channels=2, out_channels=64, kerne... |
__author__ = 'yetone'
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.abspath(__file__)))) # noqa
import pytest
import unittest
from script_manager import Manager
from script_manager.compat import PY2
def run(command_line, manager_run):
sys.argv = command_line.split()
exit_c... |
from app import app
import random
from flask import render_template, redirect, flash
from app.forms import LoginForm
from flask_login import logout_user, current_user
from flask_login import login_required, login_user
from flask import url_for
from app.models import User
from app import db
from app.forms import Registr... |
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# ClearML - Keras with Tensorboard example code, automatic logging model and Tensorboard outputs
#
# Train a simple deep NN on the MNIST dataset.
# Then store a model to be served by clearml-serving
import argparse
import os
import tempfile
import numpy as np
import tensorflow as tf
from pathlib import Path
from tenso... |
"""
====================
CMakeLists Generator
====================
:Date: 2021-01-26
:Version: 1.0.0
:Author: Ginoko
:Contact: <EMAIL>
"""
import sys
import os
import getopt
import platform
import re
import traceback
is_windows = True
class LanguageConfiguration:
__type_value_map = {
"c": ["90", "99", "... |
import os
import shutil
import numpy as np
import torch
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import pdb... |
from flask import Flask, render_template, redirect, request
import psycopg2 as pg
import psycopg2.extras
import datetime
import time
from math import radians, cos, sin, asin, sqrt, atan2
app = Flask(__name__)
rows=[[]]
cleanrows=[]
stayPointRows=[]
iternum=0
devicenum=0
@app.route("/")
def index():
return rende... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %% [markdown]
# ## Pre-processing Functions
#
# - All years data has same 43 columns
# - We have **Fiscal year data (July 1 - June 30)**. That means one file contains data for 2 years
# - **Issue Date:** We have to remove all the r... |
import os
import sys
import tensorflow as tf
import logging
import numpy as np
import PIL
import argparse
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
NUM_CLASSES = 1
PROBABILITY_THRESHOLD = 0.6
handler = logging.StreamHandler(sys.stdout)
forma... |
"""
Classes and utilities to manage IxLoad application.
"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Optional
from trafficgenerator.tgn_app import TgnApp
from ixload.api import IxLoadUtils
from ixload.api.ixl_rest import IxlRestWrapper, IxlList
from ixload.ixl_objec... |
# MIT 6.034 Lab 4: Constraint Satisfaction Problems
from copy import deepcopy
class Constraint :
def __init__(self, var1, var2, constraint_fn) :
self.var1 = var1
self.var2 = var2
self.constraint_fn = constraint_fn
def reverse(self) :
return Constraint(self.var2, self.var1, lam... |
# ----------------------------------------------------------------
# Copyright 2016-2019 Cisco Systems
#
# 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/L... |
import os
import time
from math import ceil
import MNN
import cv2
import numpy as np
import torch
import utils.box_utils_numpy as box_utils
def predict(width, height, confidences, boxes, prob_threshold, iou_threshold=0.3, top_k=-1):
boxes = boxes[0]
confidences = confidences[0]
picked_box_probs = []
... |
# Copyright 2019-2020 Spotify AB
#
# 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... |
from common.scripts.binance_spot.impl.utils import JsonWrapper
from common.scripts.binance_spot.model.exchangeinformation import Symbol
class Fills:
def __init__(self):
self.price = 0.0
self.qty = 0.0
self.commission = 0.0
self.commissionAsset = ''
class Orders:
... |
# encoding: utf-8
from __future__ import unicode_literals
import os
from random import choice
import time
import pickle
import json
from twitter import Twitter, NoAuth, OAuth, read_token_file, TwitterHTTPError
from twitter.api import TwitterDictResponse, TwitterListResponse, POST_ACTIONS, method_for_uri
from twitter.... |
import argparse
import collections
import functools
import fractions
import json
import pathlib
import statistics
import sys
PARSER = argparse.ArgumentParser(description="Evaluate JSONs into LaTeX table")
PARSER.add_argument('-f',
'--formula',
metavar='DIR',
... |
import types
from collections.abc import Iterable
from typing import Optional, Tuple, Union
import astromodels
import numba as nb
import numpy as np
from threeML.io.logging import setup_logger
from threeML.plugin_prototype import PluginPrototype
__instrument_name = "n.a."
log = setup_logger(__name__)
_tiny = np.f... |
import torch
import torch.nn as nn
def extract(a, t, x_shape):
b, *_ = t.shape
out = a.gather(-1, t).float()
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
class DDPMv2(nn.Module):
def __init__(
self,
decoder,
beta_1=1e-4,
beta_2=0.02,
T=1000,
var... |
# -*- encoding: utf-8 -*-
import json
import socket
import time
import logging
log = logging.getLogger(__name__)
def _send_event(tag, data):
__salt__['event.send'](tag, data=data)
return {
'name': tag,
'result': True,
'changes': data,
'comment': ''
}
def begin_stage(nam... |
import copy
import cv2
import torch.nn.functional as F
import os.path as osp
import glob
import numpy as np
import torch
from mmdet.apis import init_detector, inference_detector
from mmcv.parallel import collate, scatter
from mmcv.ops.nms import batched_nms
from mmdet.datasets import replace_ImageToTensor
from mmdet.da... |
#!/usr/bin/env python3
import pygame
import sys
from pygame import gfxdraw
__author__ = '<NAME>'
# Maximum window size
MAX_X = 1024
MAX_Y = 1024
# Basic colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
# Univerisy of New Hampshire brand colors
BRAND_DARK = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.