text stringlengths 3.07k 12.6k |
|---|
"""
Custom hyperparameter functions.
"""
import abc
import copy
import math
import random
import itertools
from typing import List
import rlkit.pythonplusplus as ppp
import collections.abc
class Hyperparameter(metaclass=abc.ABCMeta):
def __init__(self, name):
self._name = name
@property
def name(... |
import os
from boto3.dynamodb.conditions import Key
from logzero import logger
import logzero
from find_sale_in_wish_list.amazon_wish_list import WishList, KindleBook
from find_sale_in_wish_list.headless_chrome import HeadlessChrome
import boto3
import locale
import urllib.parse
import json
from decimal import Decimal... |
from django.conf import settings
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import pre_delete, pre_save
from django import forms
from django.utils.module_loading import import_string
from deployments.models import DeploymentInstance
from ast import literal_eval
from ... |
from pyspark import SparkContext, SparkConf
from time import time
import argparse
from operator import add
from random import random
import os
# initial settings to accept incoming dataset and k number of partitions
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file_path', help='path/to/file.txt', re... |
import global_args
global_args._init()
import os
import random
import time
import cv2
import numpy as np
import logging
import argparse
import shutil
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision
import tor... |
#!/usr/bin/env python
# Copyright (c) 2014 Qumulo, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
"""
signedimp.compat.esky: esky integration support code for signedimp
This module contains support for using signedimp together with the "esky"
auto-update module. Use the "get_bootstrap_code" function to get code for
a custom chainloading function, which will verify the chainloaded exe before
executing it. Thi... |
import numpy as np
from prime_infection import infection_rate
from prime_incubation import incubation_fcn
inc_median_lo, inc_median_hi = 1.504, 1.755
inc_sigma_lo, inc_sigma_hi = 0.271, 0.542
# Gauss-Legendre quadrature
nquad = 30
gauss_x,gauss_w = np.polynomial.legendre.leggauss(nquad) # x in [-1,1]
# Convolutio... |
import numpy
from ..tractography import Tractography
from . import tract_operations
from ..tensor import scalar_measures
try:
from collections import OrderedDict
except ImportError: # Python 2.6 fix
from ordereddict import OrderedDict
def compute_all_measures(tractography, desired_keys_list, scalars=None, ... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
import bmesh
from funcs.general_functions import *
LABEL = "Icosahedron"
OPERATOR = "mesh.create_icosahedron"
# create operator
class MESH_OT_CreateIcosahedron(bpy.types.Operator):
bl_idname = OPERATOR
bl_label = LABEL
def execute(self, context):
(obj, mesh) = createNewEmptyObject(LABEL)
... |
"""
Tests physio_obj.py
"""
import numpy as np
from phys2bids import physio_obj as po
from pytest import raises
# Tests is_valid
def test_is_valid():
test_list = [0, 1, 1, 2, 3, 5, 8, 13]
valid_output = po.is_valid(test_list, list, int)
assert valid_output == test_list
test_array = np.array([0, 1, 1... |
"""Represent the main entry point for the pipeline tool."""
# 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, including without limitation the... |
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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... |
from scipy.stats import mode
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import multivariate_normal, bernoulli, betabinom, multinomial
from sklearn.datasets import load_iris
class GMM:
def __init__(self, k, max_iter):
... |
from __future__ import print_function
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
import torch
class FCNet(nn.Module):
"""Simple class for non-linear fully connect network
"""
def __init__(self, dims, act='ReLU', dropout=0):
super(FCNet, self).__init__()
laye... |
"""
Copyright (c) 2016-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, including without limitation the rights
to use, copy, modify, merge, publish, distribute, su... |
#################################################################
# CSE 231 Project 9
#
# Lists, Sets, Functions and Dictionaries
# A Banner and Menu is displayed
# User is asked to input a number between 1-4
# If 1 is inputted, a table of cracked passwords is shown
# If 2 is inputted,... |
#!/usr/bin/env python
import pandas as pd
import pytest
import py_qualtrics_api as pqa
import time
@pytest.fixture
def api_instance():
return pqa.QualtricsAPI('config_test.yml')
@pytest.fixture
def mail_list_recs():
em = ['<EMAIL>', '<EMAIL>']
fn = ['Joe', 'Sally']
ln = ['Sample', 'Smith']
xref ... |
import numpy as np
from sklearn.datasets import fetch_openml
from nn_layers import FullyConnect, Activation, Softmax, BatchNormalization, Conv, TrasposedConv
import matplotlib.pyplot as plt
def noise(n_x, n_d):
return np.random.randn(n_x, n_d)
def bce_loss(pred, y):
eps = 1e-20
return -((1 - y) * np.log... |
# Common functions
import tensorflow as tf
from vision.foreground_removal.pix2pix.utils.dataset import remove_portion, normalize
from vision.foreground_removal.yolo.yolov3.dataset import transform_images
import numpy as np
import math
def read_image(input_file):
img = tf.io.read_file(input_file)
img = tf.image... |
# MIT License
#
# Copyright (c) 2019 <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, including without limitation the rights
# to use, copy, modify, merge,... |
import chronoptics.tof as tof
import cv2
import typing
import logging
import numpy as np
import time
import click
from timeit import default_timer as timer
from machine_vision_acquisition_python.viewer.cli import (
CameraHelper,
resize_with_aspect_ratio,
DISPLAY_SIZE_WIDTH,
)
log = logging.getLogger(__name... |
#! /usr/bin/python3
import sys
import os
import time
from typing import Dict, Iterable, List, Tuple
import re
from itertools import combinations
Floor = List[int]
Floors = List[Floor]
Elevator = Tuple[int, int]
Move = Tuple[int, int, Elevator]
State = Tuple[int, Floors]
EMPTY_SLOT = 0
radioisotopes: Dict[str, int] =... |
import socket
import time
from . import *
ADDR = ('localhost', 7642)
USB_RET_STALL = 0xfffffffd
TcpUsbHeader = Struct('TcpUsbHeader', [
('flags', Struct.INT8),
('ep', Struct.INT8),
('', 2),
('length', Struct.INT32),
])
UsbSetupPacket = Struct('UsbSetupPacket', [
('requestType', Struct.INT8),
('request', Stru... |
# -*- coding: utf-8 -*-
"""
file: module_evaluators_test.py
Unit tests for the interact profiler evaluators for a selection of
ligand test cases
"""
import os
from interact.md_system import System
from interact.interactions.hydrofobic import eval_hydrophobic_interactions, eval_pistacking
from interact.interactions.... |
"""Classes and methods used across the project"""
import json
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
import time
import fma_utils
"""Generic Utils"""
class ProgressBar:
"""Terminal progress bar
Arguments:
total: Relative size corresponding to completed task
... |
##############################################################################
#
# Copyright (c) 2001, 2002, 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution... |
# Copyright 2017 <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, softwa... |
import argparse
from mppca.mixture_ppca import MPPCA
from code.pytorch.LAMPO.core.imitation_learning import PPCAImitation, RunModel
from code.pytorch.LAMPO.core.task_interface import TaskInterface
from code.pytorch.LAMPO.core.plot import LampoMonitor
from code.pytorch.LAMPO.core.lampo import Lampo
import numpy as np
f... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class GetAcc... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2021 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from docutils import nodes
from os import path
from sphinx.util.math import wrap_displaymath
from sphinxcontrib.confluencebuilder.logger import ConfluenceLogger
from sphinxcontri... |
import json
import csv
import os
import sys
import random
from preproccess import tokenize
def writeJson(obj, file_path):
with open(file_path, 'w') as f:
json.dump(obj, f, indent=4)
def load_acronym_data():
return [
["sth", "something"],
["stfu", "shut the fuck up"],
["smh",... |
from datasets import load_dataset
from transformers import PretrainedConfig, default_data_collator
from torchdistill.common.constant import def_logger
from torchdistill.datasets.collator import register_collate_func
logger = def_logger.getChild(__name__)
GLUE_TASK2KEYS = {
'ax': ('premise', 'hypothesis'),
'c... |
import argparse
import time
from os import makedirs
from os.path import basename, join, exists
from shutil import copyfile
import torch
import torch.backends.cudnn as cudnn
from torch import nn
from torch.utils.data import DataLoader
import train.train_gru as train_gru
from config.config import Config, TRAIN_RESOLUTI... |
## Reference: Fast quantum search algorithms in protein sequence comparison: Quantum bioinformatics - <NAME>
## arXiv:
## \date: 23-01-2018 - 25-01-2018
## \repo: https://gitlab.com/prince-ph0en1x/QuInE
## \proj: Quantum-accelerated Genome-sequencing
'''
* Solution probability independent of p
* Steps
Init with w
D... |
"""
calculate the autocorrelation of a *sorted* bed file with a set
of *distance* lags.
"""
from __future__ import print_function
import argparse
from array import array
import sys
import numpy as np
import scipy.stats as ss
try:
from itertools import groupby, izip, chain
except ImportError:
from itertool... |
#!/usr/bin/env python3
# Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source Licens... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from fabric.api import local, run, put, settings, abort, env, cd, prefix
from contextlib import contextmanager
import os
import config
#from settings import DB_DIR, DB_FILE
RELEASE_PATH = './../'
ZIP_NAME = 'openvpn-admin-ui'
EXCLUDE_LIST = ['.i... |
# -*- coding: utf-8 -*-
# Copyright 2018 ProjectQ-Framework (www.projectq.ch)
#
# 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
#
# ... |
class RmQWithSparseTable:
"""
RmQ特化型クラス sparse_tableを用いている 空間計算量は大きいことに注意
計算量 構築O(NlogN) クエリO(1)
https://tookunn.hatenablog.com/entry/2016/07/13/211148 <--基本的にはこの実装
https://ikatakos.com/pot/programming_algorithm/data_structure/sparse_table
https://www.topcoder.com/thrive/articles/Range%20Minimum... |
import sqlite3
import time
from datetime import datetime
from typing import Any, Dict, Optional, Set
import hydra
import numpy as np
import pandas as pd
import schedule
from tqdm import tqdm
from hydra.utils import call
from omegaconf import DictConfig
from strava_datacollect.strava_auth import (MySession, get_token_... |
from __future__ import division
from pymer4.models import Lmer, Lm
from pymer4.utils import get_resource_path
import pandas as pd
import numpy as np
import os
from scipy.special import logit
def test_gaussian_lm():
df = pd.read_csv(os.path.join(get_resource_path(), 'sample_data.csv'))
model = Lm('DV ~ IV1 + ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import json
import argparse
import logging
import logging.config
logging.config.fileConfig('./utils/logging.conf')
import numpy as np
from tqdm import tqdm
from glob import glob
from collections import Counter
from tensorflow.keras.models import load_model
from... |
# Created by <NAME><<EMAIL> at 2/24/2021
import requests
from http import HTTPStatus
from datetime import datetime, timedelta
from functools import wraps
class AccessTokenError(Exception):
"""API Call cannot complete properly."""
class HMSSearchKit:
"""
How to find Client ID and Client Secret:
https... |
def b(G):
MIN=-98
G.add_edge("Alice","Bob",weight=54-MIN+MIN)
G.add_edge("Alice","Carol",weight=-81-MIN+MIN)
G.add_edge("Alice","David",weight=-42-MIN+MIN)
G.add_edge("Alice","Eric",weight=89-MIN+MIN)
G.add_edge("Alice","Frank",weight=-89-MIN+MIN)
G.add_edge("Alice","George",weight=97-MIN+MIN)
G.add_edge("Alice... |
import pytest
import os
import tempfile
import datetime as dt
from vital_sqi.data.signal_io import *
class TestECGReader(object):
def test_on_filename(self):
with pytest.raises(AssertionError) as exc_info:
file_type = 'sth'
ECG_reader('path_to_file', file_type=file_type)
... |
#!/usr/bin/env python
# encoding: utf-8
# <NAME>, 2006-2016 (ita)
# <NAME>, 2006 (rh)
# <NAME>, 2009
"""
gcc/llvm detection.
"""
from waflib.Tools import ccroot, ar
from waflib.Configure import conf
@conf
def find_gcc(conf):
"""
Find the program gcc, and if present, try to detect its version number
"""
cc = conf... |
import time
from examples.meeting_room.view_models import MeetingSession
from examples.meeting_room.view_models.meeting_session import \
MeetingSessionMutation
from ..views import meeting_session_ops
from onto import testing_utils
from onto.view import rest_api
from .. import view_models
# Import the fixtures used... |
#!/usr/bin/env python
"""
Modbus Message Parser
--------------------------------------------------------------------------
The following is an example of how to parse modbus messages
using the supplied framers for a number of protocols:
* tcp
* ascii
* rtu
* binary
"""
# ----------------------------------------------... |
import numpy as np
import re
import torch
from torch.autograd import Variable
# from torch.utils.data import Dataset, DataLoader
def create_variable(tensor):
# Do cuda() before wrapping with variable
if torch.cuda.is_available():
return Variable(tensor.cuda())
else:
return Variable(tensor)
... |
# @author <NAME>
# This code is licensed under the MIT license (see LICENSE.txt for details).
"""
Client implementations to communicate with various APIs.
"""
from collections import OrderedDict
import logging
import requests
import sys
from paperfetcher import GlobalConfig
from paperfetcher.exceptions import QueryErr... |
from django.db import models
from django.db.utils import DataError
def lower_value_using_mapping(my_cls, element_dict, pivot):
return element_dict[my_cls.mapping[pivot]].lower()
def check_value_using_mapping(my_cls, element_dict, pivot, value):
return element_dict[my_cls.mapping[pivot]].lower() == value.low... |
import numpy as np
from scipy import stats
import statsmodels.api as sm
import pandas as pd
import numpy.linalg as npl
import matplotlib.pyplot as plt
import numpy.random as npr
import time
from tqdm import tqdm
from scipy.stats import norm
import scipy.optimize as opt
def fnDataImport(bDropNA=True):
"""Short sum... |
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Imu
from imu_interface.MPU6050 import MPU6050
# apagar = 0
class ImuPub(Node):
i2c_bus = 1
# device_address = 0x68
# # The offsets are different for each device and should be changed
# # accordingly using a ca... |
import numpy as np
import scipy.linalg
# from numba import jit
# import pymc3 as pm
class BayesianRegression(object):
def __init__(self, X, y, y_err, prior_sd=500, informative_priors=True):
"""Class to handle the bayesian linear regression for y ~ beta * X.
Assumes X does not have an intercept te... |
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import ast
import sys
import logging
from utils.spreadsheet_snippets import SpreadsheetSnippets
from ... |
from datetime import datetime, timedelta
from pathlib import Path
from nemspy.model import ADCIRCEntry, AtmosphericMeshEntry, WaveWatch3MeshEntry
import pytest
from coupledmodeldriver import Platform
from coupledmodeldriver.configure import (
ATMESHForcingJSON,
ModelDriverJSON,
NEMSJSON,
SlurmJSON,
... |
# -*- coding: utf-8 -*-
"""Scan service.
This module implements uploading a scan file to XNAT and adding a scan to the database.
Todo: Maybe the public method should be called add, and that should kick off an upload procedure, rather than the
other way around.
Todo: do we want to infer file type from extension? Or ... |
import tensorflow as tf
def get_width_upright(bboxes):
with tf.name_scope('BoundingBoxTransform/get_width_upright'):
bboxes = tf.cast(bboxes, tf.float32)
x1, y1, x2, y2 = tf.split(bboxes, 4, axis=1)
width = x2 - x1 + 1.
height = y2 - y1 + 1.
# Calculate up right point of b... |
from django.http import HttpResponseRedirect, HttpResponse
from pffl.models import CredentialsModel
# GOOGLE AUTHENTICATION
import os
import httplib2
from apiclient import discovery
from oauth2client import client
from django.conf import settings
from oauth2client.contrib import xsrfutil
from oauth2client.contrib.djan... |
# SPDX-License-Identifier: MIT
import struct
from dataclasses import dataclass
from enum import IntEnum
from ..asc.base import *
from ...utils import *
## DCP main endpoint
class DCPMessage(Register64):
TYPE = 3, 0
class DCPEp_SetShmem(DCPMessage):
DVA = 63, 16
FLAG = 7, 4, Constan... |
#######################################################
# CURA (Ultimaker Cura) profile file compare tool
#
# Created by: <NAME>, 2020
# <EMAIL>
#
# Part of Cura Profile Compare project
#
# CuraData contains dictionary with 3 entries: general, metadata and values
# Each entry is dictionary too
#
# Free to u... |
from mip import Model, xsum, maximize, BINARY, CONTINUOUS
from collections import defaultdict
from copy import copy
class Bid:
def __init__(self, v, q, xor_group=None, winning=None, label=None, divisible=False):
self.v = v
self.q = q
self.xor_group = xor_group
self.winning = winnin... |
from aqt import mw
from aqt.utils import showInfo
from aqt.qt import *
class jocrWindow(QWidget):
def __init__(self, numChars):
super(jocrWindow, self).__init__()
self.setGeometry(300,300,400,400) #x,y on screen, width and height
self.setWindowTitle("jocr")
self.canvasList = [MyCanvasPainter() for x in range... |
#!/usr/bin/env python3
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
"""
This script imports an IDL dataset cvpr17 to the kapture format.
A Dataset for Benchmarking Image-based Localization
http://openaccess.thecvf.com/content_cvpr_2017/html/Sun_A_Dataset_for_CVPR_2017_paper.html
<NAME... |
# Copyright (c) 2020-2021, NVIDIA 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 agre... |
# -*- coding: utf-8 -*-
import multiprocessing as mp
import os
import tarfile
from tempfile import mkstemp
from typing import List, Optional, Sequence, Tuple
from xml.dom.minidom import getDOMImplementation
import cx_Oracle
from interpro7dw import logger
from interpro7dw.ebi.interpro import production as ippro
from ... |
"""Using cosine similarity with sentence embeddings from Universal Sentence Encoder."""
import os
import logging
from functools import partial
from typing import List
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from langdetect import detect
from summa.pagerank_weighted import pagerank_weigh... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import torch
import torch.nn as nn
import numpy as np
# from models.custom_functions.sparse_matrix import SparseTensor
from models.custom_functions.custom_fc import Line... |
from typing import Optional
import gym
from gym import spaces, logger
import random
from snake_utils import *
from snake_game_session import Snake, Apple, GameSession
from snake_core import Env
class GameEngine(Env):
"""
Description:
Snake...
Source:
...
Observati... |
import tensorflow as tf
import alphacheckers.config.config as config
import numpy as np
import alphacheckers.game.game as game
class Res_CNN():
def __init__(self, reg_const=config.REG_CONST, learning_rate=config.LEARNING_RATE, input_dim=(1,8,8,4), hidden_layers=[5]):
self.reg_const = reg_const
sel... |
#!/usr/bin/env python
# This file is part of dxdiff.
#
# dxdiff 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 3 of the License, or
# (at your option) any later version.
#
# ... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# --------------------------------------------------------------------------
import sys
from collections import defaultdict
from typing import Callable, Dict, List
from .. import util... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy
import torch
from rdkit.Chem.rdMolDescriptors import GetHashedMorganFingerprint
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit.Chem import DataStructs
from rdkit import Chem
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
... |
import logging
from collections import defaultdict
from datetime import datetime, date
from schedule import every
from sqlalchemy import func
from dispatch.config import (
DISPATCH_HELP_EMAIL,
)
from dispatch.conversation.enums import ConversationButtonActions
from dispatch.database.core import SessionLocal, res... |
from typing import Tuple, Optional
import numpy as np
def box_iou(
box_true: Tuple[float, float, float, float],
box_detection: Tuple[float, float, float, float]
) -> Optional[float]:
"""
Compute Intersection over Union of two bounding boxes - `box_true` and `box_detection`. Both boxes are expected to... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
determine_ext,
)
import re
class AddatimesIE(InfoExtractor):
_VALID_URL = r'https?://www\.addatimes\.com/show/(?P<slug>[^/]+)/(?P<id>[^/]+)'
_TESTS = [{
'url': 'http... |
import argparse
import csv
import glob
import logging
import os
import shutil
import requests
import sys
import time
import timeit
import pandas
from pandas.errors import EmptyDataError
from blackduck.HubRestApi import HubInstance
parser = argparse.ArgumentParser("A program that pulls license terms for each of the l... |
"""
Copyright (c) 2020 Keitaro 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwar... |
# -*- coding: utf-8 -*-
import torch
from itertools import accumulate
from onmt.constants import SubwordMarker
def make_batch_align_matrix(index_tensor, size=None, normalize=False):
"""
Convert a sparse index_tensor into a batch of alignment matrix,
with row normalize to the sum of 1 if set normalize.
... |
"""
Miscellaneous, generic functions that do not fit elsewhere.
This module includes the following functions (see docstrings for more
information):
terminate: to be called before exiting.
string_file: get the contents of a file (or string pointing to a file) as
a string.
file_lines: get a list of a file's ... |
# SPDX-FileCopyrightText: 2020 2020
#
# SPDX-License-Identifier: Apache-2.0
from future import standard_library
standard_library.install_aliases()
import json
import traceback
from urllib.parse import urlparse
from solnlib.splunkenv import get_splunkd_uri
from solnlib.splunk_rest_client import SplunkRestClient
from s... |
import sys
import glob
import os
import glob
import numpy as np
import cv2
from PIL import Image
import pytesseract
import re
def number_plate_detection(img):
def clean2_plate(plate):
gray_img = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray_img, 110, 25... |
import torch
from LSIM.distance_model import *
from LSIM.base_models import *
from LSIM.loss import *
import time
class Trainer(object):
def __init__(self, model, trainLoader, optimizer, criterion, printEvery, showProgressPrint=False):
self.model = model
self.trainLoader = trainLoader
self... |
import matplotlib.pyplot as plt
import numpy as np
def show_slice(
image, orientation, slice_nr, timepoint = None, color_map = None
):
"""
Shows a preferred slice from the 3D/4D nifti image, for a specific timepoint if applicable
Indexing: [Medio-lateral, Antero-posterior, Cranio-caudal, Time]
... |
__copyright__ = "Copyright (C) 2019 <NAME>"
__license__ = """
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, mer... |
"""
Tables Extension for Python-Markdown
====================================
Added parsing of tables to Python-Markdown.
See <https://Python-Markdown.github.io/extensions/tables>
for documentation.
Original code Copyright 2009 [<NAME>](http://achinghead.com)
All changes Copyright 2008-2014 The Python Markdown Proj... |
"""Sensor for checking the air quality around Norway."""
from datetime import timedelta
import logging
from niluclient import (
CO,
CO2,
NO,
NO2,
NOX,
OZONE,
PM1,
PM10,
PM25,
POLLUTION_INDEX,
SO2,
create_location_client,
create_station_client,
lookup_stations_in_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
from torch import nn
from combclassifier import CombinatorialClassifier
import torch.nn.functional as F
import configs.config as cf
class MLP(nn.Module):
def __init__(self, dim_in, dim_hidden, dim_out):
super(MLP, self).__init__()
... |
import os
import re
import json
import time
import requests
from bs4 import BeautifulSoup
USERNAME = os.environ["<EMAIL>"]
PASSWORD = os.environ["<PASSWORD>"]
TOKEN = ""
PROXIES = {
"http": "http://127.0.0.1:10808",
"https": "http://127.0.0.1:10808"
}
def login(username: str, password: str) -> (str, requests... |
import pytest
from unittest.mock import patch
from click.exceptions import MissingParameter
from rfidsecuritysvc.cli.guest import get, create, delete, update
from rfidsecuritysvc.exception import DuplicateGuestError as DuplicateError
from rfidsecuritysvc.exception import GuestNotFoundError as NotFoundError
from rfids... |
# 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... |
from multiprocessing import shared_memory
from multiprocessing.managers import SharedMemoryManager
from concurrent import futures
from itertools import product, repeat
import numpy as np
from scipy.optimize import optimize
from scipy.special import erfinv
from scipy.stats import mvn
__all__ = ["validate_contingency_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Room, User
from .serializers import RoomSerializer, UserSerializer, CreateRoo... |
# Copyright 2013 IBM Corp.
#
# 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... |
""" Original Author: <NAME> """
import numpy as np
import ctypes as ct
import cv2
import sys
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
showsz=800
mousex,mousey=0.5,0.5
zoom=1.0
changed=True
def onmouse(*args):
global mousex,mousey,changed
y=args[1]
x=args[2]
mousex=x... |
#! /usr/bin/env python
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) 2013-2015, Michigan State University.
# Copyright (C) 2015-2016, The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitte... |
# -*- coding: utf-8 -*-
# @Time : 2020/1/27 0027 15:44
# @Author : Erichym
# @Email : <EMAIL>
# @File : heap.py
# @Software: PyCharm
"""
implement max-heap and min-heap with their related operators
并不是排序堆
"""
class Array(object):
"""
achive an Array by Python list
"""
def __init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.