text stringlengths 3.07k 22.1k |
|---|
import math
import numpy as np
# Geometry Constants
# Layer 1 has no absorber, layers 2 and 3 have absorber of different thickness
air_thick = 2
scint_thick = 20
back_dx = 3100
back_dy = 3100
back_numLayers1 = 0
back_numLayers2 = 100
back_numLayers3 = 0
back_abso2_thick = 25
back_abso3_thick = 50
back_layer1_thick = s... |
# Copyright (c) 2016-2018, The University of Texas at Austin
# & University of California, Merced.
#
# All Rights reserved.
# See file COPYRIGHT for details.
#
# This file is part of the hIPPYlib library. For more information and source code
# availability see https://hippylib.github.io.
#
# hIPPYlib is free software;... |
import collections
import torch
import inspect
import numpy as np
import argparse
def has_arg(fn, name):
""" Checks if a callable accepts a given keyword argument.
Args:
fn (callable): Callable to inspect.
name (str): Check if `fn` can be called with `name` as a keyword
argument.
... |
# <pep8-80 compliant>
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# ... |
import math
import cmath
import numpy as np
import pandas as pd
import pickle
import pyrealsense2 as rs
import cv2
def calculateAngleFromSlope(a, b):
#gives angle from slope wrt x-axis
if a[0]-b[0]!=0:
rad = math.atan((a[1]-b[1])/(a[0]-b[0]))
else:
rad = math.pi/2
deg = rad * 180 / mat... |
import asyncio
import datetime
from asyncio.events import AbstractEventLoop
from typing import List
from unittest.mock import AsyncMock, Mock
from uuid import UUID, uuid4
import nest_asyncio
import pytest
from _pytest.monkeypatch import MonkeyPatch
from d8s_hashes import sha256
from starlette.config import environ
fro... |
# -*- coding: utf-8 -*-
# MLToolkit (mltoolkit)
__name__="mltk"
"""
MLToolkit - a verstile helping library for machine learning
===========================================================
'MLToolkit' is a Python package providing a set of user-friendly functions to
help building machine learning models in d... |
import unittest
from coc.players import Player, ClanMember
from coc.clans import Clan
from coc.player_clan import PlayerClan
from coc.enums import (
HOME_TROOP_ORDER,
BUILDER_TROOPS_ORDER,
SPELL_ORDER,
HERO_ORDER,
ACHIEVEMENT_ORDER,
SIEGE_MACHINE_ORDER,
)
from coc.miscmodels import League, Lege... |
import numpy as np
import matplotlib as mpl
from matplotlib import _pylab_helpers
from matplotlib.rcsetup import interactive_bk as _interactive_bk
import matplotlib.pyplot as plt
import matplotlib.patches
from mpl_toolkits.mplot3d import Axes3D
import os
import time
def setup_for_latex(font_size=28):
# mpl.rc("fo... |
from tomriddle import cnf
from time import time
from sympy import symbols
import sympy.logic.boolalg as form
from operator import invert
from itertools import combinations
from pycosat import itersolve
from tomriddle import satbridge
def test_max_n_true():
symbs = symbols("a,b,c,d,e")
mapper = satbridge.Sy... |
#!/usr/bin/env python
from sv2_backend import format_chrom,reciprocal_overlap
from sv2Config import Config
import os,pybedtools
from pybedtools import BedTool
class Annotation():
def __init__(self):
self.cytoband={} # [(c,s,e)]=cytoband
self.excluded={}
self.repeatmasker={} #[(c,s,e)]= id,ovr
self._1kgp={} #[(... |
import os
import argparse
import sys
import h5py
import openslide
import numpy as np
import cv2
import subprocess
import json
import torch
import logging
import copy
import pandas as pd
from misc.utils import log_info
from docopt import docopt
import extract_arguments
import analyze_output
import stitching
def create... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from .containers import OrderedDict
from . import iniparse
from .compat import text_type, string_types, PY2, implements_to_string, implements_bool
from . import errors
from .tools import textual_list
f... |
import math
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from models.momory_pool import ReplayMemory
class Brain(nn.Module):
def __init__(self, lstm_input_channels=128, hidden_channels=128, num_fc_concat=128):
super(Brain... |
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
# Setup:
#
# Disable "White Balance Temperature, Auto"
# (Default value: 1)
# $ v4l2-ctl -d /dev/video2 --set-ctrl=white_balance_temperature_auto=0
# To confirm:
# $ v4l2-ctl -d /dev/video2 --get-ctrl=white_balance_temperature_auto
# white_balance_... |
from __future__ import annotations
import re
from copy import deepcopy
from dataclasses import dataclass
from typing import List, Union, Set
DEBUG = False
LINE_PARSE = re.compile(r'^(?P<units>\d+) \s units.* '
r'with \s (?P<hp>\d+) \s hit\spoints \s '
r'(?:\((?P<weaknes... |
import graphql
import pytest
from graphql import GraphQLNamedType
from hypothesis import assume, find, given
from hypothesis import strategies as st
from hypothesis_graphql import strategies as gql_st
from hypothesis_graphql._strategies.queries import value_nodes
SCHEMA = """
type Book {
title: String
author: Aut... |
'''
A number of utility functions and classes which do not easily fit into a single
place.
To avoid circular imports, this file must not import anything from
metashare.repository.editor.
'''
from django import template
from django.contrib.admin.options import ModelAdmin, IncorrectLookupParameters
from django.contrib.... |
import os
import logging
import sysrepo
import re
DEFAULT_TACACS_PORT = 49
DEFAULT_TACACS_TIMEOUT = 300
MAX_TACACS_SERVERS = 3
# FILE
PAM_AUTH_CONF = "/etc/pam.d/common-auth-gs"
NSS_TACPLUS_CONF = "/etc/tacplus_nss.conf"
NSS_CONF = "/etc/nsswitch.conf"
class InvalidXPath(Exception):
pass
logger = logging.getL... |
"""
Provide consistent and up-to-date ``__version__`` strings for Python
packages.
It is easy to forget to update ``__version__`` strings when releasing
a project, and it is important that the ``__version__`` strings are
useful over the course of development even between releases,
especially if releases are infrequent... |
from tkinter import *
from PIL.ImageTk import PhotoImage
from tkinter.filedialog import askdirectory
import numpy as np
import json
import random
import mediapipe as mp
import cv2
from PIL import Image, ImageTk
import os
import glob
file_id = 0
file_list = []
save_path = ''
def save(p):
# save_path = "./save"
... |
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import output... |
#===============================================================================================
# IUGG 2019 Plots
#
# INITIAL PROFILES O2, NITRATE, DIC, <NAME>
#
# * Extra figure: density profiles
#===============================================================================================
import cmocean as cm... |
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# This file is part of phonopy.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, thi... |
import os
import sys
import re
import csv
import argparse
import pandas as pd
import numpy as np
import deploymentMap_dwm as dwm_nodes
import deploymentMap_evb as evb_nodes
def distance(a, b):
return (
((a[0] - b[0]) ** 2) +
((a[1] - b[1]) ** 2)
) ** 0.5
def parse_file(log_file, results_file... |
import copy
import os
import os.path as osp
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import BaseModel, register_model
from .mlp import MLP
from cogdl.utils import spmm
def average_neighbor_features(graph, feats, nhop, norm="sym", style="all"... |
'''
Copyright 2021 Elex
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, distribute, sublicense, a... |
#!/usr/bin/env python
from __future__ import print_function
import os
import copy
import Queue
import roslib
import rospy
import std_msgs.msg
import cv2
import threading
import pandas as pd
import yaml
import json
import time
import datetime
import numpy as np
import jpeg4py as jpeg
from blob_finder import BlobFinder
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# main.py
#
# Copyright 2014 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including witho... |
from datetime import datetime
import json
import re
from math import ceil
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.utils.task_group import TaskGroup
from airflow.models import Variable
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPyth... |
#!/usr/bin/env python
import rospy
import sys
import math
import time
from statemachine import StateMachine, State
from robot.robot import Robot
from std_msgs.msg import String
from my_sys import log, SysCheck, logInOne
from methods.chase import Chase
from methods.attack import Attack
from methods.behavior import Behav... |
# 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... |
#!/usr/bin/env python
from __future__ import print_function
import collections
import errno
import getpass
import inspect
import itertools
import logging
import multiprocessing
import os
import progressbar
import random
import re
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
im... |
import sqlite3
from os.path import basename
import matplotlib.pyplot as plt
import json
FIG_SIZE = (15, 8)
def get_last_exec_time(db_conn):
res = db_conn.execute('SELECT MAX(timestamp) FROM benchmark_execs')
return res.fetchone()[0]
def generate_graph_throughput_with_increasing_number_of_flows(db_file_name... |
import aiohttp
import asyncio
import io
import ssl
import aiohttp.http_exceptions
from aiohttp.client import URL
from botocore.endpoint import EndpointCreator, Endpoint, DEFAULT_TIMEOUT, \
MAX_POOL_CONNECTIONS, logger, history_recorder, create_request_object
from botocore.exceptions import ConnectionClosedError
fro... |
import torch
import numpy as np
import SimpleITK as sitk
import matplotlib.pyplot as plt
def multi_class_score(one_class_fn, predictions, labels, one_hot=False, unindexed_classes=0):
result = {}
shape = labels.shape
for label_index in range(shape[1] + unindexed_classes):
if one_hot:
cl... |
from copy import deepcopy
import multiprocessing
from multiprocessing.pool import Pool
import random
import itertools
from core.buckets import BucketOrder, BucketOrderSortType
from core.buckets import BucketOrderInfo
from core.buckets import BucketExtend
from core.camera import Camera
from core.intersectio... |
import abc
import functools
import logging
import re
import subprocess
try:
import magic
except ImportError:
magic = None
import html.parser
from bs4 import BeautifulSoup
import lxml.etree as etree
logger = logging.getLogger(__name__)
def guess_encoding(buf, authorative=None):
encoding = authorative or... |
# coding: utf-8
"""
LSTM Time series predictions
python model_tf/1_lstm.py
"""
from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
simplefilter(action='ignore', category=DeprecationWarning)
import os, sys, inspect
from datetime import datetime, timedelta
import numpy as np
impo... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 5 16:15:06 2019
@author: dgbli
"""
import numpy as np
import pandas as pd
import pickle
import multiprocessing as mp
from landlab import RasterModelGrid, FIXED_VALUE_BOUNDARY
from landlab.components import FlowAccumulator
from landlab.utils.flow__distance import calcula... |
""" molecular graph
"""
# getters
from automol.graph._graph_base import atoms
from automol.graph._graph_base import bonds
from automol.graph._graph_base import atom_keys
from automol.graph._graph_base import bond_keys
from automol.graph._graph_base import atom_symbols
from automol.graph._graph_base import atom_implicit... |
# Copyright 2012-2017 Intel Corporation.
#
# This software is supplied under the terms of a license agreement or
# nondisclosure agreement with Intel Corporation and may not be copied
# or disclosed except in accordance with the terms of that agreement.
from collections import OrderedDict
import os
import sys
import ... |
from sqlalchemy import (
Boolean, Column, Integer, ForeignKey, String, UniqueConstraint
)
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Avatar(Base):
"""
This ta... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Modifications for Guinet et al.
# TODO
import io, os, ot, argparse, random
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of c... |
import os
import shutil
from io import BytesIO
from urllib.request import urlopen
from . import Package, submodules_type
from .. import archive, log, types
from ..builders import Builder, make_builder
from ..config import ChildConfig
from ..environment import get_cmd
from ..freezedried import FreezeDried
from ..glob i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Vers... |
"""
This is a sample HTTP server interface with the GPUSim backend,
which takes fingerprints as a JSON and returns results in JSON form.
"""
import os
import subprocess
import time
from PyQt5 import QtCore, QtNetwork
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
... |
"""
MIT License
Copyright (c) 2020 DashIO-Connect
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... |
import csv, json, requests, re, time, random
#register account with companies house and add an array keys into a file called apikeys.py
# TODO: Reimplement getting current postcode through filing history as quicker than sending requests
# TODO: Think about multithreading - issues with compatability
import apikeys
... |
"""
## Datapane Teams API
Datapane Teams includes features to automate your Python workflows and easily build and share data-driven apps and results with your teams.
Generally objects are created on the server via the static methods (rather than the constructor),
and the instance methods and fields are used to access... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import os
import numpy as np
import pandas as pd
import cv2
import albumentations as A
from albumentations.pytorch import ToTensorV2
from sklearn.metrics im... |
# !/usr/bin/env python
# -*- coding utf-8 -*-
#
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Author: <NAME>
# eMail: <EMAIL>
# Date: 11/10/2020
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#
import logging
import pandas as pd
import xarray as xr
from .helpers import median, grad, savgol
logger = logging.getLogger(__name__)
def... |
import unittest
import numpy as np
from controlinverilog import mechatronics
from controlinverilog.state_space import StateSpace
import controlinverilog as civ
import matplotlib.pyplot as plt
class TestLtiSystem(unittest.TestCase):
def test_sequence(self):
sys1 = get_system1()
norm_infc = mechat... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from .datasets import PremackDataset
from .equality_experiment import EqualityExperiment
import os
from pprint import pprint
from antra import *
import tests.interchange.utils as utils
import torch
from torch.nn import ReLU
from antra.interchange.batched import Batched... |
#!/usr/bin/python3
# This file extends sklearn's BinomialDeviance and GradientBoostingClassifier
# classes to keep track of the scaling gammas in gradient boosting trees.
# Additionally, the default GradientBoostingClassifier uses independent gammas
# per leaf. The AugmentedGradientBoostingClassifier also allows one t... |
#!/usr/bin/python3
# -*- coding: UTF-8
import os
import time
import requests
from bs4 import BeautifulSoup
from requests.structures import CaseInsensitiveDict
from colorama import Fore, init
from urllib3.exceptions import InsecureRequestWarning
from requests.packages.urllib3.exceptions import InsecureRequest... |
import os
import sqlite3 as sq
import click
import pyperclip
import re
from subprocess import PIPE, Popen
import json
import urllib.request
__version__ = '0.2.1'
# cmdline
def cmd(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return proces... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""
@Time 22/05/2018 3:30 PM 2018
@Author HJ<EMAIL>
@Email <EMAIL>
@Blog jhsa26.github.io
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.autograd as autograd
import torch.optim as optim
import utils
impo... |
# author: <NAME> (Group 24)
# contributors: <NAME>, <NAME>, <NAME>
# date: 2021-11-25
# last updated: 2021-11-27
'''This script models for the Crime Vancouver
Usage: modelling.py --input_path=<input_path> --out_path=<out_path>
Options:
--input_path=<input_path> Path to directory where the data are stored... |
from __future__ import absolute_import
import os
import math
import json
import itertools
import click
from ocrd.decorators import ocrd_cli_options, ocrd_cli_wrap_processor
from ocrd import Processor
from ocrd_utils import (
getLogger,
assert_file_grp_cardinality,
make_file_id,
MIMETYPE_PAGE
)
from o... |
#!/usr/bin/env python3
# TODO:
# * vfs:parent
# * stop using res(%d)
# * move more logic into alvo
# * use alvo for postprocessing, (actual file operations)
# * actually integrate HiStore
# * move files into place (poss. across filesystems)
import os, time, stat, hashlib, sys
from typing import List
from help impo... |
# G-Research Crypto Kaggle Project
# Running tf model based on vwap.
# I want to try this a couple of different ways :
# - Normalised (whole column)
# - Normalised (by each "row" in the 3d array)
# I think row based will be better, as Target is Growth not absolute
# Setup
import os
import matplotlib.pyplot as pl... |
from __future__ import print_function
from rosdistro import *
from rosdistro.dependency_walker import *
from rosdistro.release import *
from buildbot_ros_cfg.ros_deb import ros_debbuild
from buildbot_ros_cfg.ros_test import ros_testbuild
from buildbot_ros_cfg.ros_doc import ros_docbuild
## @brief The Oracle tells yo... |
"""
[10. Regular Expression Matching]
https://leetcode.com/problems/regular-expression-matching/
Question:正则表达式匹配
Method:DP - dynamic programming 动态规划
Implement regular expression matching with support for '.' and '*'.
实现正则表达式,支持'.' and '*'
'.' Matches any single character. '.' 点匹配任何字母
'*' Matches z... |
# =============================================================================
# Copyright (c) 2016, Cisco Systems, 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:
#
# Redistributions ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 1 14:58:57 2019
@author: <NAME>
"""
import os
import time
import pickle
import datetime
import numpy as np
import scipy.sparse as sp
from src.nmf import NMF_sp
from src.config import (
Node, FLAG_U, FLAG_V,
MAX_LEVEL, NUM_CLUSTER, PURIFY_TYPE, POI_LST, WORD_LST... |
import os
import sys
import glob
import h5py
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import time
import datetime
# Part of the code is referred from: http://nlp.seas.harvard.edu/2018/04/03/attention.html#positiona... |
import logging
import mxnet as mx
import numpy as np
from mxnet import autograd as ag
from tqdm import tqdm
from common.evaluate import evaluate
from common.parser import TrainingParser
from common.utils import get_context, parse_steps, get_lr, append_postfix
from dataset import get_dataset
from models import get_fea... |
"""
Copyright (c) 2022 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with t... |
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from params.generate_all import generate_all
from functions.vphpl_pphpl_calc import vphpl_pphpl_calc
#########Std dev varying functions#########
#Given binary inputs for ms, occ, fe, calculate the std dev version of PEIT1
def calculate_p... |
from bson.objectid import ObjectId
from app.common.stream.entry import IStream, ProxyStream, EncodeStream, RelayStream, TimeshiftRecorderStream, \
CatchupStream, TimeshiftPlayerStream, TestLifeStream, VodRelayStream, VodEncodeStream, ProxyVodStream, \
CodRelayStream, CodEncodeStream
from pyfastocloud.client_co... |
# Copyright 2020 <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, softw... |
import math
import h5py
import numpy as np
import torch
import torch.utils.data
from torch.utils.data.dataloader import default_collate
from ncls import NCLS64
from bisect import bisect_right
from numpy.lib.stride_tricks import as_strided
from scipy.fftpack import fft, fftshift # Fourier features
from scipy.signal... |
"""Finite-volume scheme for the full 2D image
The functions in this module allow to solve the modified Cahn-Hilliard equation
for the image-inpainting filter
Author: <NAME>
"""
import numpy as np
from scipy import optimize
#####################################################################################
#
# FUN... |
from flask.views import MethodView
from sqlalchemy import desc
from apps.order.models import OrderGoods
from utils.auth import login_required, request
from flask import render_template, redirect, url_for
from utils.extentions import db
from utils.tools import get_redis_connection
from .models import GoodsType, IndexGo... |
#!/usr/bin/python3
# coding: utf8
"""Get the french train schedules and its states, send SMS and send alert or text to Domoticz."""
import sys
import os
import sqlite3
import xml.etree.ElementTree as ET
from urllib.parse import quote
from urllib.error import URLError, HTTPError
import urllib.request
import argparse
imp... |
'''
Textual KD SLU
Copyright (c) 2021-present NAVER Corp.
Apache License v2.0
---
MIT License
Copyright (c) 2017 <NAME>
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, inclu... |
import discord
import asyncio
import logging
from discord.ext import commands
# self-created modules below
import lib.embedCreation as embedCreation #contains functions for creating an embed
import lib.dbfzFinder as dbfzFinder #contains functions for finding character and move details
# Get token from local dir tex... |
"""MIT License
Copyright (c) 2021 gunyu1019
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... |
#!python3
import argparse
import pandas as pd
import numpy as np
import os
from subprocess import run
def partial_cov_from_precision_matrix(p):
partial_cov_matrix = np.zeros(p.shape, dtype=np.float64)
for i in range(p.shape[0]):
for j in range(p.shape[1]):
partial_cov_matrix[i][j] = - p[i]... |
from __future__ import division
from __future__ import print_function
import os
import glob
import time
import random
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from utils import load_data, accur... |
import pickle
import numpy as np
from layer import *
num_classes = 2
train_points = np.array([[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1]])
train_labels = np.array([0, 0, 0, 1, 1, 1], dtype=int)
test_points = np.array([[0, 0], [0, 1], [1, 1], [2, 1], [1, 0], [2, 0]])
test_labels = np.array([0, 0, 1, 1, 0, 0], dtype... |
import json, os, re, sys, logging, shutil
from itertools import chain
from datetime import datetime
from pyspark.sql.dataframe import DataFrame
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.types import StringType, DoubleType, ArrayType
# find the project directory
ABS_F... |
import numpy as np
import torch
from torchvision.ops.boxes import batched_nms
def encode_boxes_to_anchors(boxes, anchors, eps=1e-8):
""" Create anchors regression target based on anchors
Args:
boxes: ground truth boxes.
anchors: anchor boxes on all feature levels.
eps: small number fo... |
"""Components for the training process of an auto-encoding GAN."""
import tensorflow as tf
from tensorflow.contrib import gan as tfgan
from collections import namedtuple
class AEGANModel(namedtuple('AEGANModel', tfgan.GANModel._fields + (
'encoder_real_outputs',
'encoder_gen_outputs',
'encoder_variables'... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .data_utils.numericalizer import FieldType
class StringEmbedCNN(nn.Module):
"""
PyTorch nn.Module for embedding strings for fast edit distance computation,
based on "Convolutional Embedding for Edit Distance (SIGIR 20)"
(code: ht... |
'''
A modul for basic interaction of custom scripts with the portal.
'''
__author__ = '<NAME>'
from lost.db import access
from lost.db import dtype, state
from lost.logic.file_man import FileMan
from lost.logic import log
from lost.pyapi import inout
import argparse
import datetime
import traceback
import os
from lost... |
import configparser
import os
from os.path import exists
from datetime import datetime, timedelta
import sys
from time import time
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QProcess, Qt, QThread, QTimer
from mainUi import Ui_MainWindow
from pandascontroller import DomainInp... |
import sublime, sublime_plugin, subprocess, _thread, re, os, io
HISTORY_SIZE = 16
HISTORY_FILENAME = '~/.sublimeexternalcommand_history'
class History:
'''
Command history management.
'''
def __init__(self, max_size, filename):
self.max_size = max_size
self.filename = os.path.expanduse... |
import copy
from zlib import crc32
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.utils import six
from django.utils.datastructures import SortedDict
import views
from columns import Column
from grid_registrar import register_grid
__author__ = 'zmbq'
# The meta cl... |
"""
Calculate Mean Average Precision (mAP) and F1 score for a set of bounding boxes corresponding.
Usage:
pythons calculate_map_score_per_class.py --detections_record=detections_all_xviewz151617_dota.record --label_map=1class.pbtxt
"""
from __future__ import absolute_import, division, print_function
from copy ... |
import copy
import gmpy
import numpy as np
def normalize(M, axis=-1):
M = M.astype(float)
if M.ndim > 1:
denoms = M.sum(axis=axis, keepdims=True)
else:
denoms = M.sum()
M = np.divide(M, denoms.astype(float), out=np.zeros_like(M), where=(denoms!=0))
return M
def is_stochastic(M):
... |
'''
/********************************************************************
*
* 文件名:support.py
*
* 文件描述:封装类
*
* 创建人: qiwei_ji, 2020年5月31日
*
* 版本号:1.1.3.0301_alpha
*
* 修改记录:63
*
********************************************************************/
'''
import numpy as np
import pandas as pd
import torch
import torch... |
import numpy as np
from numpy import random, uint8, zeros
from pyquil.gates import X, Y
from pyquil.quil import Program
from forest_benchmarking.rb import merge_sequences, fit_standard_rb, rb_dataframe, \
add_sequences_to_dataframe, run_rb_measurement, survivals_by_qubits, add_survivals, survival_statistics, \
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from jd_assistant import Assistant
import random
import requests
import datetime
import json
import time
import os
# if os.name == 'nt':
# import win32api
from log import logger
import socket
import urllib
from timer import Timer, getTimeDurationDate,toTimeStamp
# impor... |
from collections import OrderedDict
import torch
import logging
import numpy as np
from torch.nn import quantized
from torch.nn.modules import activation
from torch.nn.quantized.modules import DeQuantize, Quantize
from torch.quantization.stubs import DeQuantStub, QuantStub
from mmskeleton.utils import call_obj, import_... |
import csv
import os
from dataclasses import dataclass
from datetime import datetime
from bs4 import BeautifulSoup as bs
from utils import (URL, get_content, is_url_valid, logger, string_to_date)
@dataclass
class Article:
url: str
title: str
author: str
views: int
shares: int
date: str
d... |
# coding=utf-8
# 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
# distr... |
import datetime
import argparse
import os
import logging
import json
import sys
from Aries.outputs import LoggingConfig, PackageLogFilter
from .basespace.cmd import basespace_command
from .fastq_file import ReadIdentifier
from .fastq_pair import FASTQPair
from .fastq.demux import DemultiplexInline, DemultiplexDualIndex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.