text stringlengths 3.07k 22.1k |
|---|
__author__ = 'menghui'
# coding=utf-8
import mgr.redistip as redis
import settings
from datetime import *
import json
from sql import sqlGenerator
from sql import sqlParse
import mgr.dbtip as dbtip
def addinnerjoin(row, name, prekey, buffer):
"""
添加一个InnerJoin节点,与innerjoinfromcache方法配合使用
:param row:
... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
# ==================== Constants ====================
IMAGE_DIR = "./q2_images/"
LEFT_IMAGE_NAME = "000020_left.jpg"
RIGHT_IMAGE_NAME = "000020_right.jpg"
OUT_DIR = "./out/q2/"
BOUNDING_BOX_FILE_NAME = "000020.txt"
ALL_CALIB_FILE_NAME = "000020_allcalib.txt... |
from gpaw import GPAW,Mixer,Davidson
from ase.build import bulk
from ase.db import connect
import os
import BASIC.optimizer as opt
from ase.parallel import parprint
import numpy as np
import sys
from ase.io import read, write
from ase.parallel import paropen, parprint, world
from ase.calculators.calculator import kptde... |
import collections
import json
import logging
from base64 import b64encode
from urllib import parse as urlparse
from django.conf import settings
from kubernetes import client, config
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from awx.main.utils.common ... |
#! usr/bin/env python3
"""
Author: <NAME>
Function: This script maps the fastq files against the pathways (in
fasta format).
Usage: use -h flag
Explanation:
This script is designed to map the fastq files against a reference, in this case
the reference is the file containing all the pathways and bacterial reference
... |
# -*- coding: utf-8 -*-
"""Export data to a wikitable"""
from __future__ import annotations
from datetime import timedelta
import itertools
from sqlalchemy.orm import joinedload, load_only, contains_eager
from sqlalchemy.orm.session import Session
from typing import Optional, Set, Collection
from ...model import Bas... |
import re
from abc import ABC
from enum import Enum
from typing import Optional, Union
import numpy as np
# Hydra and OmegaConf
from hydra.conf import dataclass, MISSING
from omegaconf import DictConfig
# Project Imports
from pylidar_slam.common.modules import _with_g2o
from pylidar_slam.common.utils import assert_d... |
import re
import StringIO
class nexus(object):
"""Create a nexus file object::
f = nexus(filename_or_data,[ mode="r"])
The API for the nexus file object closely follows the interface of the
standard python file object.
The mode can be one of:
* 'r' - reading (default)
* 's' - strin... |
import logging
import uuid
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
from server.library.quiz.recommender import recommend
from server.library.db.stats import *
tasks = {}
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 13:29:17 2021
@author: reideej1
:DESCRIPTION:
- Scrape annual massey rankings for NCAA College Football
:REQUIRES:
- Refer to `Package Import` section below for required packages
:TODO:
- NONE
"""
#==========================... |
# Open the designer from console: pyqt5-tools designer
# Pass the designer to python code: pyuic5 template.ui -o template.py -x
import sys
import winsound
import time
from functools import partial
from queries import Pomodoro
from PomodoroUI import PomodoroUI
from RecallsUI import Recalls
from PyQt5.QtWidgets import... |
# -*- coding: utf-8 -*-
"""Parse Singularity definition files for information about
installed apps etc."""
_LABEL_SET = frozenset(["%applabels", "%labels"])
_HELP_SET = frozenset(["%apphelp", "%help"])
_RUN_SET = frozenset(["%apprun", "%runscript"])
_MY_KW_SET = _LABEL_SET | _HELP_SET | _RUN_SET
def chunk_string(in... |
#! -*- coding:utf-8 -*-
# 三元组抽取任务,基于GlobalPointer的仿TPLinker设计
# 文章介绍:https://kexue.fm/archives/8888
# 数据集:http://ai.baidu.com/broad/download?dataset=sked
import json
from bert4torch.layers import GlobalPointer
from bert4torch.tokenizers import Tokenizer
from bert4torch.models import build_transformer_model, BaseModel
... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the Lic... |
"""Configuration of pytest."""
import json
import uuid
from pathlib import Path
import databroker
import matplotlib.pyplot as plt
import numpy
import numpy as np
import pyFAI
import pytest
from databroker.v2 import Broker
from diffpy.pdfgetx import PDFConfig, PDFGetter
from pkg_resources import resource_filename
from... |
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, <NAME> (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, <NAME> (www... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 14:35:23 2018
a module for orthogonal linear separation analysis (OLSA)
@author: setsuo,shotaro, and tadahaya
"""
import sys
import csv
import math
import os
import numpy as np
import pandas as pd
np.seterr(divide='ignore', invalid='ignore')
import time... |
# coding=utf-8
# Copyright (c) 2020, PCL. 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... |
import os
import re
import traceback
from typing import Optional
import discord
from discord.ext import commands
from pretty_help import PrettyHelp
from dotenv import load_dotenv
from logger import getLogger, set_global_logging_level
from curation_validator import get_launch_commands_bluebot, validate_curation, Curat... |
# -*- coding:utf-8 -*-
# coding:utf-8
import os, cv2, subprocess, shutil
from cv2 import VideoWriter, VideoWriter_fourcc, imread, resize
from PIL import Image, ImageFont, ImageDraw
ffmpeg = r'E:\Develop\ffmpeg\bin\ffmpeg.exe'
code_color = (169,169,169) # 颜色RGB 默认灰色 ,'' 则彩色
# 像素对应ascii码
#ascii_char = list("$@B%8&WM#*o... |
# -*- coding: utf-8 -*-
"""
Lyndon words
"""
#*****************************************************************************
# Copyright (C) 2007 <NAME> <<EMAIL>>,
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be useful,
# but W... |
import pytest
import onigurumacffi
FOO_RE = onigurumacffi.compile('^foo')
ABC_RE = onigurumacffi.compile('(a+)B+(c+)')
UNICODE_RE = onigurumacffi.compile('.*?(🙃+)')
REGSET = onigurumacffi.compile_regset('a+', 'b+', 'c+')
def test_regex_compiles():
assert FOO_RE is not None
def test_regex_repr():
assert r... |
from collections import namedtuple
import time
import logging
import numpy as np
import pickle
from es_distributed import tf_util
from es_distributed.policies import policies
from es_distributed.config import Result
from .common import SharedNoiseTable, RunningStat
from . import algo
log = logging.getLogger(__name... |
"""Base for all models."""
from abc import ABC
from typing import Any, Callable, Deque, Dict, Iterator, Optional, Type, Union
from .const import EMPTY_PAYLOAD, EVENT_PLACEHOLDER, LOGGER
from .options import OZWOptions
class ItemCollection:
"""Initialize an item collection."""
def __init__(self, item_class: ... |
import argparse
import os, sys
import math
import time
import tabulate
import copy
import torch
import numpy as np
from subspace_inference import data, models, utils, losses
from subspace_inference.posteriors import SWAG
from subspace_inference.posteriors.proj_model import SubspaceModel
from subspace_inference.poste... |
# Copyright 2022 <NAME>.
#
# 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, soft... |
"""
This creates Figure 4. Comparison of Experimental verus Predicted Activity across IL2 and IL15 concentrations.
"""
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.stats import pearsonr
from .figureCommon import subplotLabel, getSetup, global_legend, calc_dose_response, catplot_comparison, nl... |
# -*- coding: utf-8 -*-
import unittest
from rowgenerators.rowpipe import Column
from rowgenerators.exceptions import ConfigurationError
def ct(t):
col = Column('name', datatype='str', transform=t)
segs = col.expanded_transform
o = []
for seg in segs:
seg_str = []
if seg.in... |
#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of... |
# XML-to-dict code from here:
# http://code.activestate.com/recipes/410469-xml-as-dictionary/
from collections import OrderedDict
from xml.etree import ElementTree
class XmlListConfig(list):
def __init__(self, aList):
for element in aList:
if element:
# treat like dict
... |
# -*- coding: utf-8 -*-
"""
Demetrius: Find and copy files and their parent directories from a source
directory to a destination directory .
@author: johwi
"""
import json
import os
import sys
import shutil
import pandas as pd
import argparse
from spinner import Spinner
# TO-DO: Allow user to decide to save informa... |
"""
Classes to handle Carla sensors
"""
import math
import numpy as np
import tf
from cv_bridge import CvBridge
from geometry_msgs.msg import TransformStamped
from sensor_msgs.msg import CameraInfo
from sensor_msgs.point_cloud2 import create_cloud_xyz32
from std_msgs.msg import Header
from carla.sensor import Camera,... |
import json
import pickle
import struct
class MLPloader:
""" Class for managing MLP data """
def exportToJson(self):
""" Export MLP as json file, so that it can be read
without other dependencies
-> Json Model can be read by CoDeSys Script Engine directly
"... |
#!/usr/bin/env python3
# -*- coding: utf-8
"""
Script that simulates data for benchmarking of DestVI.
Created on 2020/02/03
@author romain_lopez
"""
import os
import click
import numpy as np
np.random.seed(0)
from logzero import logger
from utils import get_mean_normal, categorical
from scipy.spatial.distance impor... |
#! /usr/bin/env python
import os
import warnings
from glob import glob
from six import string_types
from .error import BadNameError, BadRegistryError
from .standardname import StandardName
def load_names_from_txt(file_like, onerror="raise"):
"""Load names from a text file.
Parameters
----------
fil... |
import os
import shutil
from datetime import date
from pathlib import Path
from zipfile import ZipFile
import pandas as pd
import requests
from tqdm import tqdm
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_PATH = os.path.join(BASE_DIR, 'data')
KEYS = ('candidates', 'parties', 'committe... |
import matplotlib.pyplot as plt
from importlib import import_module
from types import MethodType
import config, data
from base import nbprint
###############################################################################
# Exceptions
###############################################################################
cl... |
import json
import os
from openpyxl import load_workbook
# from bop_json_convert2 import insert_cell_value
file_dir = os.path.dirname(os.path.abspath(__file__))
# wb = load_workbook(os.path.join(file_dir, "excels/BOP.xlsx"), read_only=True)
# wb2 = load_workbook(os.path.join(file_dir,"excels/WC.xlsx"), read_only=True... |
from paper_1.evaluation.classification_metrics import ClassificationMetrics
from tensorflow.python.summary.summary_iterator import summary_iterator
from paper_1.data.data_loader import read_tsv_file
import matplotlib.pyplot as plt
from typing import List, Union
import seaborn as sb
import pandas as pd
import numpy as n... |
# SPDX-FileCopyrightText: Copyright (c) 2020 <NAME> for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_tla202x`
================================================================================
Library for the TI TLA202x 12-bit ADCs
* Author(s): <NAME>
Implementation Notes
--------------------
**... |
from typing import List, Tuple
from flask import json
from flask.blueprints import Blueprint
import logging
from flask_login import login_required, current_user
from flask.globals import request
from waitlist.permissions import perm_manager
from waitlist.storage.database import WaitlistEntry, Shipfit, Waitlist, Histo... |
"""
Copyright 2017-2019 Government of Canada - Public Services and Procurement Canada - buyandsell.gc.ca
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
... |
import json
#Stellt einen Quader dar
class Quader:
#Construktor
def __init__(self, x, y, z, w, h, d, index = 0):
self.x = x
self.y = y
self.z = z
self.w = w
self.h = h
self.d = d
self.index = index
#Überlappt dieser Quader mit dem gegebenen Quade... |
import time
import copy
import random
from math import exp, ceil, log
from os.path import join, dirname, abspath
import torch.optim as optim
import wandb
from matplotlib import pyplot as plt
from helper.replay_memory import ReplayMemory, Transition
from k_choice.graphical.two_choice.full_knowledge.RL.DQN.constants im... |
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
import logging
import subprocess
import fcntl
import os
import sys
import platform
ON_... |
import numpy as np
from numpy import inf
import math
class RandomPlayer():
def __init__(self, game):
self.game = game
def play(self, board):
a = np.random.randint(self.game.getActionSize())
valids = self.game.getValidMoves(board, 1)
while valids[a] != 1:
a = np.rand... |
import datetime
from django.conf import settings
import logging
from openpyxl import load_workbook
from collections import OrderedDict
import psycopg2
import pytz
import titlecase
PERTH = pytz.timezone('Australia/Perth')
LOGGER = logging.getLogger('sync_tasks')
alesco_date_to_dt = lambda d: PERTH.localize(datetime.dat... |
import sys
import os
import time
import string
import re
import time
import shutil
from mimetypes import types_map
from urllib import quote, unquote
from resources.markup import *
APP_ROOT, file_name = os.path.split(os.path.abspath(__file__))
TEMPLATES = os.path.join(APP_ROOT, "resources", "TEMPLATES")
... |
import json
import os
import sys
import time
import types
from time import gmtime, strftime
import yaml
from django.contrib.auth.models import Group, User
from termcolor import colored
import mlpipe.mlpipe_utils as mlpipeutils
from mlpipe.job_utils import JobRunner, mlpipeBuildinJob
from mlpipe.models import Data, Jo... |
import os
import sys
import numpy as np
from tqdm import tqdm
def create_dataset_cli(argvs=sys.argv[1:]):
import argparse
from classifier_3D.utils.path import get_data_path
from classifier_3D.utils.ply_file import read_ply, write_ply
from range_net import (
CITY_INFERANCE_FOLDER,
PAT... |
# found a way to include it more easily.
'''
SDL2 Window
===========
Windowing provider directly based on our own wrapped version of SDL.
TODO:
- fix keys
- support scrolling
- clean code
- manage correctly all sdl events
'''
__all__ = ('WindowSDL2', )
import sys
from os.path import join
from kivy ... |
import sys
sys.path.insert(0, '../')
import matplotlib.pyplot as plt
import cv2
import json
import numpy as np
from mv3dpose.tracking import Track
from os.path import isdir, join, isfile
from os import listdir, makedirs
import mv3dpose.geometry.camera as camera
import shutil
from mpl_toolkits.mplot3d import Axes3D
from... |
# Copyright 2020 The TEMPO Collaboration
#
# 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... |
# -*- coding: utf-8 -*-
"""
This module contains the general resources to be called by the main api
"""
from __future__ import absolute_import
from __future__ import print_function
from flask import request
from aiida.restapi.resources import BaseResource
from aiida_post.submit.distributor import distribute
def buil... |
from math import floor, sqrt
import random
import torch
def schlichtkrull_std(shape, gain):
"""
a = \text{gain} \times \frac{3}{\sqrt{\text{fan\_in} + \text{fan\_out}}}
"""
fan_in, fan_out = shape[0], shape[1]
return gain * 3.0 / sqrt(float(fan_in + fan_out))
def schlichtkrull_normal_(tensor, sha... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
Critical Net
=====
# An open-source Python implementation of the critical net algorytm based on
"<NAME>., <NAME>., <NAME>. (2010) Critical Nets and Beta-Stable Features for Image Matching.
In: <NAME>., <NAME>., <NAME>. (eds) Computer Vision – ECCV
2010. ECCV 2010. Lecture Notes in Computer Science, vol 6313. Sprin... |
# coding=utf-8
# Copyleft 2019 project LXRT.
import json
import os
import pickle
import numpy as np
import torch
from torch.utils.data import Dataset
from param import args
from utils import load_obj_tsv
from nltk.translate.bleu_score import corpus_bleu
# Load part of the dataset for fast checking.
# Notice that he... |
# coding: utf-8
import time
import os
import json
import psutil
import random
# import asyncio
from client import Client
from pprint import pprint
import jsonrpcclient
def sync_wallet_data():
ips = [
"192.168.205.221",
"192.168.202.163",
"192.168.202.162",
"192.168.2... |
from os import listdir
from PySide6 import QtCore
from PySide6 import QtWidgets
from PySide6.QtGui import QAction, QBrush, QColor, QIcon, QPainter, QPen, QPixmap, QTransform
from PySide6.QtWidgets import QCheckBox, QGraphicsItem, QGraphicsScene, QGraphicsWidget, QHBoxLayout, QLabel, QMenu, QMenuBar, QPushButton, QScrol... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch.nn.init as init
import math
import cv2
import numpy as np
import os
model_urls = {'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth'}
class VGG(nn.Module):
def __init__(se... |
from import_lib import *
from setting import *
Current_User = ""
Mode = 0
store_id = ["1RKVPuWTM1FPYXU09QZkMfPXQ9PJ6OhOxrNGDX7ISL7U" #normal breakfast
,"1f-WtnvXj4lStS0Fj1LH_oUMjqTewXpKr2Wt-3iknm5k" #health breakfast
,"1JjIVrEG8ENISzTb8LsTFH8QfwkYhCOGlIns5umvZm0Q" #dead breakfast
... |
'''
Machine learning APP
'''
import numpy as np
import matplotlib.pyplot as plt
import h5py
def sigmoid(Z):
A = 1/(1+np.exp(-Z))
cache = Z
return A, cache
def relu(Z):
A = np.maximum(0,Z)
assert(A.shape == Z.shape)
cache = Z
return A, cache
def relu_backward(dA, cache):
Z = cache
... |
"""
Distributed evaluating script for part segmentation with ShapeNetPart dataset
"""
import argparse
import os
import sys
import time
import json
import random
import numpy as np
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(ROOT_DIR)
import torch
from tor... |
## this tool is the core function of cnv and snv analysis
## author: taozhou
## email: <EMAIL>
import matplotlib as mpl
mpl.use('Agg')
import warnings
warnings.filterwarnings("ignore")
import itertools
import seaborn as sns
import matplotlib.pylab as plt
import matplotlib.colors as mc
from genecast_package... |
import pygame
import time
import sys
class Dancer:
def __init__(self, screen, x, y):
self.screen = screen
self.x = 204
self.y = 170
self.image_idle = pygame.image.load('dancer_idle.png')
self.image_idle = pygame.transform.scale(self.image_idle, (233, 300))
self.imag... |
import dash_core_components as dcc
import dash_html_components as html
from urllib import parse
REMARKS_STYLE = {
# format to look like a slack inline code block, except pink
'backgroundColor': 'rgba(29, 28, 29, 0.04)',
'color': 'rgb(224, 30, 90)',
'border': '1px solid rgb(210, 210, 210)',
'border... |
# -*- coding: utf-8 -*-
""" POI Import/Export
@requires: U{B{I{gluon}} <http://web2py.com>}
@requires: U{B{I{shapely}} <http://trac.gispython.org/lab/wiki/Shapely>}
@copyright: (c) 2010-2021 Sahana Software Foundation
@license: MIT
Permission is hereby granted, free of charge, to any person
... |
"""Dataset modules
Each considered dataset is represented by its own module, and its own class
that inherits from the generic Dataset class.
"""
import abc
import json
from multiprocessing import Pool
import os
import cv2
import daiquiri
import geopandas as gpd
import numpy as np
from osgeo import gdal
from PIL impo... |
#Basic Requirement
import os
import sys
import json
#Usage
usage = 'Usage: python3 ' + sys.argv[0] + ' <configuration file path>'
#Conf Loader
if len(sys.argv) < 2:
print(usage)
sys.exit()
else:
conf = json.load(open(sys.argv[1], encoding = 'utf-8'))
#Access_key
access_key_id = conf['Access_Key_... |
import io
import os
import os.path
import string
import random
import datetime
import argparse
def generateWord(min_len=1, max_len=10):
length = random.randint(min_len, max_len)
word = ''.join(random.choice(string.ascii_letters) for _ in range(length))
return word
def generateSentence(words):
return... |
import re
import math
# This file is part of https://github.com/cpina/science-cruise-data-management
#
# This project was programmed in a hurry without any prior Django experience,
# while circumnavigating the Antarctic on the ACE expedition, without proper
# Internet access, with 150 scientists using the system and d... |
"""Trains a Convolutional Neural Network on the MNIST dataset."""
from functools import partial
from kfp import components, dsl
from kfp.components import InputBinaryFile, OutputBinaryFile, OutputTextFile
from .common import attach_output_volume
func_to_container_op = partial(
components.func_to_container_op,
... |
import asyncio
from datetime import datetime
from random import choice
import pytz
import common
from cogs.drinkingcog import consume_drink
from cogs.duelcog import item_chance_roll
from discord.ext import commands
from objs.duel_item import get_name, get_slot
from objs.weekend_games import pretty_date
class Gameti... |
import torch
import os
import logging
import functools
from dataset import Replica
from dataset import ScanNet
from torch.utils.tensorboard import SummaryWriter
from torch.optim import SGD, Adam, ASGD, Adamax, Adadelta, Adagrad, RMSprop
from torch.optim.lr_scheduler import MultiStepLR, ExponentialLR, CosineAnnealingL... |
import sympy
from devito.ir.support import (Scope, IterationSpace, detect_flow_directions,
force_directions)
from devito.ir.clusters.cluster import PartialCluster, ClusterGroup
from devito.symbolics import CondEq, xreplace_indices
from devito.tools import flatten
from devito.types import... |
#! /bin/python
import os
import sys
import json
# this is a task called by multiple processes,
# so we need to restrict the number of threads used by numpy
from elf.util import set_numpy_threads
set_numpy_threads(1)
import numpy as np
import luigi
import vigra
import nifty.tools as nt
from elf.segmentation.watershed... |
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
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/LI... |
# Copyright 2021 The Deluca Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
import math
import random
import numpy as np
from .spp import phsppog
def scale_boxes(bboxes, scale, image_shape=[1333, 1333]):
"""Expand an array of boxes by a given scale.
Args:
bboxes (Tensor): Shape (m, 4)
scale (float): The scale factor of bboxes
Returns:
(Tensor): Shape (m, ... |
import pymysql
from flask import Flask, render_template, request, flash
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import SubmitField, SelectField, RadioField, HiddenField, StringField, IntegerField, FloatField
from wtforms.validators import InputRequired, Length, Regexp, NumberR... |
"""Unit tests for the custom code index function."""
from datetime import datetime, timedelta
from unittest.mock import Mock, patch
import pytest
from pyspark.sql import functions as F
from getl.block import BlockConfig, BlockLog
from getl.fileregistry.entrypoint import s3_date_prefix_scan
from getl.fileregistry.s3_d... |
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
class Actor:
def __init__(self, features, n_actions, layer_1_nodes, layer_2_nodes, action_bound, tau, learning_rate, batch_size, name):
self.tau = tau
self.action_bound = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import torch
import numpy as np
from torch.autograd import Variable
import logging
import matplotlib.pyplot as plt
from rdkit.Chem.rdmolfiles import MolFromPDBBlock
from rdkit.Chem import AllChem
from rdkit import DataStructs
from PIL import Image
import heapq
imp... |
#!/usr/bin/env python3
"""
poriluk.py 0.2 - Info Leakage Tactical Exploitation Tool
Copyright (c) 2017 <NAME> <<EMAIL>>
"The Other Way to Pen-Test" --HD Moore & Valsmith
I've always been a big proponent of a tactical approach
to penetration testing that does not focus on exploiting
known software vulnerabilities, bu... |
""" Latin-hypercube parameter design """
import itertools
import logging
from pathlib import Path
import re
import subprocess
import numpy as np
from . import cachedir, parse_system
def generate_lhs(npoints, ndim, seed):
"""
Generate a maximin LHS.
"""
logging.debug(
'generating maximin LH... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import time
from PySide import QtCore, QtGui
from . import _spotting, _dxcc, _bandplan, _config, _windowmanager
COLOR_SPOT = QtGui.QColor(255, 120, 120)
COLOR_BACKGROUND = QtGui.QColor(200, 200, 200)
COLOR_BAND = QtGui.QColor(150, 150, 150)
COLOR_BAND_SELEC... |
import os
import io
import csv
import json
import string
import random
import cv2
import glob
import torch
import torchvision
import numpy as np
from shutil import copyfile
from PIL import Image, ImageDraw, ImageFilter
CPU_DEVICE = torch.device('cpu')
CUDA_DEVICE = torch.device('cuda')
imgToTensor = torchvision.tr... |
#!/usr/bin/env python
import numpy as np
import numpy as cp
import pickle
import argparse
from sklearn.datasets import make_classification, make_moons, make_circles
train = False
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dataset", default=1, type=int, help="Help text")
parser.add_argument("--x1"... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import functools
import numpy as np
import xarray as xr
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.collections import PatchCollection
import matplotlib.patches as Patches
GREY = "#7F7F7F"
GREEN = "#679436"
RED = "#A01914"
BLUE = "#4F6DB8"
YELLOW = "#FABC3C"
TOTAL_... |
hellowStr = "Hellow world!"
hellowByte = bytes(hellowStr, encoding='ascii')
print(hellowByte)
print(hellowByte[0])
# 输出
# b'Hellow world!'
# 72
hellowBytes = "Hellow wolrd!".encode(encoding='ascii')
print(hellowBytes)
print(hellowBytes[0])
hellowStr = hellowBytes.decode(encoding='ascii')
print(hellowStr)
# b'Hellow wol... |
from abc import abstractmethod
import gym
from gym.spaces.discrete import Discrete
from gym.spaces.multi_discrete import MultiDiscrete
import numpy as np
class AbsEnv(gym.Env):
def __init__(self, low_s, high_s, low_a, high_a, disc_s=False,
disc_a=False):
self.low_s, self.high_s = low_s, h... |
import logging
class WWTotalPriceResponse(object):
logging.basicConfig(filename='worldpay-within-wrapper.log',level=logging.DEBUG)
def __init__(self):
logging.info('initialised WWPrice')
def setServerId(self, serverId):
self.serverId = serverId
def setClientId(self, clientId):
... |
import sys
import random
random.seed(1998)
epsilon = 10 ** -5
class Datasets:
def __init__(self, pos, neg, all_symbols, bestk):
self.pos = pos
self.neg = neg
self.all_symbols = [i for i in all_symbols]
self.bestk = bestk
self.first_pruning()
def first_pruning(self):
... |
r"""Implementation of Spectral Residual based Similarity
Code is based on MATLAB version for computations in pixel domain
https://github.com/Netflix/vmaf/blob/master/matlab/strred/SR_SIM.m
References:
https://sse.tongji.edu.cn/linzhang/ICIP12/ICIP-SR-SIM.pdf
"""
import functools
from typing import Union
import tor... |
import json
import pathlib
import sys
import tempfile
import time
import traceback
from base64 import b64encode
from datetime import timedelta
import click
import requests as requests
from metadata.generated.schema.entity.data.table import Table
from metadata.generated.schema.entity.services.connections.metadata.open... |
import tensorflow as tf
# +
import tensorflow as tf
from keras_transformer.extras import ReusableEmbedding, TiedOutputEmbedding
from keras_transformer.position import TransformerCoordinateEmbedding
from bert_concept_embeddings.custom_layers import EncoderLayer, TimeSelfAttention, TimeAttention, Encoder
def time_att... |
from __future__ import print_function
import math
import overlap
def CalcTriangleAng(pts, angleCache, pt1, pt2, pt3):
angId = (pt1, pt2, pt3)
if angId in angleCache:
return angleCache[angId]
#Angle is computed on pt3. pt1 and pt2 define the side opposite the angle
pt1v = pts[pt1]
pt2v = pts[pt2]
pt3v = pts[p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.