text
stringlengths
3.07k
22.1k
import json import os import sys import jsonpatch import unittest import pytest from deepdiff import DeepDiff from mock import patch from dump.helper import create_template_dict, sort_lists from dump.plugins.port import Port from dump.match_infra import MatchEngine, ConnectionPool from swsscommon.swsscommon import Soni...
from __future__ import print_function import sys, random, json, os, tempfile from collections import Counter import numpy as np INSIDE_BLENDER = True try: import bpy from mathutils import Vector except ImportError as e: INSIDE_BLENDER = False if INSIDE_BLENDER: try: import utils except ImportError as e: ...
import os import random import numpy as np import cv2 from lxml import etree def mkdir(path): if not os.path.exists(path): os.makedirs(path) def object_random(objects): """ random choice the object :param objects: ['object1','object2',...] :return: 'object3' """ return random.choi...
# -*- coding: utf-8 -*- import re import bpy from bpy.types import Operator from collections import OrderedDict from mmd_tools import utils from mmd_tools.core import model as mmd_model from mmd_tools.core.morph import FnMorph from mmd_tools.core.material import FnMaterial PREFIX_PATT = r'(?P<prefix>[0-9A-Z]{3}_)(?...
# Copyright 2013-2021 The Salish Sea MEOPAR contributors # and The University of British Columbia # # 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/...
import pygame from pygame.locals import * from sys import exit from PIL import Image from PID import execute_PID import numpy as np # Global Variables larg = 1000.0 alt = 640.0 global position_, angle_, velocidade position_ = 0 angle_ = 0 velocidade = 0 class Screen: def __init__(self, larg, alt, bg_image): pygam...
import os import sys from dataclasses import asdict, dataclass from pprint import pprint from typing import Iterator, Optional, Tuple, List import matplotlib.pyplot as plt import numpy as np import pandas as pd # import torch from fastai.vision.all import ( CategoryBlock, ClassificationInterpretation, Col...
from collections import deque import pickle import cv2 import numpy as np import time import ast from utils import * import tensorflow_hub as hub import concurrent.futures from tensorflow.keras import layers import tensorflow as tf # Load Yolo net = cv2.dnn.readNet("./data/yolov4-tiny.weights", "./data/yolov4-tiny....
# Code made for <NAME> # 12 Abril 2021 # License MIT # Transport Phenomena: Python Program-Assessment 4.3 import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.optimize import minimize sns.set() # Solve for Temperature of Steam at given Pressure class enviroment_convective: def tem...
from __future__ import ( absolute_import, division, print_function, unicode_literals) import collections import copy import functools import itertools import json import jsonschema import logging import os import random from ruamel.yaml import YAML import six from six import iteritems from six.moves import range ...
# This is used for testing Fine Tune Hyper-Parameters from datetime import datetime import itertools import json import matplotlib.pyplot as plt import numpy as np from keras.callbacks import ModelCheckpoint from keras.wrappers.scikit_learn import KerasClassifier from keras_preprocessing.sequence import pad_sequences ...
# -*- coding: utf-8 -*- # Copyright 2017 Interstellar Technologies Inc. All Rights Reserved. from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from OpenGoddard.optimize import Problem, Guess, Condition, Dynamics class Rocket: g0 = 1.0 # Gravity at surface [-] def __in...
"""Tests for qnaplxdunpriv.py """ # pylint: disable=missing-function-docstring import grp import os import pathlib import pwd import re import subprocess import pytest from qnaplxdunpriv import FileAclError, set_uids, unset_uids import qnaplxdunpriv _TEST_UID = 10000 _TEST_FILE = 'file' _OWNER_GROUP_RE = re.compil...
"""Distributed Extension""" import re import os import sys try: import drmaa except: pass import itertools import argparse from cement.core import backend, handler, hook from scilifelab.pm.core import command LOG = backend.minimal_logger(__name__) class DistributedCommandHandler(command.CommandHandler): ...
#!/usr/bin/python3 """ Library for Raspberry Pi interfacing with the 16-Bit I/O Expander MCP23017 from Microchip Technology. """ __all__ = ["MCP23017", "LCD20x4"] import time import smbus from collections import Iterable class MCP23017: """ Class for the MCP23017 I/O port expander. """ REG_BASE_ADDR ...
import time,os,math,inspect,re,sys,random,argparse from env import SenseEnv from torch.autograd import Variable import numpy as np from itertools import count from collections import namedtuple from tensorboardX import SummaryWriter import torch import torch.nn as nn import torch.nn.functional as F import torch.optim a...
import sys def utr_selection(transcripts, log): """UTR selection function""" tmp = [] for t in transcripts: t.utr5_exons = t.utr5_regions() t.utr3_exons = t.utr3_regions() t.utr5_start = t.start if t.strand == '+' else t.end - 1 t.utr3_end = t.end - 1 if t.strand == '+' el...
from .utils import inverse as _inverse, gcd as _gcd import itertools as _itertools import re as _re import copy as _copy def affine_encrypt(msg, k, b): res = '' for c in msg: if c.isalpha() == False: res += c continue t = ord('A') if c.isupper() else ord('a') re...
from torch.autograd import Variable import torch.nn.functional as F import scripts.utils as utils import torch.nn as nn import numpy as np import torch class CrossEntropy2d(nn.Module): def __init__(self, size_average=True, ignore_label=255): super(CrossEntropy2d, self).__init__() self.size_average...
from __future__ import absolute_import from __future__ import with_statement import pickle from nose import SkipTest from kombu import Connection, Consumer, Producer, parse_url from kombu.connection import Resource from .mocks import Transport from .utils import TestCase from .utils import Mock, skip_if_not_module ...
#!/usr/bin/env python3 # # Copyright 2018 <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...
import os, sys import numpy as np import pandas as pd import matplotlib.pyplot as plt import skimage.io from skimage.transform import resize from imgaug import augmenters as iaa from random import randint import PIL from PIL import Image import cv2 from sklearn.utils import class_weight, shuffle import keras import wa...
#!/usr/bin/env python # coding: utf-8 import sys sys.path.append("../") import pandas as pd import numpy as np import pathlib import pickle import os import itertools import argparse import logging import helpers.feature_helpers as fh from collections import Counter OUTPUT_DF_TR = 'df_steps_tr.csv' OUTPUT_DF_VAL =...
import copy import importlib import os import numpy as np import tensorflow as tf import logging tf.get_logger().setLevel(logging.ERROR) from client import Client from server import Server from model import ServerModel from baseline_constants import MAIN_PARAMS, MODEL_PARAMS from fedbayes_helper import * from fedbaye...
# -*- coding: utf-8 -*- # Copyright (c) 2019, 2020 boringhexi """imccontainer.py - read/write IMC audio container files An IMC audio container file is a file type from Gitaroo Man that has the extension .IMC and contains audio subsongs.""" import struct from itertools import count, zip_longest from gitarootools.au...
import wx from gui.textutil import CopyFont, default_font #from gui.toolbox import prnt from wx import EXPAND,ALL,TOP,VERTICAL,ALIGN_CENTER_HORIZONTAL,ALIGN_CENTER_VERTICAL,LI_HORIZONTAL ALIGN_CENTER = ALIGN_CENTER_HORIZONTAL|ALIGN_CENTER_VERTICAL TOPLESS = ALL & ~TOP bgcolors = [ wx.Color(238, 238, 238), wx...
from __future__ import print_function from __future__ import division import os import sys import time import datetime import os.path as osp import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from torch.optim import lr_scheduler from args import...
import pandas as pd import matplotlib.pyplot as plt import matplotlib.style as style import numpy as np import os style.use('ggplot') grid_list = ['grid.168010.e', 'grid.1032.0', 'grid.7177.6', 'grid.194645.b', 'grid.6571.5'] dirname = os.getcwd() dirname = dirname + '/Data/' df_ARWU2018 = pd.read_csv(dirname + 'AR...
import numpy as np import unittest import pytest from pysph.base.particle_array import ParticleArray import pysph.tools.mesh_tools as G from pysph.base.utils import get_particle_array # Data of a unit length cube def cube_data(): points = np.array([[0., 0., 0.], [0., 1., 0.], ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # MySQL Connector/Python - MySQL driver written in Python. # Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. # MySQL Connector/Python is licensed under the terms of the GPLv2 # <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most ...
""" A copy from the existing FK code. This is not a real/pure DG method, I mean, the demagnetisation fields including the magnetic potential are not totally computed by DG methods, such as IP method or the mixed form using BDM and DG space. The idea is actually even we use DG space to represent the effective field an...
import torch import torch.nn as nn import torch.nn.functional as F class sub_pixel(nn.Module): def __init__(self, scale, act=False): super(sub_pixel, self).__init__() modules = [] modules.append(nn.PixelShuffle(scale)) self.body = nn.Sequential(*modules) def forward(self, x): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Constant settings for Cowbird application. Constants defined with format ``COWBIRD_[VARIABLE_NAME]`` can be matched with corresponding settings formatted as ``cowbird.[variable_name]`` in the ``cowbird.ini`` configuration file. .. note:: Since the ``cowbird.ini`` ...
import lxml import lxml.html from collections import defaultdict import voeventparse as vp import datetime import iso8601 from astropy.coordinates import SkyCoord import astropy.units as u from fourpisky.voevent import ( create_skeleton_4pisky_voevent, asassn_alert_substream, get_stream_ivorn_prefix, ) fro...
import os import itertools import re from typing import List, Optional, Tuple, Dict, Callable, Any, NamedTuple from string import Template from typing import List from tokenizers import Tokenizer, Encoding dirname = os.path.dirname(__file__) css_filename = os.path.join(dirname, "visualizer-styles.css") with open(css_...
# ----------------------------------------------------------------------------- # WSDM Cup 2017 Classification and Evaluation # # Copyright (c) 2017 <NAME>, <NAME>, <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ...
import os import numpy as np from sys import platform, path if platform == "linux" or platform == "linux2": path.insert(1, os.path.dirname(os.getcwd()) + "/src") FILE_NAME = os.path.dirname(os.getcwd()) + "/data" + "/xAPI-Edu-Data-Edited.csv" elif platform == "win32": path.insert(1, os.path.dirname(os.getc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author : <NAME> @file : at_app.py @time : 2019/01/02 @site : @software: PyCharm ,----------------, ,---------, ,-----------------------, ," ,"| ," ,"| ," ," |...
""" This module deals with querying and downloading LAT FITS files. """ # Scientific Library import numpy as np import pandas as pd # Requests Urls and Manupilate Files from astropy.utils.data import download_files_in_parallel, download_file from astroquery import fermi from tqdm import tqdm import requests import ...
""" Stats stuff! """ import textwrap import numpy as np import pandas as pd from scipy import stats from IPython.display import display from .boxes import * from .table_display import * __DEBUG__ = False def debug(*args, **kwargs): if __DEBUG__: print(*args, **kwargs) class Chi2Result(object): "...
############################################################################### # mockDensData.py: generate mock data following a given density ############################################################################### import os, os.path import pickle import multiprocessing from optparse import OptionParser import...
"""Test responses from Denon/Marantz.""" from pyavreceiver.denon.response import DenonMessage def test_separate(message_none): """Test separation of messages.""" assert message_none.separate("PWON") == ("PW", None, "ON") assert message_none.separate("PWSTANDBY") == ("PW", None, "STANDBY") assert mess...
# We often don't use all members of all the pyuv callbacks # pylint: disable=unused-argument import sys, hashlib import logging import os import pickle import signal import argparse import re import pyuv from ..__main__ import getObjectFileHash class HashCache: def __init__(self, loop, excludePatterns, disableWat...
import copy import numpy as np import pandas as pd import os import contextlib from sklearn.metrics import f1_score, accuracy_score from sklearn.model_selection import StratifiedKFold from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Standa...
""" Scrape card info from pokemon-card.com and save as csv file author: type-null date: July 2020 """ import bs4 import sys import requests import pandas as pd def getContent(cardId): # anti-scraping user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0" url = f'https:/...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import collections import csv import io import math import pathlib import re import pandas as pd class Barcode: """A TCGA barcode. TCGA barcodes can be truncated at almost any segment depending on what they represent, for example, a particiant, a sample or...
""" Indexes a dataset in Elasticsearch. The dataset consists of a dataset.json file and optional supporting files stored in the same directory. If a supporting file is found, it overrides that section of the dataset.json. Where possible dsloader attempts to enhance and complete information available in dataset.json ...
#!/usr/bin/env python # coding: utf8 # # Copyright (c) 2021 Centre National d'Etudes Spatiales (CNES). # # This file is part of PANDORA_MCCNN # # https://github.com/CNES/Pandora_MCCNN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens...
from os import path, remove import subprocess from glob import glob from shutil import move import MDAnalysis as mda from miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose from miscell.na_bp import d_n_bp, d_type_na from pdb_util.pdb import PDBReader, PDBWriter class PreliminaryAgent: ...
#! /usr/bin/env python3 import argparse from pathlib import Path import sys from scriptutil import get_nodes_to_ea, decode_file, gen_json_data, calc C0_OFF = "Task: C0, Corunner: OFF" C0_ON = "Task: C0, Corunner: ON" C0_ON_LOCAL = "Task: C0, Corunner: ON (Local)" C1_OFF = "Task: C1, Corunner: OFF" C1_ON = "Task: C1, ...
# -*- coding: utf-8 -*- """ Copyright [2009-2018] EMBL-European Bioinformatics Institute 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...
import pytest from pyspark.sql import SparkSession from collections import defaultdict from dsgrid.project import Project from dsgrid.dataset.dataset import Dataset from dsgrid.dimension.base_models import DimensionType from dsgrid.exceptions import DSGValueNotRegistered, DSGInvalidDimensionMapping from dsgrid.tests.c...
# # Copyright (c) 2015-2020 <NAME> <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE...
import time from random import randint from threading import Lock from typing import List, Optional, Tuple import telegram from src.config import CONFIG from src.modules.antimat.antimat import Antimat from src.utils.cache import pure_cache, TWO_YEARS, cache, MONTH from src.utils.callback_helpers import get_callback_d...
import tensorflow as tf import csv import time from datetime import timedelta import sys import numpy as np from tensorflow.python.training import training_util from tensorflow.contrib import slim from tensorflow.python.ops import variables as tf_variables from ..configuration import * from .. import trainer, evaluator...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 7/20/20 8:07 PM # @Author : anonymous # @File : Mutation_equal.py #TODO:integrate transformation rules import re import random import mutation.gateCirq_EqualT as MC import mutation.gateQiskit_EqualT as MQ import mutation.gatePyQuil_EqualT as MP def figur...
import torch import random import torch.nn as nn from abc import abstractmethod from abc import ABCMeta from torch import Tensor from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Optional from .losses import GANLoss from .losses import GANTarget from ....
import os import sys import errno import importlib import contextlib # print("prepare Avalon Max Pipeline") from pyblish import api as pyblish from . import lib, workio from ..lib import logger from .. import api, io, schema, Session from ..vendor import six from ..vendor.Qt import QtCore, QtWidgets from ..pipeline i...
#!/usr/bin/env python # Author: by <NAME> on March 15, 2020 # Date: March 15, 2020 from matplotlib import pyplot from pydoc import pager from time import sleep import argparse import datetime as dt import json import matplotlib import pandas as pd import requests import seaborn import sys import yaml def main(): ...
# pylint: disable=C0103 # pylint: disable=unnecessary-lambda """ This module illustates the humble object principal whereby the business logic is seperated from the external interfaces. class CalendarClockDevice This class is an implementation of a Tango Device. No business logic exists in this class. class C...
"""運動学関係 2次のマクローリン展開 """ import sympy as sy from sympy import sqrt import sumi_maclaurin_2.P_0 as P_0 import sumi_maclaurin_2.P_1 as P_1 import sumi_maclaurin_2.P_2 as P_2 import sumi_maclaurin_2.R_0_0 as R_0_0 import sumi_maclaurin_2.R_0_1 as R_0_1 import sumi_maclaurin_2.R_0_2 as R_0_2 import sumi_maclaurin_2.R_0...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 1 08:04:50 2019 @author: alexandradarmon """ import random import numpy as np import seaborn as sns import matplotlib.pyplot as plt from punctuation.config import options from punctuation.visualisation.heatmap_functions import heatmap, annotate_he...
# Copyright (c) 2021 CatPy # # Python stdlib imports from typing import NamedTuple # # package imports #import xlwings as xw #from openpyxl import load_workbook # # class RiserData(NamedTuple): """Riser data""" name:str length_upper:float length_lower:float unit_weight:float diam...
# _______________________________________________________________________________________ # ___________________________________Welcome_____________________________________________ # _______________________________________________________________________________________ import pygame # Importing modul...
"""Algorithmic methods for the selection of common blocks in DiffBlocks - select_common_blocks - - segments_difference """ import re import tempfile import subprocess from collections import defaultdict, OrderedDict import numpy as np from ..biotools import reverse_complement, sequence_to_record def format_seq...
#pylint: skip-file """ NOTE: This is a local copy of the readers module, taken from the support-tools/timeseries repository. Provides functions to read FTDC data from either an FTDC file or from a file containing serverStatus JSON documents, one per line. Each reader takes a filename argument and returns a generator t...
from eylanglexer import reserved from eylanglexer import rules as lex_rules from eylanginterpreter import * from rply import ParserGenerator EYLANG_VARS = EylangVars() pg = ParserGenerator( list(reserved.values()) + [name for name, _ in lex_rules], precedence=[ ('left', ['AND', 'OR', 'NOT']), ...
import sys import numpy as np from skimage.measure import label def getSegType(mid): m_type = np.uint64 if mid<2**8: m_type = np.uint8 elif mid<2**16: m_type = np.uint16 elif mid<2**32: m_type = np.uint32 return m_type def seg2Count(seg,do_sort=True,rm_zero=False): sm =...
""" Manage Configuration AppMap recorder for Python. """ import inspect import logging from os.path import realpath from pathlib import Path import re import sys from textwrap import dedent import importlib_metadata import yaml from yaml.parser import ParserError from . import utils from .env import Env from .instru...
#! /usr/bin/env python3 import json import os import sys import re import argparse import time from math import floor from os.path import dirname from subprocess import Popen, PIPE, STDOUT from blessings import Terminal class Heatmap(object): coords = [ [ # Row 0 [ 4, 0], [ 4, 2]...
"""This module does the argument and config parsing, and contains the main function (that is called when calling pep8radius from shell).""" from __future__ import print_function import os import sys try: from configparser import ConfigParser as SafeConfigParser, NoSectionError except ImportError: # py2, pragma:...
import csv """Set of functions used to import from csv into the FIDO model. The import is specified as a dictionary, defining the model, the name of the primary key and the list of fields. Recursions are used to defind foreign keys.""" IMPORT_CSV_MODEL_KEY = "model" IMPORT_CSV_PK_NAME_KEY = "pk_name" IMPORT_CSV_PK_KE...
import sys import click from tabulate import tabulate import textwrap from . import admin from ...helper import is_admin from ...session import Session, is_legacy_server from ...versioning import get_naming, apply_version_aware_fields from ..pretty import print_error, print_fail # Lets say formattable options are: ...
from .abs_Qstate import _Qstate, unreal from .Basis import Basis from .Operator import MeasureOp, Op from .Qerrors import IllegalOperationError, InitializationError from .Qmath import ket, math, matrix, roundedVector from .qtils import Vdigit, equal, formatProbs, mod_square, prod, val2str #### Qbits.py # # This file c...
# Copyright 2021 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python3 """Creates a standard tiff image from RLENGTH data sent by Brother scanners.""" import struct import sys def rle_decode(data): """Decodes PackBits encoded data.""" i = 0 output = bytearray() while i < len(data): val = data[i] i += 1 if val == 0x80: ...
import pygame, math pygame.init() win = pygame.display.set_mode((1000, 600)) pygame.display.set_caption("Plumber") angle = [pygame.image.load('angl1.png'), pygame.image.load('angl2.png'), pygame.image.load('angl3.png'), pygame.image.load('angl4.png')] straight = [pygame.image.load('str1.png'), pyga...
# # BSD 3-Clause License # # Copyright (c) 2022 University of Wisconsin - Madison # 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 copyrig...
"""Implement some basic operations of SGD. """ #################################################### # Author: <<NAME>><EMAIL> # License: MIT #################################################### from activation import * def random_mini_batches(data, label, batch_size): """ creates a list of random mini batches fr...
import numpy as np import matplotlib.pyplot as plt import math from scipy.optimize import linprog from cvxpy import * class CuttingPlaneModel: def __init__(self, dim, bounds): self.dim = dim self.bounds = bounds self.coefficients = np.empty((0,dim+1)) def __call__(self, x):#REMOVE ...
import argparse import os import sys import numpy as np import pdb from tqdm import tqdm import cv2 import glob import numpy as np from numpy import * import matplotlib #matplotlib.use("Agg") #matplotlib.use("wx") #matplotlib.use('tkagg') import matplotlib.pyplot as plt import scipy from scipy.special import softmax ...
from itertools import combinations import numpy as np from PlanningCore.core.constants import State from PlanningCore.core.physics import ( ball_ball_collision, ball_cushion_collision, cue_strike, evolve_ball_motion, get_ball_ball_collision_time, get_ball_cushion_collision_time, get_roll_t...
#!/usr/bin/env python # Copyright 2015-2017 ARM 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 applicable...
"""Meter Parser Image Processing component and sensor.""" # Copyright 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...
#!/usr/bin/python3 # find_conserved_blocks_v*.py ########################### # Overview: # Script analyses DNA multi sequence alignment data and searches for areas # (blocks) which are conserved (i.e. identical or very similar). Required # input is any valid FASTA file with multiple sequences. # User can adjus...
from __future__ import absolute_import, unicode_literals import warnings from unittest import TestCase from immutable import Immutable, ImmutableFactory warnings.filterwarnings("ignore") class TestImmutableObjectFactory(TestCase): def test_create_empty(self): # unlike a namedtuple, you don't even nee...
#funcsboot.py from placerg.funcs import * from placerg.funcsrg import * from placerg.funcsall import * from placerg.objects import * from scipy.optimize import curve_fit def bootfunc(a, env): rate=[] coeff=[] eigspec=[] var=[] psil=[] actmom=[] autocorr=[] tau=[] ...
# -*- coding: UTF-8 -*- # 该算法比较慢 import operator # 牌型枚举 class ComeType: PASS, SINGLE, PAIR, TRIPLE, TRIPLE_ONE, TRIPLE_TWO, FOURTH_TWO_ONES, FOURTH_TWO_PAIRS, STRAIGHT, EVEN_PAIR, BOMB = \ range(11) # 3-14 分别代表 3-10, J, Q, K, A # 16, 18, 19 分别代表 2, little_joker, big_joker # 将 2 与其他牌分开是为了方便计算顺子 # 定义 HAN...
import enum import time from collections import namedtuple from dataclasses import dataclass, field from typing import List, Dict, Any, Union, Tuple, Sequence, Callable, Optional import gym import numpy as np from malib.utils.notations import deprecated """ Rename and definition of basic data types which are corresp...
import csv import datetime import re import json import unicodedata from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.contrib.auth.decorators i...
''' clyther.rttt -------------------- Run Time Type Tree (rttt) ''' from clast import cast from clyther.pybuiltins import builtin_map from inspect import isroutine, isclass, isfunction from meta.asttools.visitors import visit_children, Mutator from meta.asttools.visitors.print_visitor import print_ast from opencl im...
#GamePlay.py #<NAME>, <NAME>, <NAME> """This module contains the functions needed to support pentago gameplay. A pentago gameboard is represented by a 6x6 2D array. Each location on the board is initialized to "" and is set to 0 or 1 when the player or the AI respectively places a marble on that location. Each ar...
import h5py import matplotlib.pyplot as plt import numpy as np import scipy.io import scipy.stats import complex_pca def plot_pca_variance_curve(x: np.ndarray, title: str = 'PCA -- Variance Explained Curve') -> None: pca = complex_pca.ComplexPCA(n_components=x.shape[1]) pca.fit(x) plt.figure() plt.p...
import os from random import sample import numpy as np from numpy import cos from scipy.linalg import lstsq from compmech.constants import CMHOME from compmech.logger import * def load_c0(name, funcnum, m0, n0): path = os.path.join(CMHOME, 'conecyl', 'imperfections', 'c0', 'c0_{0}_f{1}_m{2:03d}_n{3:0...
from shapely.geometry import shape import fiona import networkx as nx import matplotlib.pyplot as plt import math import random import traffic import pickle from datetime import datetime from request import Request import numpy as np try: from itertools import izip as zip except ImportError: pass def main():...
from libs.graph.DLinkedList import Queue, DoubledLinkedList as List from libs.graph.PriorityQueue import PriorityQueueBinary as PriorityQueue from libs.graph.Tree import * #it is better to use a DoubledLinkedList to operate with a great efficiency on #the lists those will be used in the graph representation class Node...
"""Class to dynamically create the different forms in the config file """ import os from wtforms import ( BooleanField, SelectField, StringField, FloatField, IntegerField, FormField, TextAreaField, FieldList, DecimalField ) from wtforms.validators import InputRequired, Optional, NumberRange, \ ValidationEr...
#!/usr/bin/env python3 """ Extracts SSH keys from Bitwarden vault """ import argparse import json import logging import os import subprocess import pexpect import time from pkg_resources import parse_version def memoize(func): """ Decorator function to cache the results of another function call """ ...
# importing libraries import warnings warnings.filterwarnings("ignore") import sys import pandas as pd import numpy as np from matplotlib import pyplot as plt import xgboost as xgb from catboost import CatBoostRegressor import lightgbm as lgb from sqlalchemy import create_engine import pickle from sklearn.metrics impor...
from typing import Tuple, List puzzle = [ # || || [0, 0, 4, 0, 0, 7, 0, 6, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 9, 3, 0], # || || [0, 0, 0, 0, 0, 5, 0, 0, 2], [0, 0, 0, 0, 0, 0, 0, 4, 0], [0, 0, 0, 0, 3, 2, 5, 7, 0], # || || [5,...