text stringlengths 3.07k 22.1k |
|---|
"""
@author : <NAME>
@date : 1-10-2021
Ensemble Learning is an often overshadowed and underestimated field of machine learning. Here we provide 2 algorithms
central to the game - random forests and ensemble/voting classifier. Random Forests are very especially fast
with parallel processing to fit multiple decision tre... |
import torch
import torch.nn as nn
from torchvision import models
class Conv2D_BN_activa(nn.Module):
def __init__(
self, in_channels, out_channels, kernel_size, stride, padding=0,
dilation=1, if_bn=True, activation='relu', bias=None, initializer=None, transpose=False
):
super(C... |
'''
SpeakDiar.py
21 audio recordings of academic conferences making up the NIST speaker
diarization dataset, created to asses the ability of different models to
segment speech data into unique speakers.
The 21 recordings are meant to be trained on independently.
Thus, get_data() takes a meetingNum parameter (default ... |
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import BaseHTTPServer
import cgi
import mimetypes
import os
import os.path
import posixpath
import SimpleHTTPServer
import SocketServer
import threading
... |
import cv2
import numpy as np
from PIL import Image
from PIL import ImageDraw
from subprocess import Popen, PIPE
import pycocotools.mask as coco_mask_util
def draw_bboxes(image, bboxes, labels=None, output_file=None, fill='red'):
"""
Draw bounding boxes on image.
Return image with drawings as BGR ndarray.... |
#!/usr/bin/env python3
# Copyright 2019 <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 agree... |
import io
import time
from functools import lru_cache
from urllib.error import HTTPError
import numpy as np
import pandas as pd
import requests
import sidekick as sk
import mundi
from mundi import transforms
from ..cache import ttl_cache
from ..logging import log
from ..utils import today
HOURS = 3600
TIMEOUT = 6 * ... |
# Shoot!
# by KidsCanCode 2014
# A generic space shooter - prototype (no art)
# For educational purposes only
import pygame
import sys
import random
# define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BGCOLOR = BLACK
class Meteor(pygame.sprite.Sprit... |
"""Git Utility functions."""
from __future__ import absolute_import
from __future__ import print_function
import itertools
import os
import re
import subprocess
from typing import Any, Callable, List, Tuple
from buildscripts import moduleconfig
from buildscripts.resmokelib.utils import globstar
# Path to the modules... |
import logging
from typing import Optional, Dict, List
import pysolr
import serpy
from manifest_server.helpers.fields import StaticField
from manifest_server.helpers.identifiers import get_identifier, IIIF_V3_CONTEXT
from manifest_server.helpers.metadata import v3_metadata_block, get_links
from manifest_server.helper... |
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
#!/usr/bin/env python3
"""
migrate_signoffs.py
Copies nova-labs signoffs from spaceman to wild apricot
adapted from spaceman2apricot.py by https://github.com/azagh
"""
import argparse
import datetime
import pandas as pd
import numpy as np
import os
import sys
import traceback
import urllib.parse
import signoffs
fro... |
import numpy as np
import cv2
import collections
import numbers
import random
import math
import copy
from up.data.datasets.transforms import Augmentation
from up.utils.general.registry_factory import AUGMENTATION_REGISTRY
@AUGMENTATION_REGISTRY.register('color_jitter_mmseg')
class RandomColorJitterMMSeg(Augmentatio... |
import json
def calc_liquidity_bonus_multiplier(
current_time, start_time, close_time):
""" Returns multiplier that applied to reduce bets """
return (current_time - start_time) / (close_time - start_time)
def calc_bet_return(top, bottom, amount, fee=0):
""" Calculates the amount that would be ... |
import torch
import pdb
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pdb
class LinearNorm(torch.nn.Module):
def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'):
super(LinearNorm, self).__init__()
self.linear_layer = torch.nn.Linear(in_dim, out_dim... |
"""Permission storage model."""
import logging
from enum import IntEnum
from functools import reduce
from typing import List, Optional, Union
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, User
from django.db import models, transaction
log... |
import ctypes
import functools
from .exceptions import Aborted, NeedHelp, NeedExtra
from .native import FUNCTIONS
Any = object()
def native_bridge(name: str, bases: tuple, dct: dict):
dct2 = {}
while dct:
k, v = dct.popitem()
if k.startswith('_') or (not isinstance(v, type) and v is not Any)... |
from abc import ABC
from dataclasses import asdict, dataclass
from typing import Any, Dict, List, Optional, Sequence, Union
import numpy as np
import torch
from lhotse.features.base import FeatureExtractor, register_extractor
from lhotse.utils import EPSILON, Seconds, is_module_available
@dataclass
class KaldifeatF... |
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Callable, Dict, Tuple
import numpy as np
from dppy.finite_dpps import FiniteDPP
from scipydirect import minimize
from .acquisition import (
AcquisitionFunction,
OneShotBatchAcquisitionFunction,
SequentialBatchAcq... |
from typing import Tuple, List
import matplotlib.pyplot as plt
import tensorflow as tf
from histomics_detect.boxes.transforms import filter_edge_boxes
from histomics_detect.anchors.create import create_anchors
from histomics_detect.metrics import greedy_iou_mapping
from histomics_detect.metrics.iou import iou
from hi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 1.6
import argparse
import json
import os
import re
import sys
import yaml
import colorama
from queries import custom_search
from utilities import escape_ldap
from ldap_connector import LDAP3Connector
from ldap_connector import ImpacketLDAPConn... |
import os.path, sys
from ctypes import *
from modules.windows_thumbnailcache.lib.olefile import olefile
from modules.windows_thumbnailcache.lib.yjSysUtils import *
#from lib.yjSQLite3 import TSQLite3
import base64, hashlib
def exit(exit_code, msg=None):
if debug_mode: exit_code = 0
if msg: print(msg)
sys.... |
####
#
# The MIT License (MIT)
#
# Copyright 2021, 2022 <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 without limitation the rights
# to us... |
import sys
import time
import argparse
import os
import warnings
import numpy as np
import torch
import torch.nn as nn
from collections import defaultdict
import pickle as pk
from torch.nn import Parameter
from layers import DNANodeRepModule, ConvNodeRepModule
from metrics import compute_mae, compute_mape, compute_ss... |
from rest_framework import viewsets, status, serializers, mixins, filters
from rest_framework.exceptions import NotFound
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import PostIt, Board, WorkIn, VoteIn
from django.core.exceptions import ObjectDoesNotExist
from ... |
"""
This file includes a set of helpers that make treating Swift as a filesystem a
bit easier.
See COPYING for license information.
"""
import datetime
import stat
import os
import urlparse
import time
from twisted.internet import defer, reactor, task
from twisted.web.iweb import IBodyProducer, UNKNOWN_LENGTH
from tw... |
from app import app
from flask import redirect, flash, request
from werkzeug import secure_filename
from .alchemy import db, User, tablename
import os
from os import listdir, mkdir
from os.path import isfile, join, isdir
import time
import uuid
import re
import shutil
main_path = app.config['USER_STORAGE_PATH']
# ch... |
#!/usr/bin/python3
import re, os, cgi
directory = 'statsyears'
fileNameRe = re.compile(r'^statscumulative.(\d+)$')
lineRe = re.compile(r'^"(H|V)",(\d+),(\d),(\d),(-?\d+),(\d+),(\d+)$')
outputFileName = 'leverage'
class Situation:
def initReal(self, homeOrVisitor, inning, outs, runnersOneBased, runDiff, totalCount... |
from boptx.evaluator import BaseEvaluator, DefaultEvaluation
from boptx.algorithms.opdyts import OpdytsProblem, OpdytsEvaluation
from boptx.problem import Problem
import os, shutil
import subprocess as sp
import pandas as pd
import numpy as np
import glob
import json
import logging
logger = logging.getLogger(__name__... |
'''
Created on 2021-07-30
@author: wf
'''
from corpus.event import EventStorage
from corpus.eventcorpus import EventCorpus, EventDataSource
from corpus.datasources.acm import ACM
from corpus.datasources.confref import Confref
from corpus.datasources.crossref import Crossref
from corpus.datasources.dblp import Dblp
fro... |
#!/usr/bin/env python2
from src.lib import *
from src.sampler import *
from src.agents import *
from src.emulator import *
from src.simulators import *
from src.visualizer import *
def get_agent(model_type, env, learning_rate=0.01, fld_load=True, input_size=32, batch_size=8, discount_factor=0.99, buffer_size=2000, b... |
"""Command line tools for optimisation."""
import datetime
import json
import logging
from pathlib import Path
from typing import List
import click
import matplotlib.pyplot as plt
import numpy as np
from hoqunm.data_tools.base import (EXAMPLE_FILEPATH_OPTIMISATION_COMPUTATION,
EXA... |
import sys
from copy import deepcopy
ALPHABET = ['A', 'C', 'G', 'T']
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
def process_input(adj_list):
for edge in adj_list:
if RepresentsInt(edge[0]) and RepresentsInt(edge[1]):
break
... |
"""Point metrics for forecasting a single point per time step."""
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import scipy.stats
import torch
import torch.nn.functional as F
from torch.nn.utils import rnn
from pytorch_forecasting.metrics.base_metrics import MultiHorizonMetric
from pytorch_for... |
import cv2
import os
import numpy as np
import traceback
from time import *
import winsound
import pyttsx3
# s1,s2:就是识别人的名字
subjects = ["stranger", "hfp", "lc"]
def menu():
"""菜单"""
print("*"*10 + "人脸识别系统" + "*"*10)
print("*"*10 + "菜单" + "*"*10)
print("*"*5 + "1、进行检测" + "*"*8)
... |
from . import util, config
from datetime import date
import sys
import re
import requests
from pathlib import Path
import json
import boto3
import gzip
DefaultVersion = 'v2'
class StatIds:
Combined = 'combined'
MedianTripTimes = 'median-trip-times'
AllStatIds = [
StatIds.Combined,
StatIds.MedianTripT... |
import wikiquotes
import os
from time import sleep
from sys import argv
from sys import exit
from getpass import getpass
from random import randint
from PIL import Image, ImageDraw, ImageFont, ImageStat
wd = os.getcwd() # Get the working directory
def getInstagramFile(username):
"""
This function hand... |
import random
import hashlib
import math
class Neuron:
def __init__(self, net, index, activ_func, alfa=1, is_input=False):
self.net = net
self.is_input = is_input
self.n = net.mass
self.x = [1] + [0] * self.n
self.b = [0] * (self.n + 1)
self.b_step = [0] * (self.n... |
from typing import Union, Tuple, List, Dict, Any
from easydict import EasyDict
import random
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from ding.utils import SequenceType, REWARD_MODEL_REGISTRY
from ding.model import FCEncoder, ConvEncoder
from .base_reward_model i... |
# Copyright (c) 2017-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. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
#
import sys
import torch
from tor... |
#!/usr/bin/env python3
import sys, os, re, math, copy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
# import the Python wrapper
from dubinswrapper import DubinsWrapper as dubins
################################################
# Scenarios
########################... |
"""
@author: <NAME> <<EMAIL>>
"""
import os
import argparse
from torch.utils.data import DataLoader
import torch.nn as nn
import torch
from src.voc_dataset import VOCDataset
from src.utils import custom_collate_fn, multiple_losses, update_lr, get_optimizer
from src.deeplab import Deeplab
from tensorboardX import Summar... |
import requests
from typing import List
from bs4 import BeautifulSoup
import http.cookiejar as cookielib
import numpy as np
import re
crawl_header = {"user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"}
# 根据工资获取中间段
def get_midfix(sala... |
import pdb
from collections import namedtuple
from pathlib import Path
import z3
import sage.all
import helpers.vcommon as CM
from helpers.miscs import Miscs
import data.prog
import settings
DBG = pdb.set_trace
mlog = CM.getLogger(__name__, settings.logger_level)
class SymbsVals(namedtuple("SymbsVals", ("ss", "v... |
"""
!git
clone
https: // bitbucket.org / jadslim / german - traffic - signs
!ls
german - traffic - sign
"""
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.optimizers import Adam
from keras.layers import Dense
from keras.layers import Flatten, Dropout
from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy import Column, String, Integer, ForeignKey, TIMESTAMP, func, and_, or_
from sqlalchemy.sql import text
from sqlalchemy.orm import sessionmaker, relationship, query, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import creat... |
from opentera.db.Base import db, BaseModel
from enum import Enum
import random
from datetime import datetime, timedelta
import uuid
class TeraSessionStatus(Enum):
STATUS_NOTSTARTED = 0
STATUS_INPROGRESS = 1
STATUS_COMPLETED = 2
STATUS_CANCELLED = 3
STATUS_TERMINATED = 4
class TeraSession(db.Mod... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# The MIT License
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... |
"""Magic 8-Ball
Simulates the classic Magic 8-Ball toy, with some ZeroBot twists...
"""
from __future__ import annotations
import random
import re
from collections import deque
from dataclasses import dataclass
from enum import Enum, unique
from string import Template
from typing import Optional, Union
from ZeroBot... |
import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
from torch.autograd import grad
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from tensorboardX import SummaryWriter... |
import random
import bintrees
import threading
from itertools import count
from collections import Counter
import tensorflow as tf
from joblib import Parallel, delayed
from lib.ops import get_available_gpus
from lib.trainer import SampleBasedTrainer
class MultiGPUTrainer:
def __init__(self, name, make_model,
... |
from django.core.exceptions import ValidationError
from django import forms
from form_helper import FormOrderMixin
from survey.models import (Answer, MultiChoiceAnswer, MultiSelectAnswer, DateAnswer, QuestionFlow,
Question, TextArgument, NumericalAnswer, TextAnswer, TemplateOption)
from surve... |
from micropython import const
from trezor import log, wire
from trezor.crypto import base58, hashlib
from trezor.crypto.curve import ed25519
from trezor.messages.CardanoSignedTx import CardanoSignedTx
from trezor.messages.CardanoTxRequest import CardanoTxRequest
from trezor.messages.MessageType import CardanoTxAck
fr... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
# functions of initializing layers
def init_layer(layer):
"""Initialize a Linear or Convolutional layer."""
nn.init.xavier_uniform_(layer.weight)
if hasattr(layer, 'bias'):
if layer.bias is not None:
... |
from typing import Dict, Type
import bpy
from bpy.app.handlers import persistent
from bpy.props import (BoolProperty, FloatProperty, IntProperty,
PointerProperty, StringProperty)
from bpy.types import Operator, PropertyGroup, UILayout, UIList
# Globals
XFBIN_LISTS = list()
XFBIN_CLIPBOARD: Dict... |
import pymc3 as pm
import matplotlib.pyplot as pl
from matplotlib import dates
import numpy as np
import pandas as pd
from . import ephem, MPLSTYLE, PACKAGEDIR
from .cobs import read_cobs
class CometModel():
def __init__(self, comet="2019 Y4", cobs_id=None, horizons_id=None,
start="2020-01-01",... |
import logging
import operator
import random
import requests
import requests.auth
import requests.exceptions
import six.moves.urllib.parse
import threading
import zeep
import zeep.exceptions
import zeep.xsd.elements
import zeep.xsd.elements.indicators
import zeit.content.author.interfaces
import zeit.vgwort.interfaces
... |
#!/bin/env python
# -*- coding: utf-8 -*-
##
# test_solvers.py: Checks correctness of azure.quantum.optimization module.
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
import pytest
from asyncmock import AsyncMock, patch, Mock
from azure.quantum.aio.optimization imp... |
# The functions defined here were copied based on the source code
# defined in xarray
import datetime
from typing import Any, Iterable
import numpy as np
import pandas as pd
try:
import cftime
except ImportError:
cftime = None
try:
import dask.array
dask_array_type = dask.array.Array
except Impor... |
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Test validation of keys generated by flocker-ca.
"""
from __future__ import print_function
from OpenSSL.SSL import Context, TLSv1_METHOD, Error as SSLError
from twisted.trial.unittest import TestCase
from twisted.internet.endpoints import (
SSL4Serve... |
#!/usr/bin/python
import datetime
import signal
import sys
import time
import RPi.GPIO as GPIO
from components import rebooter, rgb, pir, matrix, oled, continuousP1, joystick, writer, data
# Setup classes
###################################################################################################
debug = Fa... |
"""
yxf: Convert from XLSForm to YAML and back.
To convert an XLSForm to a YAML file: `python -m yxf form.xlsx`.
By default, the result will be called `form.yaml`, in other words, the same name
as the input file with the extension changed to `.yaml`. You can specify a
different output file name using the `--output ot... |
import numpy as np
import seaborn as sns
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import torchvision.models as models
from PIL import Image
import json
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.... |
# -*- coding: utf-8 -*-
"""
Built-in predicate checkers.
This is mostly took from repoze.what.precidates
This is module provides the predicate checkers that were present in the
original "identity" framework of TurboGears 1, plus others.
"""
from __future__ import unicode_literals
from tg import request
from tg._com... |
from soccerdepth.data.dataset_loader import get_set
import numpy as np
import utils.files as file_utils
from os.path import join
import argparse
from soccerdepth.models.hourglass import hg8
from soccerdepth.models.utils import weights_init
from soccerdepth.data.data_utils import image_logger_converter_visdom
import to... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for novice submodule.
:license: modified BSD
"""
import os, tempfile
import numpy as np
from image_novice import novice
from numpy.testing import TestCase, assert_equal, assert_raises, assert_allclose
def _array_2d_to_RGB(array):
return np.tile(array[:, :, n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Chromium OS Dependencies:
# shred --> sys-apps/coreutils
# mogrify --> media-gfx/imagemagick
#... |
'''
Process IMDb datasets and store them as parquet files
'''
import datetime
import os
import pyspark.sql.functions as F
import util
def fix_year(col):
'''
Fix the year column by getting rid of bad values
Params
- col: column name
'''
# Get today's date
now = datetime.datetime.now()
... |
import logging
import multiprocessing
import time
from radosgw_agent import worker
from radosgw_agent import client
from radosgw_agent.util import get_dev_logger
from radosgw_agent.exceptions import NotFound, HttpError
log = logging.getLogger(__name__)
dev_log = get_dev_logger(__name__)
# the replica log api only s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List, Tuple, Union
from hwt.code import If
from hwt.interfaces.utils import addClkRstn
from hwt.pyUtils.arrayQuery import iter_with_last
from hwt.serializer.mode import serializeParamsUniq
from hwt.synthesizer.interfaceLevel.unitImplHelpers import getS... |
import os
import time
import yaml
import pickle
import numpy as np
from random import shuffle
from sklearn.neighbors import KDTree
ALL_LAYERS = np.array([[8,2],
[8,4],
[8,6],
[8,8],
[13,2],
[13,4],
... |
#%%
import os
import pandas as pd
import numpy as np
import copy
from tqdm import tqdm
from plot import plot
from utils.evaluator import evaluate, set_thresholds
from utils.evaluator_seg import compute_anomaly_scores, compute_metrics
# Univariate
from utils.data_loader import load_kpi, load_IoT_fridge
# Multivariate
... |
import pygame
from pygame.locals import *
from enum import Enum
X = 0
Y = 1
groundPos = 450 # global temporary variable (useless once collision is implemented) ; might use this for a global death barrier (below screen)
def cap(maxVal, eq): # caps a value to prevent an equation from breaking said cap ; global ... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect 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... |
import json
import re
import base64
import os
import requests
import jwt
from collections import defaultdict
from flask import Flask, jsonify, abort, make_response, request, current_app, _request_ctx_stack
from flask.ext.cors import cross_origin
from functools import wraps
from datetime import timedelta
from functool... |
# This file is part of Pynguin.
#
# Pynguin is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pynguin is distributed in the ho... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
Sphinx Theme
~~~~~~~~~~~~
A sphinx theme with accessibility in mind.
:copyright: (c) 2021-present ooliver1
:license: MIT, see LICENSE for more details.
"""
# credit to tooty as I kinda took a decent chunk
from __future__ import annotations
__version__ = "0.0.0a"
__title__ = "tooty-theme"
__author__ = "<NAME> - ... |
import re
import numpy as np
from rdkit import Chem
from rdkit.Chem.rdchem import ChiralType
from EFGs import standize
pat = r'\d+(?:\.\d+)?%'
p2f = lambda x: float(x.strip('%'))/100
def mols_from_smiles_list(all_smiles):
'''Given a list of smiles strings, this function creates rdkit
molecules'''
mols =... |
# -*- 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... |
"""authentik e2e testing utilities"""
import json
import os
from functools import lru_cache, wraps
from os import environ, makedirs
from time import sleep, time
from typing import Any, Callable, Optional
from django.apps import apps
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.db... |
'''
Copyright (c) 2018 <NAME>/HiFiBerry
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, distribut... |
"""Training procedure for real NVP.
"""
import argparse
import torch, torchvision
import torch.distributions as distributions
import torch.optim as optim
import torchvision.utils as utils
import numpy as np
import realnvp, data_utils
class Hyperparameters():
def __init__(self, base_dim, res_blocks, bottleneck, ... |
from collections import OrderedDict
import torch
from torch import nn
import torch.nn.functional as F
from exp import ex
from utils import jsonl_to_json, mean
from data.batcher import make_feature_lm_batch_with_keywords, ConvertToken
from .modules import Attention, GRU
from .scn_rnn import SCNLSTM
from .transformer_... |
from HSTB.kluster.gui.backends._qt import QtGui, QtCore, QtWidgets, Signal
from HSTB.kluster.gui.common_widgets import SaveStateDialog
from HSTB.kluster import kluster_variables
class PatchTestDialog(SaveStateDialog):
patch_query = Signal(str) # submit new query to main for data
def __init__(self, parent=No... |
#!/usr/bin/env python
'''
pysomtsdatalogger.py
Python-based network/serial raw data consumer and logger via a
RabbitMQ AMQP producer/consumer model.
https://github.com/somts/pysomtsdatalogger
Package installation:
CentOS: requires EPEL and pip to work. Commands:
install base packages with: yum -y install... |
import hashlib
import os
import warnings
from dataclasses import dataclass, asdict, field
from pathlib import Path
import torch
import torchaudio
from fastai.core import ifnone
from fastai.data_block import get_files
from fastprogress.fastprogress import progress_bar
from torchaudio.transforms import Spectrogram, MelSc... |
#!/usr/bin/python
#
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
#!/usr/bin/env python3
import collections
from .symbols import SymbolScope
from .ast import ASTVisitor, ASTScopedVisitorMixin
from .mtypes import MethodType
from .opcodes import Opcodes
from . import asm
# Function activation block:
# arguments...
# retval
# retaddr
# locals
class StackSize(ASTScopedVisitorMixin, ... |
# Description: Sample script for reading excel file using Pandas and saving to a SQL database - SQLite, Postgres, SQL Server, MySQL
# Date: 05-01-2020
# Author: <NAME>
# Usage: $python3 19_excel_to_sql.py
# Requirements: pandas ($pip3 install pandas)
'''
Structure of sheet Number 1 in Excel file (although not used in ... |
"""A module for housing the Cursor class.
Exported Classes:
Cursor -- Class for representing a database cursor.
"""
from collections import deque
from .statement import Statement, PreparedStatement
from .exception import Error, NotSupportedError, ProgrammingError
class Cursor(object):
"""Class for represent... |
#!/usr/bin/env python
# coding=utf-8
"""
Copyright 2012 Load Impact
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... |
# split_file.py
# MIT license; Copyright (c) 2020 - 2021 <NAME>
import os
import datetime
import time
import cfg
# Checks if there is more than one file in the raw dir to be processed.
def new_file_in_dir(dir):
i = 0
for file in os.listdir(dir):
try:
int(file)
i += 1
... |
import pytest
import uuid
from eha_jsonpath import parse
from eha_jsonpath.ext_functions import BaseFn
src = {
'space': '1 2 3 4',
'pipe': '1|2|3|4',
'comma': '1,2,3,4',
'float': '1.04',
'bad_float': '1.04s',
'epoch1': '0',
'epoch2': 1_000_000_000,
'epoch3': 1_000_000_000_000_000,
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
Example implementation of MAML++ on miniImageNet.
"""
import learn2learn as l2l
import numpy as np
import random
import torch
from collections import namedtuple
... |
import time
class Preprocessed:
def __init__(self, c, db, profile, summoners):
"""
:type profile: str
:type db: darkarisulolstats.lolstats.database.Database
:type c: darkarisulolstats.arisu.console.Console
"""
db.preprocessed.add(profile, "matchlists", generate_matc... |
"""
This library contains the functions that allow stacktrain to produce
Windows batch files.
"""
# Force Python 2 to use float division even for ints
from __future__ import division
from __future__ import print_function
import logging
import io
import ntpath
import os
import re
from string import Template
from sh... |
"""The CranPort class that understands the CRAN package format."""
from pathlib import Path
from re import compile as re_compile
from tarfile import TarFile
from traceback import print_exc
from typing import Callable, Dict, Optional, Union, cast
from .uses import Cran
from ..core import Port, PortDepends, PortError, Po... |
from collections import OrderedDict
from lib import util
## Serializes all device atoms
def serialize(obj, state = None):
if state == None:
state = []
if isinstance(obj, Atom):
if obj in state:
return {
'object_ref': state.index(obj) + 1,
}
state.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.