text
stringlengths
3.07k
12.6k
# from https://github.com/chartbeat-labs/textacy/blob/master/textacy/constants.py AUX_DEPS = {"aux", "auxpass", "neg"} # from https://chartbeat-labs.github.io/textacy/_modules/textacy/spacier/utils.html import itertools import re def get_span_for_verb_auxiliaries(verb): """ Return document indexes spanning a...
''' Gui/Views/Crosslink_Discoverer/splash _____________________________________ Central widget for Crosslink Discoverer, which provides a splash menu for various configurations. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for ...
# -*- coding: utf-8 -*- # @Author : kevin_w import math import numpy as np import torch from modify.util import collect_action, GetRawObservations ball_pos = [0, 0, 0] player_pos = [0, 0, 0] last_team = 0 last_dist_to_ball = 0 last_dist_to_goal = 0 e = np.finfo(np.float32).eps.item() def action_modify(obs, action...
# Copyright 2019-2022 Huawei Technologies Co., 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 law or agre...
#!/usr/bin/env python # # spyne - Copyright (C) Spyne contributors. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later ve...
# -*- coding: utf-8 -*- """ Created on Fri Feb 21 07:45:26 2020 @author: <NAME> <EMAIL> """ import matplotlib.pyplot as plt import sympy as sp from scipy.integrate import solve_ivp from tkinter import Tk, StringVar, ttk, N, W, E, S import os clear = lambda: os.system('cls') cwd = os.getcwd() dir_path = os.path.dirn...
#Import dependencies import tensorflow as tf from keras.models import Sequential from keras.layers import LSTM, Bidirectional, Activation, Dropout, Dense,CuDNNLSTM, Embedding,GRU, CuDNNGRU from keras.callbacks import * from keras.optimizers import Adam from keras.utils import np_utils import numpy as np import pandas a...
# Licensed under the Upwork's API Terms of Use; # you may not use this file except in compliance with the Terms. # # 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 i...
import abc import sys import itertools from pysgrs import errors class GenericAlphabet(abc.ABC): def __repr__(self): return self.__str__() @abc.abstractmethod def encode(self, s: str) -> str: pass @abc.abstractmethod def decode(self, s: str, **kwargs) -> str: pass cla...
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber 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 # # Unles...
#!/usr/bin/env python import random import string import ftplib import zipfile import os import re import sys import socket def genRandomString(length): # генерирует и возвращает строку случайных символов заданой длины в нижнем регистре rS = ''.join(random.choices(string.ascii_lowercase + string.digits, k=length)...
import mock from xml.etree import ElementTree from tests.compat import unittest from evelink.thirdparty.six.moves.urllib.parse import parse_qs import evelink.api as evelink_api # Python 2.6's ElementTree raises xml.parsers.expat.ExpatError instead # of ElementTree.ParseError _xml_error = getattr(ElementTree, 'ParseE...
"""Numerical timestepping methods for stochastic differential equation (SDE) systems.""" import sympy import symnum.numpy as snp import symnum.diffops.symbolic as diffops def euler_maruyama_step(drift_func, diff_coeff): """Construct Euler-Maruyama integrator step function.""" def forward_func(z, x, v, δ): ...
from abc import abstractmethod import requests import jsonpickle import json HTTP_OK = 200 class CommandBase(object): def __init__(self): self._url = "" @property def _method(self): return "PUT" @property def url(self): return self._url @url.setter def url(s...
import os import time import json from struct import pack, unpack from base64 import b64encode, b64decode import gw2api __all__ = ("encode_item_link", "encode_coin_link", "encode_chat_link", "decode_chat_link") def mtime(path): """Get the modification time of a file, or -1 if the file does not exist...
"""S3 Stream client.""" from typing import Generator, Iterable, Optional, Tuple, Union, cast import boto3 from botocore import client as boto_client from tentaclio import fs, protocols, urls from . import base_client, decorators, exceptions __all__ = ["S3Client"] class S3Client(base_client.BaseClient["S3Client"]...
#!/usr/bin/env python3 """ The product of some transcriptome assemblies had sequences which contained large inverted repeats within some transcripts. We wanted a quick utility to detect these and generate a simple report on them. The input is just a FASTA file. This script will iterate over them, writing each to ...
import json from itertools import groupby from operator import itemgetter import django from django import forms from django.conf import settings from django.contrib.admin.views.decorators import staff_member_required from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectD...
""" Utility functions to be for tokenization and handling arguments.""" import argparse import os import json from collections import namedtuple from typing import Union from nltk import sent_tokenize from datasets import arrow_dataset MODEL_MAPPING = { "bert-base-multilingual-cased": "mbert", "xlm-roberta-b...
import os import textwrap import pytest import tpi from dvc.main import main from dvc.ui import ui from tests.utils import console_width from .conftest import BASIC_CONFIG @pytest.mark.parametrize( "slot,value", [ ("region", "us-west"), ("image", "iterative-cml"), ("spot", "True"), ...
from functools import wraps from typing import Union, Callable import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np import zproc from matplotlib.lines import Line2D zproc_ctx = zproc.Context() ZPROC_INTERNAL_NAMESPACE = "oscilloscope" class Normalizer: def __init__(self, o...
import os import difflib import itertools import pygments import pygments.lexers import pygments.formatters from server.constants import DIFF_SIZE_LIMIT, SOURCE_SIZE_LIMIT class File: def __init__(self, name, lines=(), source='', too_big=False): self.lines = lines self.name = name.lower() ...
import copy import prawcore import time import traceback from . import common from . import exceptions from . import tsdb from voussoirkit import vlogging log = vlogging.get_logger(__name__) def _listify(x): ''' The user may have given us a string containing multiple subreddits / users. Try to split tha...
"""The console log writer""" # -*- coding:utf-8 -*- import os import queue import sys import threading import time import traceback from .mslogconfig import MsConsoleLogConfig from .msloglevel import MsLogLevels from .mslogmsg import MsLogMessage from .mslogwriter import MsLogWriter __mutex = threading.RLock() __in...
import os import re import datetime import logging import json import yaml from slack_bolt import App from slack_sdk.errors import SlackApiError from slack_sdk import WebClient, logging # from MrPeanutButter.bot_utils import RandomGroups, RandomGroupParticipation, pick_random_quote from MrPeanutButter.bot_utils impor...
from typing import Dict, List from collections import OrderedDict import torch from torch import nn from einops import rearrange, reduce from comvex.vit import ViTBase from comvex.utils import MLP, PathDropout, PatchEmbeddingXd, ChannelFirstLayerNorm from comvex.utils.helpers import config_pop_argument from .config i...
# -*- coding: utf-8 -*- # Copyright 1996-2015 PSERC. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), K...
""" The following code contains the default functions commonly used for solar X-ray spectral fitting in the for f(*args,energies=None). Used to import `*` into fitter.py but changed as per the Zen of Python, the models here are now imported explicitly into fitter.py so **remember** to add any new models there too as w...
# # This file is part of Python Module for Cube Builder. # Copyright (C) 2019-2021 INPE. # # Cube Builder is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Create a python click context and inject it to the global flask commands."""...
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 <NAME> # Copyright (c) 2008-2020 pyglet contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020 Google 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
import hashlib import json import logging import os from mlflow.exceptions import ExecutionException from mlflow.utils import process # Environment variable indicating a path to a conda installation. MLflow will default to running # "conda" if unset MLFLOW_CONDA_HOME = "MLFLOW_CONDA_HOME" # Environment variable indi...
#!/usr/bin/env python # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
# -*- coding: utf-8 -*- import os import redis import pymongo from scrapy import Spider from datetime import datetime from scrapy.mail import MailSender from scrapy.item import Item, Field from DingTalkBot.bot import DingTalkBot from scrapy.settings import Settings, BaseSettings from scrapy_ddiy.utils.common import ge...
# Code generated by jtd-codegen for Python v0.3.1 import re from dataclasses import dataclass from datetime import datetime, timedelta, timezone from typing import Any, Dict, Optional, Union, get_args, get_origin @dataclass class Course: a_emplid: 'str' a_strm: 'str' b_catalog_nbr: 'str' b_crse_id: '...
import time, os from colorama import Fore version = 'v2.9' #color section f = Fore v = f.MAGENTA r = f.RED g = f.GREEN y = f.YELLOW c = f.CYAN b = f.BLUE def banner1(): print(r+""" ╦ ╦┬┬─┐╔═╗┌─┐┌┐┌ ╚╗╔╝│├┬┘║ ╦├┤ │││ ╚╝ ┴┴└─╚═╝└─┘┘└┘ Virus|Generator """) print(y+"By: Anikin Luke\n") print(v+"Type -h or 'h...
# Load submodules import tensorflow as tf import pandas as pd import numpy as np import regex as re from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction.text import CountVectorizer import time from tqdm import tqd...
#importing some useful packages import numpy as np import cv2 import math def grayscale(img): """ Applies the Grayscale transform This will return an image with only one color channel """ return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) def canny(img, low_threshold, high_threshold): """ Appl...
#!/usr/bin/env python # encoding: utf-8 """ @author: LiuZhi @contact: <EMAIL> @software: PyCharm @file: app.py @time: 2018-12-22 23:18 """ from flask import Flask, render_template from flask.helpers import get_debug_flag import sys import IPython from IPython.terminal.ipapp import load_default_config from traitlets....
import copy import difflib import logging import fitz from core.constants import EMPTY_TWO_COLUMN_LEFT_PDF_PATH logger = logging.getLogger(__name__) class Box(object): def __init__(self, char, page_index, left=None, bottom=None, right=None, top=None, colour=None): self.char = char self.left = l...
""" Generate a file tree table of contents for a directory of markdown files run from command line: $ python md_file_tree.py will generate a markdown index of all markdown files in the current working directory and its sub folders and insert it into a file `index.md`. If a previous index exists in the file it wi...
import os from typing import Dict, Iterable, List, Optional, Tuple import aiofiles from bs4 import BeautifulSoup from pydantic import BaseModel from omniglot.lexeme import Lexeme from omniglot.sense import Sense from omnilingual import LanguageCode, PartOfSpeech from omnilingual.features.uxy import ( XianMood, ...
""" *********** Evaluations *********** An evaluation_ object represents a collection of Synapse Entities that will be processed in a particular way. This could mean scoring Entries in a challenge or executing a processing pipeline. Imports:: from synapseclient import Evaluation, Submission, SubmissionStatus E...
import os import luigi import pickle import numpy as np from astropy.table import Table from astra.tasks.base import BaseTask from astra.utils import log from astra.tools.spectrum import Spectrum1D from astra.tools.spectrum.writers import create_astra_source from astra.tasks.io import ApStarFile from tqdm import tqdm ...
import os import pathlib import pytest import random import shutil import socket import subprocess import tempfile import threading import time from parsl.channels import LocalChannel, SSHChannel from parsl.launchers import SingleNodeLauncher from parsl.providers import LocalProvider from parsl.providers.provider_base...
import numpy as np import os import pickle import matplotlib.pyplot as plt import keras from keras.models import load_model from keras import datasets import math from PIL import Image import mnist_manifold import mnist_model import warnings warnings.filterwarnings("ignore") ''' Load MNIST model, manifold model, and...
# Copyright 2020 Huawei Technologies Co., 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 law or agreed to...
import numpy as np # linear algebra import pandas as pd from keras.models import Sequential from keras.layers import Dense, Dropout from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split ...
#!/usr/bin/env python3 import numpy as np import numpy.testing as npt from pathlib import Path import pybind_isce3 as isce import iscetest def test_default_driver(): driver = isce.io.gdal.Raster.default_driver() print(driver) # init from path # (access defaults to read-only) def test_open1(): path = Pat...
import IPython if IPython.release.version < '0.11': raise ImportError('this module requires at least v0.11 of IPython') elif IPython.release.version < '2.0': install_nbextension=None _canUse3D=False else: from IPython.html.nbextensions import install_nbextension _canUse3D=True from rdkit import Che...
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch import optim import numpy as np from utils import decode_ctc_outputs class ResBlock(nn.Module): def __init__(self,in_c,out_c,stride=1): super(ResBlock, self).__init__() self.conv1 = nn...
""" This module implements row model of PayPal CSV. see: - PayPal activity download specification https://www.paypalobjects.com/webstatic/en_US/developer/docs/pdf/PP_ActivityDownload.pdf """ from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime from enum import...
import chaospy import numpy from ..baseclass import Dist from .. import evaluation from .binary import BinaryOperator class Matmul(BinaryOperator): """Multiplication.""" matrix = True def __init__(self, left, right): """ Args: left (Dist, numpy.ndarray): Left...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Jan 8 22:09:19 2017 @author: LinZhang """ # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves impo...
import json import os import pytest import libtbx import procrunner from dxtbx.model.experiment_list import ExperimentListFactory from dxtbx.serialize import load from dials.array_family import flex from dials.algorithms.shadowing.filter import filter_shadowed_reflections from dials.util.masking import lru_equality_...
import json import os import random import time from flask import * import flask_cors import lightmysql import config app = Flask(__name__) # 初始化app对象 flask_cors.CORS(app, supports_credentials=True) app.secret_key = "<KEY>" # session的加密密钥 thisDir = os.path.dirname(__file__) # 相对目录 mysql = lightmysql.Connect(confi...
import os, math import numpy as np import flopy fm = flopy.modflow fp6 = flopy.mf6 from flopy.discretization import StructuredGrid from flopy.utils import SpatialReference as OGsr from flopy.export.shapefile_utils import shp2recarray try: import shapefile if int(shapefile.__version__.split('.')[0]) < 2: ...
# Currently depedent on Flask-Ask and python-tuya # Tested on Gentoo Linux, ebuilds for above packages available at # https://github.com/SDNick484/rectec_status/ # # This script requires the following variables which can be found # with the device discover script on above GitHub site: # GW_ID = gwID (also known as dev...
# ___________________________________________________________________________ # # EGRET: Electrical Grid Research and Engineering Tools # Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain r...
# Copyright Allen Institute for Artificial Intelligence 2017 """ ai2thor.server Handles all communication with Unity through a Flask service. Messages are sent to the controller using a pair of request/response queues. """ import ai2thor.server import json import logging import threading import os try: from queu...
''' Star Trek episodes/characters/lines database creator Coded by <NAME> Scripts found at: https://www.st-minutiae.com/resources/scripts. Files have been renamed ("tng_s01e01.txt" through "dsn_s07e25.txt"). Some formatting has been fixed in TNG scripts, DS9 scripts have a lot of errors, some of which have been accounte...
import time import unittest from threading import Thread from mock import MagicMock from hazelcast.errors import DistributedObjectDestroyedError, OperationTimeoutError from hazelcast.future import ImmediateExceptionFuture from hazelcast.proxy.cp.count_down_latch import CountDownLatch from hazelcast.util import Atomic...
import nujson as json import os from collections import Counter, OrderedDict import numpy as np from vaemof.utils import header_str PRESETS = ['vae', 'ssvae', 'mof_vae', 'mof_y', 'full'] rand_uniform10 = lambda low, high: 10 ** np.random.uniform(low, high) rand_uniform = lambda low, high: np.random.uniform(low, high)...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import curses import sys import random import copy import warnings from pycolab import ascii_art from pycolab import human_ui from pycolab import rendering from pycolab.prefab_parts import sprites as prefab_sp...
import numpy as np from skimage.color.rgb_colors import * from skimage import draw from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def angle_diff(a1, a2): a1 = a1%180 a2 = a2%180 return abs(min(a1 - a2, 180 - abs(a1 - a2))) def line_coords(img, sym, angle_bins, drange=10, arange=...
import os import glob from itertools import islice import pandas as pd import numpy as np from .base import partition def get_data_configs(): return ['IC79.2010', 'IC86.2011', 'IC86.2012', 'IC86.2013', 'IC86.2014', 'IC86.2015'] def _get_data_path_prefix(config=None): if config is None: ...
""" Saves a CSV of all plot sales to an output folder. Methodology: To reduce the amount of plots in memory at any one point, this script iterates over each district in each world independently. It first begins by getting the latest state of all plots (1,440 per district). For each individual plot, it then iterates o...
from collections import namedtuple import inspect import os.path import zlib from azure_devtools.scenario_tests import ( ReplayableTest, AzureTestError, AbstractPreparer, GeneralNameReplacer, OAuthRequestResponsesFilter, DeploymentNameReplacer, RequestUrlNormalizer, LargeRequestBodyProcessor, Re...
import numpy as np from submodules.colmap_scripts import read_write_model as rwm from submodules.colmap_scripts.database import COLMAPDatabase, blob_to_array from submodules.colmap_scripts.read_write_model import BaseImage, Camera, CAMERA_MODEL_IDS, Point3D, qvec2rotmat from sfm_helpers import SparseModel, GetInlineMat...
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """S3-Compatible object store.""" from __future__ import annotations import os import pathlib import uuid from typing import Any, Callable, Dict, Optional, Union from composer.utils.import_helpers import MissingConditionalImportError f...
# -*- coding: utf-8 -*- """ web_ui.py - Advanced Access Token Generator Plugin for Trac This module defines a Trac extension point for generating access tokens backend. See TracTracAccessTokenBackend for more details. """ import itertools from operator import itemgetter import pkg_resources import re try: impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Copyright 2018 <NAME> # #Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # #1. Redistributions of source code must retain the above copyright notice, this list of conditions and...
""" MIT License Copyright (c) 2021 Andy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribu...
import argparse import os import os.path as osp import pickle import numpy as np from pyquaternion import Quaternion from scipy.spatial.transform import Rotation as R from tqdm.auto import tqdm def cart2hom(pts_3d): n = pts_3d.shape[0] pts_3d_hom = np.hstack((pts_3d, np.ones((n, 1), dtype=np.float32))) r...
import ctypes import frida import time import struct import sys from abc import ABC import pymem.ressources.structure from exceptions import MissingKwargError from pymem import Pymem from pymem.exception import WinAPIError, ProcessNotFound from ReadWriteMemory import ReadWriteMemory from script_info import ScriptIn...
""" cam_contact.py Look for CAM expression that is over represented in larger contact. @author <NAME> @date 28 April 2019 """ import sys sys.path.append('.') sys.path.append('./volumetric_analysis') import argparse import numpy as np import matplotlib.pyplot as plt from scipy.stats import pearsonr import networkx a...
# -*- coding: utf-8 -*- from config import opt import models import dataset import torch from torch.utils.data import DataLoader import torch.optim as optim from utils import save_pr, now, eval_metric def collate_fn(batch): ''' custom for DataLoader ''' data, label = zip(*batch) return data, labe...
#**************Importing Required Libraries************* import numpy as np import pandas as pd from numpy.linalg import inv import matplotlib.pyplot as plt #*************Declare Variables************************** #Read Input File measurements = pd.read_csv('obj_pose-laser-radar-synthetic-input.txt', header=None, de...
from datetime import datetime, timedelta from collections import deque, OrderedDict from methods import sanitize from classes import Tweet class LastAuthorDict(OrderedDict): def __init__(self, *args, **kwargs): OrderedDict.__init__(self, *args, **kwargs) def delete_old_authors(self, dt): keys...
import urwid import urwid.util from .. import utils, flow VIEW_LIST = 0 VIEW_FLOW = 1 VIEW_FLOW_REQUEST = 0 VIEW_FLOW_RESPONSE = 1 def highlight_key(s, k): l = [] parts = s.split(k, 1) if parts[0]: l.append(("text", parts[0])) l.append(("key", k)) if parts[1]: l.append(("text",...
from __future__ import annotations from typing import List from actor import * import pygame from victoryScreen import victoryScreen def load_map(filename: str) -> List[List[str]]: """ Load the map data from the given filename and return as a list of lists. """ with open(filename) as f: map_d...
import numpy as np import pydensecrf.densecrf as dcrf import scipy.io as sio import scipy from scipy.misc import imresize import os from scipy.ndimage.filters import gaussian_filter def run_crf(path_soft, sxy, srgb, scomp, gauss_k, out_path='./post_processed_davis'): result_path = path_soft seq_names = os.lis...
import sys import os import argparse import collections import numpy as np import tensorflow as tf import torch import tensorflow.keras.backend as K uer_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, uer_dir) from scripts.convert_bert_from_original_tf_to_uer import tensors_to_...
# import required modules from selenium import webdriver from selenium.webdriver.chrome.options import Options import time import numpy as np import cv2 import pyautogui import dlib def Glogin(mail_address, password): # Login Page driver.get( 'https://accounts.google.com/ServiceLogin?hl=en&...
# -*- coding: utf-8 -*- import os from lxml import etree from nbformat import read, write, NO_CONVERT title_font_size = 14 item_font_size = 9 head_margin = 3 text_margin = 2 def parse_headers(filename): nb = read(filename, as_version=NO_CONVERT) headers = [] form = False for cell in filter(lambda cel...
#!/usr/bin/env python3 # Copyright 2018 by <NAME>. Licensed under the 3-clause BSD license. """ Sequential implementation of map-reduce for graph import """ from __future__ import print_function from os.path import dirname, exists, abspath import csv import time from .import_defs import cleanup_text ###############...
from manimlib.imports import * from ManimProjects.utils.Parabola import Parabola from ManimProjects.utils.geometry import * class OpenScene(Scene): def construct(self): sub1 = CText('这是一个') sub2 = CText('关于切线的性质') subs = VGroup(sub1, sub2) subs.arrange(DOWN) self.play(Write(...
################################################################################ # BSD LICENSE # # Copyright(c) 2019-2021 Intel Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # *...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 22 14:37:29 2018 @author: Brettmccausland """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import operator from operator import itemgetter, attrgetter from sklearn.preprocessing import Imputer from sk...
import numpy as np class Optimizer: # Simple optimizer class which is like torch's Optimizer def __init__(self, tensors, lr): self.lr = lr self.tensors = tensors def step(self): for t in self.tensors: t.value -= self.lr * t.grad def clear(self): for t in s...
# RT - Data Manager from __future__ import annotations from typing import ( TYPE_CHECKING, TypeVar, Literal, Union, Optional, NoReturn, Any, get_args ) from collections import defaultdict from asyncio import Event from discord.ext import commands, tasks from ujson import loads, dumps from aiomysql import Curso...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from math import ceil from typing import List from yaml import safe_load from maro.simulator.utils import random, seed from .entities import CimSyntheticDataCollection, OrderGenerateMode, Stop from .parsers import parse_global_order_proportion...
import random from typing import List, Any import numpy as np import torch import wandb import librosa import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import matplotlib.cm as cm from coreml.utils.viz import fig2im from coreml.modules.decomposition import factory as de...
# Copyright (c) Facebook, Inc. and its affiliates. import array as ar import copy from collections import OrderedDict from dataclasses import dataclass from typing import List import numpy as np import torcharrow.dtypes as dt import torcharrow.pytorch as pytorch from tabulate import tabulate from torcharrow.column_fac...
import numpy as np import operator import random # Exercise 1 - Generate words and calculate average length. def exercise_1(size): alphabet = list("qazxswedcvfrtgbnhyujmkilop ") total_length = 0 for _ in range(size): total_length += len(exercise_1_single_word(alphabet)) return tot...
# -*- coding: utf-8 -*- """ Basic graph module """ from collections import deque import heapq from .datamodel import Free, manhattan_dist __docformat__ = "restructuredtext" class NoPathException(Exception): pass class NoPositionException(Exception): pass class AdjacencyList(dict): """ Adjacency list [...
import os import pytest import trimesh import numpy as np from PIL import Image import vtk import pyvista from pyvista import _vtk def test_wrap_none(): # check against the "None" edge case assert pyvista.wrap(None) is None def test_wrap_pyvista_ndarray(sphere): pd = pyvista.wrap(sphere.points) asse...
# Authors: CommPy contributors # License: BSD 3-Clause from itertools import product from numpy import zeros, identity, arange, concatenate, log2, array, inf from numpy.random import seed from numpy.testing import run_module_suite, assert_allclose, dec, assert_raises, assert_array_equal from commpy.channels import M...
""" The main pyk toolkit. @author: <NAME>, http://mhausenblas.info/#i @since: 2015-11-27 @status: init """ import logging import requests from pyk import util class ResourceCRUDException(Exception): pass class KubeHTTPClient(object): """ Provides communication primitives for the Kubernetes API as de...