text
stringlengths
3.07k
22.1k
# -*- coding: utf-8 -*- import os import shutil import sys import unittest from tempfile import TemporaryDirectory import pytest from mltk import * from mltk.utils import json_loads from tests.helpers import set_environ_context, get_file_content, zip_snapshot @config_params(undefined_fields=True) class _YourConfig...
import datetime import logging import os import requests import tempfile import wget from django.db.models import Q from django.conf import settings from obs import ObsClient from django.core.management.base import BaseCommand from meetings.models import Meeting, Video, Record from multiprocessing.dummy import Pool as ...
""" To run this template just do: python gan.py After a few epochs, launch tensorboard to see the images being generated at every batch. tensorboard --logdir default """ import logging import os import os.path as osp import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.f...
''' IO utility functions for MDA filetype source: https://github.com/flatironinstitute/mountainsort/blob/master/packages/pyms/mlpy/mdaio.py ''' import struct import numpy as np class MdaHeader: def __init__(self, dt0, dims0): uses64bitdims=(max(dims0)>2e9) self.uses64bitdims=uses64bit...
#!/usr/bin/env python # ClusterShell (local) test suite # Written by <NAME> """Unit test for ClusterShell Task (event-based mode)""" import copy import sys import unittest sys.path.insert(0, '../lib') import ClusterShell from ClusterShell.NodeSet import NodeSet from ClusterShell.Task import * from ClusterShell.Ev...
import os import random import torch.nn as nn import torch import math import config from typing import Union,Tuple import pytorch_lightning as pl import copy class ConvNorm1d(nn.Module): def __init__(self,in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int]], stride: Union[int, ...
from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime, timedelta from typing import Any, List, Optional, Tuple, Union, ClassVar, Type import attr from attr.converters import optional as c_optional from attr.validators import in_, instance_of, optional as v_optional fro...
import tensorflow as tf import numpy as np def sampling(z_mean, z_log_sigma, batchsize, length): eps = tf.random_normal(shape=(batchsize, length), mean=0., stddev=4.) return z_mean + tf.exp(z_log_sigma) * eps def leaky_relu(x, alpha=0.2): """ Calculate activation with leaky Relu Parameters --...
from cluster.database import Model, SurrogatePK, backref, relationship from flask_user import UserMixin from sqlalchemy import Column, Integer, String, ForeignKey, Boolean, DateTime from cluster.database.filename_constants import XYS, EXPRESSION, CLUSTERING, MARKER_TABLE, STATE from sqlalchemy import UniqueConstraint, ...
import json import math from aiohttp import web global g_majorWeights def getWeight(diff): return math.exp(-(diff - 5)**2 / (2 * 10**2)) g_majorWeights = { "A+": 4, "A": 3.6, "A-": 3.3, "B+": 3, "B": 2.6, "B-": 2.3, "C+": 2, "C": 1.6, "C-": 1.3 } provinceIDs = { '北京': ...
# Copyright 2013 by <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, sof...
from fractions import Fraction from django.contrib.auth.decorators import login_required from django.core import serializers from django.core.exceptions import ObjectDoesNotExist from django.http import JsonResponse from django.shortcuts import render, redirect, get_object_or_404, reverse from django.views.decorators.c...
from model.detection.yolo import * from model.detection.efficientdet import * class New_Predictor(nn.Module): """ __version__ = 1.1 __date__ = Mar 23, 2022 Created by hotcouscous1. The difference from the predictor of YoloV4 is that this has depth-scalable lateral layers. Unlike Yolo-FPNs f...
import os import shutil import multiprocessing from subprocess import call from operator import itemgetter from re import sub KERNEL_ROOT_DIR = "/usr/src" MODULES_ROOT_DIR = "/lib/modules" GRUB_ROOT_DIR = "/boot" class SelectedKernel(object): """ Represents the selected kernel, that is the one /usr/src/linu...
from pathlib import Path from time import sleep import pytest from cloudpathlib.local import LocalGSPath, LocalS3Path, LocalS3Client from cloudpathlib.exceptions import ( CloudPathFileExistsError, CloudPathNotADirectoryError, OverwriteNewerCloudError, ) @pytest.fixture def upload_assets_dir(tmpdir): ...
import os import subprocess from flask import make_response, Flask, render_template, request, redirect, send_from_directory, flash, url_for from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from forms import LoginForm, UserForm, DeleteForm, RegisterForm from flask_table import Table, Col from we...
#!/usr/bin/env python from math import pi from uncertainties import unumpy, umath, UFloat import numpy as np # local modules from .com import total_com def combine_bike_rider(bicyclePar, riderPar): """ Combines the inertia of the bicycle frame with the inertia of a rider. Parameters ---------- ...
import numpy as np from scipy import linalg from hmmlearn.hmm import GaussianHMM from hmmlearn.base import ConvergenceMonitor from sklearn.utils import check_array from hmmlearn.utils import iter_from_X_lengths ################################################################################################### # Classe...
from anytree import * import yaml def load_configuration(filename): """ Load a configuration parameters from *filename*. If there are any troubles the display an error message and return empty dict :param filename: filename in YAML format :type filename: string :return: configuration parameters :rtype: dict...
""" Module containing views for administration panel """ from django.core import mail from django.utils import timezone from django.db.utils import IntegrityError from rest_framework.response import Response from rest_framework import status, generics, permissions from rest_framework.serializers import Serializer from...
import os import numpy as np from keras import backend as K from keras.models import Model, model_from_json from keras.layers import Input, Dense, Flatten from prednet import PredNet from data_utils import SequenceGenerator, data_padding from scipy import sparse from scipy.sparse import * from numba im...
from bs4 import BeautifulSoup import requests import argparse import re import os import sys import time import random parser = argparse.ArgumentParser( description="""Crawler for past twitter tweets. """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-q", "--query", type=str, ...
# -*- coding: utf-8 -*- """ This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. """ import sys impor...
import logging import os import random import warnings from functools import partial from time import time from tqdm import tqdm import h5py import mne import numpy as np from sklearn.preprocessing import OneHotEncoder COHORT = "eegbci" logger = logging.getLogger("eegbci") def process_subject_fn(subject, runs, dat...
import requests import urllib from bs4 import BeautifulSoup from collections import defaultdict from discogstagger.wordprocessor import WordProcessor class WebCrawler: def __init__(self): self.base_url = "https://discogs.com" self.header = { 'User-Agent': 'Discogs Tagger User Agent 1....
from django import forms from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from .models import StudentInfo, ParentalMetricScore class LoginForm(AuthenticationForm): username = forms.RegexField(regex=r'^[\w\d...
#!/usr/bin/env python # # 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 "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, co...
# Copyright 2015 Mirantis, 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 ...
import fcntl import os import signal import subprocess import sys import time from dataclasses import dataclass from pathlib import Path from typing import Optional, Union from shpyx.errors import InternalError, VerificationError from shpyx.result import ShellCmdResult def _is_action_required(user_value: Optional[bo...
""" Module implements guides when moving items and handles around. """ from __future__ import division from builtins import map from builtins import object from functools import reduce from simplegeneric import generic from gaphas.aspect import InMotion, HandleInMotion, PaintFocused from gaphas.aspect import ItemInM...
import pickle import warnings from types import SimpleNamespace import gym import numpy as np from . import camera, collision_objects, trifingerpro_limits from .sim_finger import SimFinger from .tasks import move_cube class ObjectPose: """A pure-python copy of trifinger_object_tracking::ObjectPose.""" __sl...
from dataclasses import dataclass, field from typing import List import matplotlib.pyplot as plt import seaborn as sns import numpy as np from itertools import cycle from tarpan.shared.info_path import InfoPath, get_info_path from tarpan.plot.utils import remove_ticks_labels @dataclass class ScatterKdeParams: tit...
# wikimedia functions .wikimedia.py """ collection of existing Python tools and Wikimedia/Data endpoints """ import os import pandas as pd import xml.etree.ElementTree as ET from amidict import Resources # SPARQL keywords WIKIDATA_QUERY_URL = 'https://query.wikidata.org/sparql' RESULTS_NS = "http://www.w3.org/2005/spa...
# -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # # 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...
""" Filename: spatial_weights.py Author: <NAME>, <EMAIL> Description: Functions for calculating spatial weights """ # Import general Python modules import sys, os, pdb import argparse, math import numpy import iris from iris.analysis.cartography import cosine_latitude_weights import gsw # Import my modul...
from random import randint from math import sin, cos, tan import pygame class Vector2: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y return def as_int_tuple(self) -> tuple: return (int(self.x), int(self.y)) def ait_with_offset(self, offset:...
from gan import models from gan import help from gan import losses import torch import argparse import os import re import pickle import matplotlib.pyplot as plt import numpy as np # load the model and real data def G_model(restore_path, opt): G_a = models.AgentGenerator(opt) ckpt= torch.load(restore_path) ...
import random import zipfile import itertools import operator import csv from datetime import datetime import random import sys import nltk import numpy as np nltk.download('punkt') vocabulary_size = 8000 unknown_token = "<PASSWORD>" sentence_start_token = "<PASSWORD>" sentence_end_token = "<PASSWORD>" # Read the dat...
import pandas as pd import numpy as np import random import math import argparse import time #self-defined from handler.student_handler import Student from handler.room_handler import Room from .static.config import PREFERENCE_DICT, NATIONALITIES, LOCAL_NATIONALITY, logging from .init_helper import df2object_student f...
# coding: utf-8 import markovify from flask import Flask from flask import g, session, request, url_for, flash from flask import redirect, render_template from flask_oauthlib.client import OAuth from flask_bootstrap import Bootstrap from pymongo import MongoClient # Database connector import twitter import json import...
import collections import functools import multiprocessing import os from typing import Set import numpy as np import tensorflow as tf def is_image(tensor): return len(tensor.shape) == 3 and tensor.shape[-1] in [1, 3, 4] def batch_to_seq(tensor_batch, n_batch, n_steps, flat=False): if flat: tensor_...
""" Created on Tue Mar 13 18:16:11 2018 @author: Bogdan """ from nltk.corpus import wordnet as wn from nltk.tokenize import word_tokenize as w_tok from nltk.stem import WordNetLemmatizer from nltk.tag import pos_tag import wsd_utils as utils def overlap(gloss1, gloss2): """Determines the longest sequence of comm...
from typing import Tuple, Iterator from enum import Enum, unique import re from pybibtex.bibliography import Database, Item @unique class TokenType(Enum): LCBRACE = '{' RCBRACE = '}' LPAR = '(' RPAR = ')' SPACE = 'SPC' NL = 'NWL' EOS = '\0' CHAR = 'CHR' AT = '@' QUOTE = '"' ...
import os class InkColor: ENDC = '\033[0m' BOLD = '\033[1m' DIM = '\033[2m' UNDERLINE = '\033[4m' FLASHING = '\033[5m' INVERT = '\033[7m' LIGHTCYAN = '\033[96m' CYAN = '\033[36m' BLACK = '\033[97m' LIGHTGREY = '\033[37m' GRAY = '\033[90m' DARKGRAY = '\033[30m' RED ...
import csv import glob import xml.etree.ElementTree as ET import nibabel as nib import numpy as np import os from mri_tools.common import ensure_unzipped __author__ = '<NAME>' __date__ = "2015-08-06" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" class ROIAggregate(object): def aggregate(self, values): ...
import json from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase, force_authenticate from ..models import User, Category, Title, Review class UserTests(APITestCase): def test_create_user(self): u...
# # This file made available under CC0 1.0 Universal (https://creativecommons.org/publicdomain/zero/1.0/legalcode) # # Created with the Rule Development Kit: https://github.com/awslabs/aws-config-rdk # Can be used stand-alone or with the Rule Compliance Engine: https://github.com/awslabs/aws-config-engine-for-complianc...
"""Source decision helper""" from enum import Enum from typing import Any, Optional from django.contrib import messages from django.db import IntegrityError from django.db.models.query_utils import Q from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest from django.shortcuts import redirect from dj...
import logging from argparse import ArgumentParser from ragavi import __version__ logger = logging.getLogger(__name__) class ArgumentParserError(Exception): pass class MyParser(ArgumentParser): def error(self, message): raise ArgumentParserError(message) # for ragavi-vis def vis_argparser(): ...
"""Core module for runflow.""" import enum import inspect import logging import traceback import asyncio from functools import reduce import networkx from decouple import config from tenacity import ( retry, stop_after_delay, stop_after_attempt, ) from . import hcl2, utils from .errors import ( Runfl...
import os import os.path as osp from collections import OrderedDict from functools import reduce import pandas as pd import mmcv import numpy as np from mmcv.utils import print_log from prettytable import PrettyTable from torch.utils.data import Dataset from mmseg.core import eval_metrics from mmseg.utils ...
#! /usr/bin/env python3.6 import argparse import torch import os import numpy as np from tensorboardX import SummaryWriter from algorithm import MASAC from buffer import ReplayBuffer from env_wrapper import ParallelEnv from mapf_env import Environment from misc import from_unit_actions, to_unit_actions, LinearDecay fr...
""" for reference (not used anywhere): https://www.pettingzoo.ml/classic """ import json import random import chess import chess.pgn import torch import numpy as np import torch.nn.functional as F from model import BaseHFGPT, ModelConfig ####### Engine ################################# # Here I am writing a simple gam...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This statistics file is meant to try each of our program in a more realist way than # the original one # import os import time import subprocess import ast # # Editable configuration # You are welcome to edit this configuration # PROGRAMS = ["ourIA/closest.py", "ou...
# MIT License # # Copyright (c) 2020 <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 use, copy, modify, me...
## Implementing Sequencing Modelling ## Building a bi-directional encoder and decoder using tensor flow ## So we can talk about the future and the past both, via model using pattern recognition import tensorflow as tf # this is for ML import helpers as helpers # clearing cache in case of multiple graphs tf.reset_def...
import numpy as np import numpy.linalg as LA import matplotlib.pyplot as plt import torch import torch.nn as nn from tqdm import tqdm, trange from torch.utils.data import TensorDataset from plotly.subplots import make_subplots import plotly.graph_objects as go def visualize3D(vis_net, x, y, dir1, dir2, dir3, len1 = 1,...
# coding=utf-8 # # created by kpe on 28.04.2020 at 11:08 AM # from __future__ import division, absolute_import, print_function import os import random import pprint from typing import Tuple, List, Text, Dict, Union, Any from absl import logging as log import numpy as np import tensorflow as tf import params as pp...
# pyright: reportWildcardImportFromLibrary=false import asyncio import logging import sys import time as pytime from math import inf from typing import Optional import pygame import pygame.display import pygame.draw import pygame.event import pygame.mouse import pygame.time from and_beyond.utils import DEBUG, init_log...
from utils.image import ImgDraw from nonebot.adapters.cqhttp.event import GroupMessageEvent import pymongo import datetime from utils.group import User, make_query from utils import NAME import os import json import random import nonebot from nonebot import on_command from nonebot.adapters.cqhttp import Bot, MessageEv...
""" ncexplorer.plotter.projection ----------------------------- This module contains wrapper classes for some of the large set of projections implemented in Matplotlib.pyplot. @created: May 30, 2017 @author: neil """ from ncexplorer.const import LOC_UCLA as UCLA from ncexplorer.const import LAMBERT_NORTH_AMERICA from...
import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt def read_perturbations_csv(adata_here,cell2guide_csv,guide2gene_csv=None,pref='perturb', sep='\t',copy=False): import pandas as pd if copy: adata_here = adata_here.copy() #read cel...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = '<NAME>' __version__ = '4.0' __email__ = '<EMAIL>' __github__ = 'https://github.com/mufeedvh/basecrack' import os import re import sys import time import platform import json import argparse from colorama import init from termcolor import colored from pa...
""" LCM: Linear time Closed item set Miner as described in `http://lig-membres.imag.fr/termier/HLCM/hlcm.pdf` url: https://github.com/scikit-mine/scikit-mine/blob/master/skmine/preprocessing/lcm.py """ # Author: <NAME> <<EMAIL>> # License: BSD 3 clause from collections import defaultdict import numpy as np import ...
# -*- coding: UTF-8 -*- # TODO: Incorporate LMDB-based dataloading """Utilities for constructing the appropriate set of torch Datasets & DataLoaders. Functions "prepare_dataset(...)" and "prepare_dataloader(...)" construct a set of torch Datasets and DataLoaders respectively based off of configurations specified in ...
from .core.protocol import Request, Range from .core.protocol import SymbolKind from .core.registry import LspTextCommand from .core.typing import Any, List, Optional, Tuple, Dict from .core.views import location_to_encoded_filename from .core.views import range_to_region from .core.views import text_document_identifie...
import logging import sys from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.utils.translation import gettext_lazy as _ from onelogin.saml2.utils import OneLogin_Saml2_ValidationError from .choices import SectorType from .exceptions import eHerkenningNoRS...
#!/usr/bin/python # Copyright 2015 The ANGLE Project Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # gen_texture_format_table.py: # Code generation for texture format map # import json import pprint template = """// GENERATED FIL...
import os import networkx as nx import pandas as pd def induced_subgraph( G, filter_type, filter_attribute, filter_values, ignore_attrs=False ): """ Create custom induced subgraph. Args: filter_type: 'node' or 'edge' filter_attribute: attribute to filter on filter_values: att...
"""Contains utilities for handling dimensions.""" import logging import math from copy import deepcopy from typing import Any, List, Optional, Tuple, TypedDict, Union import numpy as np # type: ignore[import] import pandas as pd # type: ignore[import] CatBin = Union[str, pd.Interval] def analyze_data_type(data_...
# -*- coding: utf-8 -*- """ Created on Fri Nov 16 08:08:33 2018 Machine Learning to train model. Run each cell separately in order Model naming convention: Model_Version_inputxoutput_YYYY-MM-DD-HH-MM-SS e.g. Model_3-1_56x26_2018-12-02-12-07-26 Version and input & output size must match for valid model @author: mik...
#!/usr/bin/env python """ @file route_departOffset.py @author <NAME> @author <NAME> @date 11.09.2009 @version $Id$ Applies a given offset to the given route's departure time SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ Copyright (C) 2008-2017 DLR (http://www.dlr.de/) and contributors This file...
import os import torch import torchvision.transforms as transforms import torch.nn.functional as F import numpy as np from ZSSGAN.criteria.clip_loss import DirectionLoss from ZSSGAN.model.psp import pSp from utils.svm import train_boundary from sklearn import svm def adjust_sigmoid(x, beta=1): return torch.sigm...
# -*- coding: utf-8 -*- """ Created on Wed Oct 31 19:31:00 2018 @author: shirhe-lyh Convert raw dataset to TFRecord for object_detection. """ import glob import hashlib import io import json import numpy as np import os import PIL.Image import tensorflow as tf import read_pbtxt_file flags =...
""" LSTM MODEL STUFF """ import numpy as np import scipy.io as sio import json import tensorflow as tf from pandas import DataFrame, Series, concat from tensorflow.python.keras.layers import Input, Dense, LSTM from tensorflow.python.keras.models import Sequential from random import randrange from sklearn.preprocessing...
#!/usr/bin/python3 # 8 bit RLE compressor # written by <NAME> 2020 # for SNES background maps (and other things) # all 8 bit units, and 8-16 bit headers # non-planar and planar combined version # (planar = split all even and odd bytes) # it tests both and outputs only the smaller # eof byte (last of file) of F0 indi...
import random import string import cv2 import numpy as np import scipy from Util import Util from ObjectDetector import BoundingBox class Person: def __init__(self, human_bounding_box=None, human_pose=None, face_bounding_box=None, facial_landmarks=None, facial_emotion=None, id='random'): if id == 'random...
class Mention: def __init__(self, doc_name, sent_num, start, end, words): self.doc_name = doc_name self.sent_num = sent_num self.start = start self.end = end self.words = words self.gold_parse_is_set = False self.gold_parse = None self.min_spans = set(...
#!/usr/bin/env python3 import time import random from operator import or_ from functools import reduce from utils import memfill, memcheck ################################################################################ class DRAMAddressConverter: def __init__(self, colbits=10, rowbits=14, bankbits=3, ...
## # https://stackoverflow.com/questions/990422/how-to-get-a-reference-to-current-modules-attributes-in-python import inspect import re import time import sys import os import yaml from concurrent.futures import ThreadPoolExecutor, as_completed import click from colorama import init, Fore from pyVmomi import vim, vm...
#~~API:Feature~~ import json, uuid from portality.core import app from flask import request from copy import deepcopy from link_header import LinkHeader, Link LINK_HEADERS = ['next', 'prev', 'last'] TOTAL_RESULTS_COUNT = ['total'] ERROR_TEMPLATE = {"status": {"type": "string"}, "error": {"type": "string"}} CREATED_TE...
#!/usr/bin/env python3 #-*- coding: iso-8859-1 -*- ################################################################################ # # This module implements the central facility for request processing - # a thread pool of fixed maximum size, allocating and deallocating threads # as necessary. # # Pythomnic3k project ...
from html.parser import HTMLParser import io class Node: def __init__(self, tag="", attrs={}): self.tag = tag self.attrs = {} for p in attrs: if p[1].strip() == "": continue self.attrs[p[0]] = p[1] self.data = "" self.children = [] ...
# 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 # distributed under t...
import logging from datetime import date from django.conf import settings from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect from django.urls import reverse_lazy from django.views.generic.edit import FormView, UpdateView from django.views....
#!/usr/bin/python3 """ Given a parsed PHP trace (PHPTraceParser.py@Trace) This file will parse all function calls, with their parameters and their respective return values. """ from wsEventServer import start_server import asyncio import logging import argparse import sqlite3 import os import os.path import re import...
from __future__ import print_function import ctypes import sys class PyObject(ctypes.Structure): '''ctypes representation of PyObject_HEAD''' _fields_ = ( ('ob_refcnt', ctypes.c_size_t), ('ob_type', ctypes.c_void_p), ) class SofaPySPtr(ctypes.Structure): '''ctypes representation ...
"""Driver for solving the coupled perturbed Hartree-Fock (CPHF) equations.""" from abc import ABC, abstractmethod from typing import Optional, Sequence import numpy as np from pyresponse.core import Hamiltonian, Program, Spin from pyresponse.operators import Operator from pyresponse.solvers import Solver from pyresp...
from rest_framework import viewsets from rest_framework.generics import GenericAPIView, CreateAPIView, UpdateAPIView from rest_framework.views import APIView from django.shortcuts import get_object_or_404 from django.contrib.auth import get_user_model from posts.utils import Visibility from posts.models import Post fro...
import cv2 import numpy as np # Utility function to draw points in a quadrilateral polygon def quadrilateral_points(input_image, vertices): output_image = np.copy(input_image) color = [0, 0, 255] # Red thickness = 2 radius = 3 x0, y0 = vertices[0] x1, y1 = vertices[1] x2, y2 = vertices[2]...
from typing import List import PySimpleGUI as sg import numpy as np from framework.DataConstants import TYPE_CHART_MULTIPLIER, DEFAULT_PKM_N_MOVES, DEFAULT_PARTY_SIZE from framework.DataObjects import PkmMove, GameStateView from framework.DataTypes import PkmStat, PkmType, WeatherCondition, PkmStatus from framework.b...
import pytest from obsidiantools.md_utils import (_get_all_wikilinks_from_html_content, _get_all_embedded_files_from_html_content, _get_unique_wikilinks, _get_all_md_link_info_from_ascii_plaintext, ...
import os.path import re from ...assets import default_resolver def remove_comments(comment_symbol, text): return re.sub(f'{comment_symbol}.*', '', text).strip() class PathResolver: def __init__(self, filepath): self._base = os.path.dirname(os.path.abspath(filepath)) def resolve(self, filepath...
from __future__ import division from builtins import range from builtins import object from past.utils import old_div import sys import pyglet from pyglet.window import key from psychopy.visual import Window, shape, TextStim, GratingStim, Circle from psychopy.visual.windowwarp import Warper from psychopy import event, ...
"""Integration tests for Job import and export.""" import copy from operator import attrgetter from time import sleep from typing import Any, Callable, List, Optional, Tuple import pytest from brewtils import EasyClient # type: ignore from brewtils.models import ( # type: ignore IntervalTrigger, Job, Req...
#coding:utf-8 import numpy as np import tensorflow as tf import prettytensor as pt from matplotlib import pyplot as plt from tensorflow.examples.tutorials.mnist import input_data import os import time from datetime import timedelta from sklearn.metrics import confusion_matrix import math print("tensorflow version:", t...
#!/usr/bin/env python # just testing basic parallelization that will be used in the actual project from __future__ import division,unicode_literals from future.builtins import map,zip, range import numpy as np import itertools as it # setup proper logging import logging logger = logging.getLogger('psnobfit') logger.se...
import logging import os import shutil import numpy as np import unittest import doctest from pathlib import Path import pysnptools.util as pstutil from pysnptools.pstreader import PstData from pysnptools.pstreader import PstMemMap from pysnptools.snpreader import SnpReader, SnpData from pysnptools.standardizer import...
import os import warnings # to disable tensorflow-numpy warnings: from https://github.com/tensorflow/tensorflow/issues/30427 warnings.filterwarnings('ignore', category=FutureWarning) import keras from keras import backend as K from keras.models import Sequential from keras.layers import Conv2D, BatchNormalization, ...
# Copyright (c) 2018-2019 Huawei Technologies, 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 o...