text
stringlengths
3.07k
12.6k
"""Puddleworld from RLPy.""" import typing as t import gym import numpy as np from gym.utils import seeding class ContinuousPuddleWorld(gym.Env): ACTION_SCALE: float = 0.1 DEFAULT_PUDDLES: np.ndarray = np.array( [[[0.1, 0.75], [0.45, 0.75]], [[0.45, 0.4], [0.45, 0.8]]] ) REWARD_UNIT: float =...
# enumerations used in QuantLib code. from bgtools.utils.dates import parse_date from pybg.ql import qldate_from_pydate, pydate_from_qldate class TimeUnits(object): from pybg.quantlib.time.date import Days, Weeks, Months, Years class Compounding(object): Simple = 0 # 1+rt Compounded = 1 # (...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_str from ..utils import ( int_or_none, str_or_none, try_get, unified_timestamp, update_url_query, urljoin, ) # compat_range try: if callable(xrange): range = xrange...
import settings from ali1688scraperbrowser import ScraperBrowser from bs4 import BeautifulSoup import datetime from functools import reduce import re def get_attr_content(aa, bb): cc=[] for a in aa: for b in bb: ctemp=[] tmp0=a[0] + ',' + b[0] ctemp.append(tmp0) ...
import argparse import numpy as np import copy class LogisticRegressionClassifier(): def __init__(self): self.theta = {0:0.0} # bias self.X = [] self.Y = [] def fit(self,train_input): self.X, self.Y = self.parse_data(train_input) def train(self,num_epoch): self.the...
import social, facebook from django.conf import settings from _commons.helpers.countries import CountriesHelper from avatar.models import Binding as AvatarBinding from comment.helpers import PoolHelper from avatar.helpers import AvatarHelper from .models import * from .factories import * def get_username(backend, ...
import numpy as np from common.common import Algorithm, LEARNING_RATE_CONSTANT, DEFAULT_NUM_ITERS from lossfunctions.logistic_regression import ( LogisticRegression, LogisticRegressionSinglePoint) from lossfunctions.huber_svm import HuberSVM from scipy.optimize import minimize from scipy.sparse import csr_matrix, h...
# coding: utf-8 """ MIT License """ ''' Project: Wavelet DNN Authors: <NAME> Description: Image preprocessing scripts to visualize CT images, normalize the image, and conduct multiscale wavelet decomposition ''' # ---------------------------------------------------------------------------- # from PIL im...
# -*- coding: utf-8 -*- import pyglet from pyglet.window import key import paho.mqtt.client as mqtt from joystick import Joystick from slider import Slider from datetime import datetime, timedelta window = pyglet.window.Window() keys = key.KeyStateHandler() window.push_handlers(keys) # Aqui criamos o di...
"""Implementation of a mapplot for the climwip weighting scheme. <NAME> et al. section 2.4 https://iopscience.iop.org/article/10.1088/1748-9326/ab492f """ import logging import os from pathlib import Path import cartopy.crs as ccrs import matplotlib.pyplot as plt import numpy as np from cartopy.mpl.ticker import Lati...
""" Pythonic representation of an SBML model with some extensions. - moietys (functional groups within a molecule) - molecules (species) - reactions SimpleSBML extracts all information required from an SBML model to avoid saving the libsbml object (since these objects are fragile with python garbage collection). """ f...
# -*- coding: utf-8 -*- class BSTNode(object): def __init__(self, key, value, left=None, right=None): self.key, self.value, self.left, self.right = key, value, left, right class BST(object): def __init__(self, root=None): self.root = root @classmethod def build_from(cls, node_list):...
import asyncio from subprocess import call import os import dotenv import aiohttp import requests import youtube_dl as ytdl from apiclient.discovery import build __BASE_URL__ = "https://www.googleapis.com/youtube/v3" class BaseYoutubeAPI: """Base Youtube API Client. Handles users credentials API key. ""...
import logging import os import random # import sys from flask import Flask, render_template, request, url_for from fourlang.corenlp_wrapper import CoreNLPWrapper from fourlang.utils import draw_dep_graph, draw_text_graph, ensure_dir, get_cfg from fourlang.dependency_processor import Dependencies from fourlang.dep_to...
#!/usr/bin/env python # Copyright 2018 Datawire. 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 b...
import decimal import re from enum import Enum from typing import Optional, Union from boto3.dynamodb.conditions import Key from boto3.dynamodb.types import TypeSerializer, TypeDeserializer from botocore.exceptions import ClientError from typhoon.aws.boto3_helper import boto3_session from typhoon.aws.exceptions impor...
"""Command-line interface for Zellij.""" import math import pprint import click from zellij.color import random_color, parse_color from zellij.debug import debug_world, debug_click_options, should_debug from zellij.design import get_design from zellij.drawing import Drawing from zellij.path import combine_paths, dra...
from django.shortcuts import render from django.db import models from django.db.models import F, Q, Exists, Value, IntegerField, Sum from .models import Artista, UsuarioEtiquetaArtista, Usuario, UsuarioArtista, Etiqueta import csv import datetime as dt from recomendation.forms import * from collections import Counter i...
import random import string import logging import flask char = list(string.printable.strip()) secret = "" for i in range(16): secret += random.choice(char) app = flask.Flask(__name__) app.secret_key = secret PLAYER = random.choice(["😳", "😐", "😎", "🥶", "😏"]) FOOD = "🍎" WALL = "🟫" GROUND = "🟩" SCREEN_WID...
import numpy as np import torch from torch.autograd import Function import holoviews as hv hv.extension('bokeh') """ pytorch-grad-cam by JacobGil (https://github.com/jacobgil/pytorch-grad-cam) """ class FeatureExtractor(object): """ Class for extracting activations and registering gradients from targetted in...
# ================================================================= # # Authors: <NAME> <<EMAIL>> # # # 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 # r...
import json import time import requests from flask_socketio import SocketIO, emit from flask import Flask, render_template, url_for, copy_current_request_context from random import random from time import sleep from threading import Thread, Event import datetime from random import shuffle from lxml import html import y...
#!/usr/bin/env python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ---------------------------------------------...
import numpy as np import pytest from pandas import ( DataFrame, NaT, Series, Timedelta, Timestamp, ) import pandas._testing as tm def test_group_shift_with_null_key(): # This test is designed to replicate the segfault in issue #13813. n_rows = 1200 # Generate a moderately large data...
#!/usr/bin/env python3 # TODO: # - Apply bitmask on opcodes to zero out variant bits (e.g. relative and absolute addresses or nops) # - Hash resulting instruction bytes instead of mnemonics # - https://www.hex-rays.com/products/ida/tech/flirt/in_depth/#Variability import filterdiff import ratio import r2pipe...
"""Exercise 1: Basic Object-Oriented Programming - SuperDuperManager, which manages all the cars in the system - Car, a class which represents a single car in the system Your task is to design and implement the Car class, and then modify the SuperDuperManager methods so that they make proper use of the Car clas...
import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ from utils.filestorage.uploads import get_unique_upload_path from utils.filestorage.signals import delete_files_on_delete, \ delete_files_on_change from photos.utils import generate_thumbnail MONTH_CHOICES = ((mo...
#!/usr/bin/env python """ Copyright (c) 2015 <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, publi...
import enum import torch from utils import load_file, save_pkl, load_pkl from config import Config from logger import logger as logging import os from tqdm import trange, tqdm from torch.utils.data import TensorDataset config = Config() def dataset_format(file_path, separater=" "): label_map = {label: i for i, l...
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
import copy from collections import namedtuple import numpy as np import torch from torchvision import transforms from PIL import Image, ImageFilter, ImageEnhance # An augmentation object consists of its name, the transform functions of type # torchvision.transforms, and the resulting augmented dataset of type # torc...
import json import logging import os import platform import subprocess import threading from urllib.request import urlopen from urllib.error import HTTPError if platform.system() == "Windows": try: from colorama import init init(convert=True) except ImportError: try: import ...
# -*- coding: utf8 -*- # 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 orjson from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.images import ImageFile from django.db.models import TextField, ForeignKey, FileField, ImageField, Field from django.db.models.fields.files import FileDescriptor, FieldFile from django.db.models.query_utils import Deferre...
""" Added build utility module for managing the rig_builder ui functionality. """ # import standard modules import sys import posixpath import os py_version = None if sys.version_info.major == 2: py_version = 2 import imp elif sys.version_info.major == 3: py_version = 3 import importlib # import loca...
import os import re import json import requests import urllib3 from requests_http_signature import HTTPSignatureAuth import logging import datetime from uuid import uuid4 from functools import lru_cache import jmespath from jmespath.exceptions import JMESPathError from dcplib.aws.sqs import SQSMessenger, get_queue_url...
""" This module contains general purpose URL functions not found in the standard library. """ import os import re import urlparse import urllib import posixpath import cgi from scrapy.utils.python import unicode_to_str def url_is_from_any_domain(url, domains): """Return True if the url belongs to any of the give...
"""Support for standalone client challenge solvers. """ import argparse import collections import functools import logging import os import sys from six.moves import BaseHTTPServer # pylint: disable=import-error from six.moves import http_client # pylint: disable=import-error from six.moves import socketserver # py...
""" WDL values instantiated at runtime Each value is represented by an instance of a Python class inheriting from ``WDL.Value.Base``. .. inheritance-diagram:: WDL.Value :top-classes: WDL.Value.Base """ from abc import ABC from typing import Any, List, Optional, Tuple, Dict, Iterable import json import WDL.Type as ...
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import os import glob from imageio import imread, imsave import cv2 import dlib import time def preprocess(img): return (img / 255. - 0.5) * 2 def deprocess(img): return (img + 1) / 2 def showImg(img,name="img",delay=0): cv2.imshow(name,...
# -*- coding: utf-8 -*- """ Created on Sat Mar 23 12:02:01 2019 @author: s168003 """ import os import datetime from tensorboard.backend.event_processing.event_accumulator import EventAccumulator import numpy as np import matplotlib.pyplot as plt from keras.preprocessing.image import ImageDataGenerator...
#!/usr/bin/env python3 """Local Validatoin""" import sys import numpy as np import pandas as pd from sklearn.metrics import log_loss EXAM_COLS = [ 'negative_exam_for_pe', 'indeterminate', 'chronic_pe', 'acute_and_chronic_pe', 'central_pe', 'leftsided_pe', 'rightsided_pe', 'rv_lv_ratio_...
from typing import Literal import akinator import discord from akinator.async_aki import Akinator from redbot.core import commands from redbot.core.bot import Red from redbot.core.config import Config from redbot.vendored.discord.ext import menus RequestType = Literal["discord_deleted_user", "owner", "user", "user_st...
import math from typing import Optional import torch import torch.nn as nn from torch.utils.checkpoint import checkpoint from lib.modules.rotary import RotaryEmbeddings class LeanSelfAttention(nn.Module): def __init__( self, hidden_size: int, num_attention_heads: int, attention_c...
#!/usr/bin/env python # -*- coding: Latin-1 -*- """ @file FCDvsCompleteRoute.py @author <NAME> @author <NAME> @author <NAME> @date 2008-04-08 @version $Id$ Compares the FCD-route of an taxi with the generated route which is used in the simulation. The output data can be visualized with the script My_mpl_dump_...
from dataclasses import asdict, dataclass from typing import Any, Dict, List, Union, Optional, Sequence import numpy as np import warnings from lhotse.features.base import FeatureExtractor, register_extractor from lhotse.utils import is_module_available, Seconds, compute_num_frames @dataclass class OpenSmileConfig: ...
import numpy as np import time import sys if sys.version_info.major == 2: import Tkinter as tk else: import tkinter as tk cell = 60 w_height = 6 w_width = 6 class MazeGrid(tk.Tk, object): def __init__(self): super(MazeGrid, self).__init__() self.action_space = ['up', 'down', 'left', 'rig...
from twisted.trial import unittest from twisted.internet import task, defer from collections import OrderedDict import nanobot import app import string import twisted.internet.base twisted.internet.base.DelayedCall.debug = True class CacheTests(unittest.TestCase): def setUp(self): self.clock = task.Clock()...
""" LABORATORIO 2 - REDES <NAME> 181202 <NAME> 18398 FUENTES DE CONSULTA: https://www.geeksforgeeks.org/hamming-code-implementation-in-python/ https://github.com/danielmuthama/Hamming-Code/blob/master/hammingcode.py """ # chequea el numero de paridad de bits en la generacion del hamming code # devuelve el numero de bi...
from advent_of_code.utils.Elf import Elf from advent_of_code.utils.Gnome import Gnome def parse_input(raw_input, elf_ap=3): raw_input = raw_input.strip() dungeon = raw_input.split("\n") creatures = list() num_e = 0 num_g = 0 for idx, row in enumerate(dungeon): i = row.find("E") ...
# Copyright 2008-2015 Nokia Solutions and Networks # # 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...
import lz4.block import sys from multiprocessing.pool import ThreadPool import os import pytest if sys.version_info <= (3, 2): import struct def get_stored_size(buff): if sys.version_info > (2, 7): if isinstance(buff, memoryview): b = buff.tobytes() else: b = bytes(buff...
__author__ = "<NAME>" __license__ = "MIT" ''' Utility functions for the homework ''' import pandas as pd from sklearn.preprocessing import MultiLabelBinarizer from sklearn.metrics import confusion_matrix import seaborn as sns import numpy as np import matplotlib.pyplot as plt def parse_data(feature_file, label_file...
#!/usr/bin/env python # (c)quasardb SAS. All rights reserved. # qdb is a trademark of quasardb SAS # pylint: disable=C0103,C0111,C0326,W0201 import os import re import sys import platform import subprocess import glob from setuptools.command.build_ext import build_ext from setuptools import setup, Extension from se...
import numpy as np from pymoo.performance_indicator.gd import GD from pymoo.performance_indicator.igd import IGD from pymoo.performance_indicator.hv import Hypervolume from pymoo.util.termination.f_tol import MultiObjectiveSpaceToleranceTermination def pareto_front_if_possible(problem): try: return probl...
import sys sys.path.append('.') import argparse import cv2 import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F from lietorch import SE3 import raft3d.projective_ops as pops from data_readers import frame_utils from utils import show_image, normalize_image DEPTH_SCALE = 0...
# $Id$ # # Copyright (C) 2004 Rational Discovery LLC # All Rights Reserved # from rdkit import RDConfig import sys, os.path from rdkit.VLib.Supply import SupplyNode import pickle if RDConfig.usePgSQL: from pyPgSQL import PgSQL as sql class _lazyDataSeq: """ These classes are used to speed up (a lot...
import time import logging import random from portalocker import Lock from portalocker.exceptions import LockException from O365.utils import FirestoreBackend, FileSystemTokenBackend log = logging.getLogger(__name__) # This is an implementation of the 'should_refresh_token' method class LockableFirestoreBackend(F...
# This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2020 <NAME> for Adafruit Industries # # 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 th...
import pytest from code42cli.util import _PADDING_SIZE from code42cli.util import does_user_agree from code42cli.util import find_format_width from code42cli.util import format_string_list_to_columns from code42cli.util import get_url_parts TEST_HEADER = {"key1": "Column 1", "key2": "Column 10", "key3": "Column 100"}...
# Copyright 2019 The FastEstimator 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 appl...
import numpy as np import matplotlib.pyplot as plt import matplotlib import h5py as h5 from importlib import reload import sys direc = sys.argv[0].split('scripts')[0] where = sys.argv[1] sys.path.append(direc+'support') import parameters reload(parameters) import parameters as par import functions reload(functions) imp...
import numpy as np from sklearn.model_selection import KFold import scipy.sparse as sp import torch def data_loader(dataset, flag, not_computational): if dataset == 'SL': if flag==0: with open("../data/sl/List_Proteins_in_SL.txt", "r") as inf: gene_name = [line.rstrip(...
# #!/usr/bin/env python3 # # _*_ coding:utf-8 _*_ # # CVE-2020-2551 # # updated 2020/03/07 # # by 0xn0ne # # 不会 java,该漏洞的分析也没人发,对该 POC 还不是很理解 #!/usr/bin/env python3 # -*- coding:utf-8 -*- import socket,argparse,sys,requests,os,atexit from urllib.parse import urlparse from multiprocessing.dummy import Pool as ThreadPo...
from flask import ( request, make_response, jsonify, redirect, session, current_app ) from flask_login import ( login_user, logout_user, login_required, current_user ) from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, get_jwt_identity ) from . import auth from googl...
from waflib import Task from waflib.TaskGen import feature, before_method, taskgen_method, extension from waflib.Tools import c_preproc try: import cPickle as pickle except ImportError: import pickle template_kernel = """ _MOTOR_PLUGIN_EXPORT void _%(kernel)s(const u32 index, const u32 total, ...
""" Copyright (C) 2021 <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, software dist...
""" Serialized Data Converter. Licensed under MIT Copyright (c) 2012 - 2015 <NAME> <<EMAIL>> """ import sublime import datetime from . import pyyaml as yaml from . import plistlib from collections import OrderedDict import re __all__ = ("read_yaml_from_view", "yaml_dumps") # http://yaml.org/type/timestamp.html YAML_...
# Copyright 2019-2020 ETH Zurich and the DaCe authors. All rights reserved. import dace from dace.sdfg import SDFG from dace.transformation.subgraph.stencil_tiling import StencilTiling from dace.transformation.subgraph import SubgraphFusion from dace.sdfg.graph import SubgraphView import numpy as np import pytest imp...
import wx import wx.grid as gridlib from pycoingecko import CoinGeckoAPI import pandas as pd from win10toast import ToastNotifier notifier = ToastNotifier() def sendNotifications(msg): notifier.show_toast("Coingecko", msg, icon_path=None,duration=1000,threaded=True) class Application(wx.Frame): def __init...
from heapq import merge import telebot from telebot import types import os from telebot import custom_filters from telebot.handler_backends import State, StatesGroup #States from telebot.storage import StateMemoryStorage from telebot.types import ReplyKeyboardMarkup, KeyboardButton class MyStates(StatesGroup): de...
import math class InvalidInt(Exception): pass class TooLessVars(Exception): pass class UnidentifiableName(Exception): pass def inv_sum_of_interior_angles(sum_interior_angle): self.sum_interior_angle = sum_interior_angle return (self.sum_interior_angle/180) + 2 def inv_interior_angles(interior_...
import os import subprocess import re def run_command(cmds, cwd='.'): return subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd).communicate()[0] def cmd_adb_devices(): return run_command(['adb', 'devices']) def cmd_getprop_ro_build_fingerprint(serial_id): return run_command...
#!/usr/bin/env python3 # Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at # http://www.apache.org/licenses/LICENS...
from collections import defaultdict, deque import numpy as np import ray from ray.experimental.serve.utils import logger from blist import sortedlist import time class Query: def __init__(self, request_args, request_kwargs, request_context, req...
from BeamlineStatusLogger.timer import SynchronizedPeriodicTimer from BeamlineStatusLogger.timer import PeriodicTimer import BeamlineStatusLogger.timer as timer import random import pytest from pytest import approx class MockTime: def __init__(self, time=100): self.time = time def mocktime(self): ...
import unittest from galaxy import model from galaxy.workflow.run import WorkflowProgress from .workflow_support import TestApp, yaml_to_model TEST_WORKFLOW_YAML = """ steps: - type: "data_input" tool_inputs: {"name": "input1"} - type: "data_input" tool_inputs: {"name": "input2"} - type: "tool" too...
import numpy as np import pyvista as pv import pyvistaqt as pvqt import matplotlib.pyplot as plt from collections import OrderedDict import pandas as pd def create_nodal_radial_vectors(X0): """ Create a list of fixed nodal inward radial vectors names (unit vectors) Parameters: - X0: unde...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import scipy.io from scipy import misc import tensorflow as tf from constants import OBJECTNET3D_DATADIR, OBJECTNET3D_TF_DATADIR from datasets import dataset_utils # The names of the cl...
#!/usr/bin/env python3 # # MIT License # # (C) Copyright 2019-2022 Hewlett Packard Enterprise Development LP # # 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 w...
######################################################## ### ### ### IBM Spectrum Protect Plus ### ### ### ### Microsoft SQL support REST API sample script ### ### ...
# -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Author: <NAME> # Institute: The Seismology Lab, the Chinese University of Hong Kong # Reference: Yang, <NAME>, and <NAME>(2009), Fault-Plane Determination of # the 18 April 2008 Mt. Carmel, Illinois, E...
''' System identification with post-stabilization enabled Loss: MSELoss constructed over ALL points in a SINGLE trajectory Optimizer: RMSProp from PyTorch ''' import os import sys import time import math from math import sin, cos import cv2 import pygame import numpy as np import matplotlib.pyplot as plt from mpl_too...
import hashlib import os import tempfile import matplotlib.pyplot as plt import neptune import numpy as np import optuna import tensorflow as tf from tensorflow import keras def log_data(logs): neptune.log_metric('epoch_accuracy', logs['accuracy']) neptune.log_metric('epoch_loss', logs['loss']) def train_e...
# # kde.py: KDE utilities for density estimation in unusual topologies. # # Copyright 2012 <NAME> <<EMAIL>> # Modified 2017 <NAME> <<EMAIL>> to handle 1D KDEs # gracefully. # # 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...
import re from ..queue import Queue from ..item import Item from ..commander import Command from ..commander import Commander from busy import dateparser MARKER = re.compile(r'\s*\-*\>\s*') REPEAT = re.compile(r'^\s*repeat(?:\s+[io]n)?\s+(.+)\s*$', re.I) class Task(Item): def __init__(self, description=None): ...
# Copyright (C) 2002, <NAME> (<EMAIL>) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """The structure class, representing a macromolecular structure.""" from typing import List, NamedTuple import ...
# _________ .__ .__ ____ ___ __ .__.__ # \_ ___ \| | |__|_____ | | \_/ |_|__| | ______ # / \ \/| | | \____ \ | | /\ __\ | | / ___/ # \ \___| |_| | |_> > | | / | | | | |__\___ \ # \______ /____/__| __/ |______/ |__| |__|____/____ > # \/ ...
"""Library to interface with system programs.""" from __future__ import annotations from typing import Optional, Any, NamedTuple from solana.publickey import PublicKey from solana.system_program import SYS_PROGRAM_ID from solana.transaction import AccountMeta, TransactionInstruction from solana.utils.validate import ...
from io import BytesIO from typing import Iterator, Any import base64 import hashlib import urllib.request import xml.etree.ElementTree as ET class HLRequest(object): document = None def __init__(self): self.document = ET.Element('request') def __str__(self) -> str: return self.serialize...
import abc import utils from tqdm import tqdm import torch from torch import nn from torch.autograd import Variable from torch.utils.data import ConcatDataset # ============ # Base Classes # ============ class GenerativeMixin(object, metaclass=abc.ABCMeta): """Abstract base class which requires subclasses to def...
import sklearn import sklearn.preprocessing import sklearn.random_projection from sklearn.metrics import euclidean_distances from sklearn.exceptions import DataDimensionalityWarning from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing ...
#!/usr/bin/env python # cardinal_pythonlib/sqlalchemy/core_query.py """ =============================================================================== Original code copyright (C) 2009-2021 <NAME> (<EMAIL>). This file is part of cardinal_pythonlib. Licensed under the Apache License, Version 2.0 (the "Li...
import datetime from enum import Enum from itertools import groupby from typing import Any, Iterator, List, Tuple, Dict, Union import copy import bson import numpy as np from monty.json import MSONable from pydantic import BaseModel from pymatgen.analysis.structure_matcher import ( AbstractComparator, ElementC...
import time import numpy as np from numpy import linalg import miccs.optimize as core def fit(observations, lambda_glasso, lambda_ridge=0, ths = 0.001, max_iter = 1000, ths_glasso = 1e-8, ths_lasso = 1e-10, verbose = False, weight_init = None, Omega_init = None): # check on observa...
"""Test inline query logic.""" import pytest from tests.factories import sticker_factory from stickerfinder.models import Tag from stickerfinder.telegram.inline_query.context import Context from stickerfinder.telegram.inline_query.search import get_matching_stickers @pytest.mark.parametrize('query,first_score, secon...
import torch from torch import nn as nn from torch.nn import functional as F from basicsr.utils.registry import ARCH_REGISTRY from .spynet_arch import SpyNet from .arch_util import ResidualBlockNoBN, flow_warp, make_layer @ARCH_REGISTRY.register() class BasicVSR(nn.Module): """BasicVSR: The Search for Essential ...
import time import numpy as np import tensorflow as tf import model as ml import runner as rn import utils as ul import market_making_game as env from baselines.common import explained_variance from baselines import logger def learn(policy, env, config): noptepochs = 8 nminibatches = 8 lr = lambda _: 0.0001 ...
import multiprocessing import os import sys import threading import typing from multiprocessing import connection #from uncompyle6 import main as Uncompyle6Main from unpyc37 import unpyc3 # noinspection SpellCheckingInspection from decompyle3 import main as Decompyle3Main _decompileProcess = None # type: typing.Opti...
""" A light and fast template engine. Copyright (c) 2012, <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 o...