text
stringlengths
3.07k
12.6k
import cv2 from vidaug import augmentors as va import PIL from PIL import Image import math import json from pathlib import Path import os import tqdm from torchvision.transforms import CenterCrop class ToPIL(object): """ Convert everything to PIL images """ def __init__(self): pass def ...
""" Module for loading and saving files. """ import glob import json import os from typing import Any from typing import Dict from typing import List import yaml from pydantic import BaseModel __all__ = [ 'save_json', 'load_json', 'save_yaml', 'load_yaml', 'save_config', 'load', 'get_files...
import csv import sys import sprint3_getData ''' reference help: https://www.geeksforgeeks.org/python-finding-strings-with-given-substring-in-list/ ''' ''' 0 uniq_id 1 product_name 2 manufacturer 3 price 4 number_available_in_stock 5 number_of_reviews 6 number_of_answered_questions 7 average_review_rating 8 amazon_cat...
import numpy as np from collections import Counter from gensim.models import KeyedVectors from os.path import exists class VDCNNDictionary: def __init__(self, args=None): self.ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/|_#$%^&*~`+=<>()[]{}" # + space, pad, unknown token self.PAD_T...
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
import re import numpy as np def clean_text(txt): txt = txt.lower() txt = re.sub(r"i'm", "i am", txt) txt = re.sub(r"he's", "he is", txt) txt = re.sub(r"she's", "she is", txt) txt = re.sub(r"that's", "that is", txt) txt = re.sub(r"what's", "what is", txt) txt = re.sub(r"where's", "where is...
""" Library that allow facial ctrls to be matched/mirrored/baked. Original code by <NAME> (https://github.com/goujin), thanks for the contribution! todo: Use className to find sibling. """ import pymel.core as pymel from omtk.libs import libRigging def get_orig_shape(shape): return next((hist for hist in shape.li...
import os import time import math import redis from past.builtins import xrange # pylint: disable=redefined-builtin,import-modules-only from ciqueue import static class LostMaster(Exception): pass class Base(object): def __init__(self, redis, build_id): self.redis = redis self.build_id =...
#!/usr/bin/env python # Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P. # # 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...
#!/usr/bin/env python3 import click import cv2 import numpy as np import pandas as pd import torch from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from src.augmentations import valid_aug from src.model import MultiHeadNet from src.utils import HEIGHT, WIDTH, crop_resize class GraphemeDatasetTe...
import http.server import logging import socketserver import threading import time import traceback from collections import defaultdict from http import HTTPStatus from multiprocessing.connection import Connection, Listener from typing import Dict, List, Optional, Tuple, Union from numpy.lib.arraysetops import isin l...
import sqlite3, uuid, sys, logging, time, os, json, zlib, hashlib, tempfile, multiprocessing from util import mbtiles_connect, process_tile, prettify_connect_string from multiprocessing import Pool logger = logging.getLogger(__name__) def process_tiles(pool, tiles_to_process, con, count, total_tiles, start_time, pr...
import numpy as np import spacy from scipy.sparse.csr import csr_matrix from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.decomposition import LatentDirichletAllocation from keras.preprocessing.sequence import pad_sequences ...
#!/usr/bin/env python # coding: utf-8 # In[1]: # "pyclient_01.py <IPv4 or IPv6 addr> <port>" # # Simple TCP/IP Client that can be used interact with the UUT running the # Server. Once connected, the UUT sends telemetry messages to the Client at # regular intervals. # Messages are comprised of both a header and a bo...
import ipywidgets as widgets import numpy as np import plotly.graph_objects as go import pynwb import trimesh from plotly.colors import DEFAULT_PLOTLY_COLORS from .base import df_to_hover_text def make_cylinder_mesh(radius, height, sections=32, position=(0, 0, 0), direction=(1, 0, 0), **kwargs): new_normal = dir...
from azure.cosmos import CosmosClient,PartitionKey from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser import pandas as pd import datetime from api_miners import key_vault as kv """ Steps 1. Initialize the cosmos client 2. Update all videos For eac...
import h5py import numpy as np from friday_harbor.structure import Ontology import utilities import numpy.testing as nptest class LinearModel(object): def __init__(self, W, col_labels, row_labels, data_dir='.', P=[]): self.data_dir=data_dir self.W = W self.col_labels = list(col_labels) ...
"""Meta controller of epsilon-greedy's parameter using a bandit algorithm.""" from typing import Optional import numpy as np from dqn.utils import np_inverse_value_scaling, np_value_scaling def compute_beta(index: int, N: int, beta: float) -> float: """Sigmoid based on [Agent57 paper](http://arxiv.org/abs/2003....
""" @author: <NAME> @contact: <EMAIL> """ import argparse import configparser from ifpd import bioext from ifpd.scripts import arguments as ap # type: ignore from ifpd.exception import enable_rich_assert import logging import numpy as np # type: ignore import os import pandas as pd # type: ignore from rich.logging ...
import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance import AudioDetection.audioBasicIO as audioBasicIO import AudioDetection.audioTrainTest as at import AudioDetection.ShortTermFeatures as stf """ General utility functions """ def smooth_moving_avg(signal, window=11): window = i...
from retriever_base import RetrieverBase from botocore.errorfactory import ClientError import json import os import re import boto3 import pandas as pd import datetime class GoalTermDataRetriever(RetrieverBase): def __init__(self, **kwargs): super(GoalTermDataRetriever, self).__init__(**kwargs) def e...
import os import boto3 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication from tkinter import * from PIL import Image, ImageTk from tkinter import filedialog import cv2 import numpy as np import math import string import random import h...
#!/usr/bin/env python3 # # MIT License # # Copyright (c) 2022 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, ...
# coding: utf-8 """ Implements an SQL database writer and reader for storing CAN messages. .. note:: The database schema is given in the documentation of the loggers. """ from __future__ import absolute_import import sys import time import threading import logging import sqlite3 from can.listener import BufferedRe...
import enum import logging import threading import time import grpc from google.protobuf.empty_pb2 import Empty from minio import Minio from mprl.utility_services.cloud_storage import DEFAULT_LOCAL_SAVE_PATH, connect_storage_client, maybe_download_object from mprl.utility_services.payoff_table import PayoffTable, Pol...
import os import urllib import requests import ipinfo import json from flask import Flask, jsonify, make_response, request, render_template app = Flask(__name__) @app.route('/docs', methods=["GET"]) def get_docs(): return render_template('swagger.html') @app.route('/v1/get_podinfo', methods=["GET", "OPTIONS"...
import importlib try: from comet_ml import Experiment as CometExperiment from comet_ml import OfflineExperiment as CometOfflineExperiment except ImportError: # pragma: no-cover _COMET_AVAILABLE = False else: _COMET_AVAILABLE = True from utils import Timer import torch from torch import is_tensor from ...
import difflib import os import zipfile from mtl.datasets.definitions import MOD_SEMSEG, MOD_DEPTH from mtl.utils.config import EXPERIMENT_INVARIANT_KEYS def add_filetree_to_zip(zip, dir_src, filter_filename=None, filter_dirname=None): dir_src = os.path.abspath(dir_src) dir_src_name = os.path.basename(dir_sr...
import logging import urllib import time import os import json import asyncio from .base import ProviderBase, ProviderSearchResultBase, ProviderError from ..toolbox import db from ..toolbox.net import download from ..config import config __all__ = ['Provider'] log = logging.getLogger('stagehand.providers.tvmaze') ...
# Python code for implementing Information Retrieval using Boolean Query # Step-1 Importing the necessary libraries import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer, PorterStemmer from nltk.tokenize import sent_tokenize , word_tokenize import glob import re import os import numpy ...
""" GW1000 Sensor Platform """ import logging _LOGGER = logging.getLogger(__name__) _LOGGER.debug("Loading...") import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import ENTITY_ID_FORMAT, PLATFORM_SCHEMA from homeassistant.const import ( CONF_WEB...
import imp import os import shutil import sys import warnings import pytest from six import StringIO import setupmeta from setupmeta import decode from setupmeta.scm import Git TESTS = os.path.abspath(os.path.dirname(__file__)) PROJECT_DIR = os.path.dirname(TESTS) setupmeta.TESTING = True os.environ["PYTHONDONTWRI...
import functools import getpass import json import logging import os import tempfile import shlex import time import conda_pack import skein import cluster_pack from cluster_pack.skein import skein_config_builder, skein_launcher from cluster_pack import packaging import mlflow from mlflow.entities imp...
#-*- coding: utf-8 -*- import math import numpy as np import itertools import time import math from scipy import integrate import pandas as pd from STGE import STGE import argparse import skmonaco integrate_time_list = [] bd = 2 def one_mode(x,y,a=0.1,b=0.1): ans = 30*math.exp(-(a*x**2 + b*y**2)) return(ans) d...
# -*- coding: utf-8 -*- from typing import List, Tuple, Set, Dict import copy import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models from torchvision.transforms.functional import normalize LayerIndex = Tuple[int, int] """Typedef for indexing VGG19 layers. A LayerIndex (bl...
from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms.widgets import Select from django import forms # Create your models here. class Campaign(models.Model): campaign_title = models.CharField(max_length=200) start_date = models.DateTimeFie...
""" 建标库规范 selenium 自动化下载 """ from selenium import webdriver import requests import time from PIL import Image from fpdf import FPDF import os import re import win32api from win10toast import ToastNotifier """ 弹窗提示 """ def alert(msg, title): win32api.MessageBox(0, msg, title, 0x00001000) """ 图片转 PDF """ def imag...
""" <NAME> <EMAIL> 14th December 2018 updated: 19/12/2018 latest update : reduced running time from ~70 sec to ~24 sec Creating interface for searching through records """ # importing required packages import os import dash import dash_table import urllib.parse import pandas as pd from io import Strin...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities __...
import itertools import json from argparse import ArgumentParser from pathlib import Path import urllib.request from concurrent.futures import ThreadPoolExecutor def print_progress_bar(fill): fill_hashes = int(fill*20) print("\rProgress: [{:20}] {: >3}% ".format( '#'*fill_hashes, int(fill*100)), end=...
import collections import confluent_kafka import dictdiffer import functools import re import socket import time import uuid from django.conf import settings from django.core.serializers import json from django.db.models import signals from utilities.api import get_serializer_for_model def seriali...
# -*- coding: utf-8 -*- # Copyright 2020 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 o...
#!/usr/bin/env python from collections import namedtuple from datetime import datetime, timedelta from flask import Flask, request import calendar import json import numpy as np import os import pickle def get_timestamps(evts): return [c['timestamp'] for c in evts['content']] def get_bucket(dt): return dt.weekda...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch def pad_1d_unsqueeze(x, padlen): x = x + 1 # pad id = 0 xlen = x.size(0) if xlen < padlen: new_x = x.new_zeros([padlen], dtype=x.dtype) new_x[:xlen] = x x = new_x return x.unsqueeze(0) def...
r""" Reads all the frame on network. This example reads all the frames on the network and displays them. This is used to demonstrate a frame input stream session. Ensure that you have connected the selected interface to another Ethernet interface that is transmitting data. The gRPC API is built from the C A...
import argparse import numpy as np import matplotlib.pyplot as plt from texttable import Texttable # Conversion factors TO_CM = 219474.63067 TO_EV = 27.2113839 TO_BOHR = 1.88973 TO_ANGSTROM = 0.5291761 FORCE_MASS = 1822.88853 def polfit(x, y, n=6): "Fits a polynomial of order n to the set of (x [Bohr], y [Hartree...
from traits.api import Int, Float from traitsui.api import VGroup, Item from enable.api import ComponentEditor from scipy import signal import numpy as np from neurogen.util import db, dbi from cochlear import nidaqmx as ni from cochlear.calibration import GolayCalibration from cochlear.calibration.base import (Base...
#!/usr/bin/python3 import itertools import os import re _RE_INCLUDE = re.compile('#include ([<"])([^"<>]+)') _LIB_BY_HEADER = { 'curl/curl.h': 'curl', 're2/re2.h': 're2', 'sqlite3.h': 'sqlite3', } def dfs(root, get_children): todo = [root] visited = {id(root)} while todo: item = todo.pop() yiel...
""" let's do this this file is arcane. quoth the manual: The *.cei files (see Fig. 2.11) is used to set catch ceilings which are the primary means selected by the PSC to reduce stock exploitation rates. The *.cei file is used: (1) to specify fisheries with ceilings; (2) to set ceiling levels (catch levels); and (3) to...
import ctypes import os from OpenGL import GL as gl import panda3d.core as p3d from panda3d_render_pass import RenderPass import lionrender from .gpu_buffer import GpuBufferRGBA32F SHADER_DIR = os.path.join(os.path.dirname(__file__), 'shaders', '') VERTEX_STRIDE = 4 MATERIAL_STRIDE = 5 class MaterialRecord: ...
from enum import Flag, auto, Enum import time class ObjectFlags(Flag) : NOFLAG = 0 JUNK = auto() CONNECTED = auto() WIZARD = auto() DARK = auto() class ObjectTypes(Enum) : OBJECT = auto() ROOM = auto() EXIT = auto() PLAYER = auto() class AttributeFlags(Flag) : NOFLAG = 0 def dbGetOb...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 24 11:21:39 2020 @author: zhantao """ import torch import torch.nn as nn class downsampleLayer(nn.Module): ''' A downsample layer of UNet. LeakyReLU is used as the activation func. ''' def __init__(self, infeature, outfeature, ke...
import pandas as pd import numpy as np import ROOT from root_numpy import fill_hist import xgboost as xgb from sklearn.model_selection import train_test_split import glob import random import matplotlib.pyplot as plt import pickle # Overtraining def compare_train_test(clf, X_train, y_train, X_test, y_test, outpath, ...
""" Afterglow Core: source extraction job plugin """ from typing import List as TList from marshmallow.fields import Integer, List, Nested from astropy.wcs import WCS from skylib.extraction import auto_sat_level, extract_sources from ...models import Job, JobResult, SourceExtractionData from ...schemas import After...
import torch from models.faceboxes import FaceBoxes from models.reid import Baseline from layers.functions.prior_box import PriorBox from data import cfg from utils.nms_wrapper import nms from utils.box_utils import decode import numpy as np import torchvision.transforms as T import time import pymysql import logging ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (c) 2020 ASMlover. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright...
import gym import numpy as np import pytest import torch as T from gym import spaces from pearll.common.utils import ( extend_shape, filter_dataclass_by_none, filter_rewards, get_space_range, get_space_shape, set_seed, to_numpy, to_torch, ) from pearll.settings import ExplorerSettings ...
import os import glob import yaml from extract_config import get_args def extract_info_from_file(log_file): result_dict = {} result_dict["samples"] = 0 result_dict["memory"] = 0 with open(log_file, "r") as f: for line in f.readlines(): if "iteration:" in line and "time:" in line: ...
################################ ######Movie_maker############### ################################ def read_imgs( inDir ): '''Give image folder: inDir Get a pims.sequences, e.g. inDir= '/home/.../*.png' ''' from pims import ImageSequence as Images return Images( inDir ) def select_regoi...
import zipfile import os import PIL.Image from typing import List, Tuple, Dict import numpy as np from deep500.utils.download import real_download, unrar from deep500.lv2.dataset import FileListDataset from deep500.utils.onnx_interop.losses import SoftmaxCrossEntropy # Optionally import PyAV try: import av except...
""" Usage of AutoML loop, and hyperparams with sklearn models. ============================================================= This demonstrates how you can build an AutoML loop that finds the best possible sklearn classifier. It also shows you how to add hyperparams to sklearn steps using SKLearnWrapper. This example h...
import time import re import queue import networkx as nx import logging #**** imports from our codebase ***** from . import common_classes from . import useful_methods from . import psdd from .sparse_linear_algebra import main as sparse_linear_algebra_main logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelnam...
#!/usr/bin/env python ## ## depth_eval.py ## ## Usage: ## $ ./depth_eval.py depth_net_coarse.pt depth_net_fine.pt input.jpg ... ## $ ./depth_eval.py --camera depth_net_coarse.pt depth_net_fine.pt ## import os.path import logging import torch import torch.optim as optim import numpy as np from torch.utils.data i...
# coding: utf-8 # In[1]: #interface gráfica from tkinter import * from tkinter.ttk import Checkbutton from tkinter import messagebox janela = Tk() janela.title("Consumo de Energia Elétrica") janela.geometry("600x400") #labels dataInicial = Label(janela, text="Data Inicial: ", font=("Arial",12)) dataInicial.place(...
# Code taken from PointNetVLAD repo: https://github.com/mikacuy/pointnetvlad import os import pickle import numpy as np import pandas as pd from sklearn.neighbors import KDTree #####For training and test data split##### x_width = 150 y_width = 150 # For Oxford p1 = [5735712.768124, 620084.402381] p2 = [5735611.2992...
""" Computes Geodesic Gaussian Filter (GGF) for GraphMCF Input: - GraphMCF (pickle file) Output: - GGF stored in a vertex property """ __author__ = '<NAME>' # ################ Package import import sys import time import getopt from globals import * from factory import unpickle_obj from graph import...
import re import sys import json import argparse import threading from requests import get from requests.auth import HTTPBasicAuth parser = argparse.ArgumentParser() parser.add_argument('target', help='target') parser.add_argument('-o', help='output file', dest='output') parser.add_argument('-u', help='your username',...
"""A Dataflow script for creating Amazon question/answer data. For usage see README.md. """ import argparse import ast import hashlib import logging import os import uuid from functools import partial import apache_beam as beam import tensorflow as tf from apache_beam import pvalue from apache_beam.io.textio import...
"""Configuration management for RP""" import importlib import json import logging import os from typing import Dict from typing import List from typing import Optional from oidcrp.logging import configure_logging from oidcrp.util import load_yaml_config from oidcrp.util import lower_or_upper try: from secrets imp...
""" Compositional Performance Analysis Algorithms for Path Latencies | Copyright (C) 2007-2012 <NAME>, <NAME> | TU Braunschweig, Germany | All rights reserved. | See LICENSE file for copyright and license details. :Authors: - <NAME> - <NAME> Description ----------- This module contains methods for...
import os import textwrap as tw import click import pkg_resources from .__version__ import __version__ def echo_status(status, title, text, use_default_color=False): status_color = { 'Success': 'green', 'Error': 'red', 'Hint': 'yellow', } if status not in status_color.keys(): ...
import os import subprocess from airflow.exceptions import AirflowException from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator, SparkSubmitHook from typing import Optional, Any, Dict # Custom SparkSubmitHook to pass returncode to XCom if user wants to skip it class SparkSubmitHookCu...
import matplotlib.pyplot as plt import numpy as np import itertools import logging import os from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.utils.class_weight import compute_sample_weight from src.utils_io import save_plot from collections import Counter def plot_histo...
# # Copyright 2016 ENS LSCP (Author: <NAME>) # from __future__ import print_function, division import numpy as np import os from scipy.signal import convolve, argrelmax from scipy.fftpack import rfft, rfftfreq, irfft from peakdet import detect_peaks def check_valleys(x, i, threshold=1): left = True right = ...
r""" PyTorch implementation of AutoEncoders that form sparse representations. .. autosummary:: :toctree: toctree/include/ MatchingPursuit LISTA """ import math import torch import torch.nn as nn from mighty.models.autoencoder import AutoencoderOutput from sparse.nn.solver import BasisPursuitADMM __all__ ...
import pytest from newql import Field, field def _field_error(error: str, *args, error_class: type = ValueError, **kwargs): with pytest.raises(error_class) as info: field(*args, **kwargs) assert isinstance(info.value, error_class) assert str(info.value) == error def test_field_invalid(): _f...
#!/usr/bin/env python3 import os from baselines.common import tf_util as U from baselines import logger import gymfc import argparse import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import gym import math def train(num_timesteps, seed, model_path=None, env_id=None): from...
# [LICENSE] # Copyright (c) 2020, Alliance for Sustainable Energy. # All rights reserved. # # 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 # cop...
# coding: utf-8 import logging import re from collections import OrderedDict import pyzabbix from prometheus_client import CONTENT_TYPE_LATEST, REGISTRY, Counter, Gauge, CollectorRegistry from .compat import BaseHTTPRequestHandler from .prometheus import MetricFamily, generate_latest from .utils import SortedDict lo...
import inspect from typing import (Callable, cast, get_type_hints, Iterable, overload, TypeVar, Union) from .register import register from .wire import wire from .._internal.default_container import get_default_container from ..core import DEPENDENCIES_TYPE, DependencyContainer, inject from ..exceptions import Duplica...
""" This module contains code that implements API calls for OneSignal Restful API. Some important concepts: App: Represents a single App across all platforms. Players (aka devices or users): Each OneSignal app represent many users. Notification: A notification can be sent to individuals, segments and users. Two type of...
""" Project: SSITH CyberPhysical Demonstrator Name: can.py Author: <NAME> <<EMAIL>>, <NAME> <<EMAIL>> Date: 26 August 2020 CAN Packet encoder / decoder """ import abc import typing as typ import enum from abc import ABCMeta, abstractmethod from can import Message from .component import ThreadExiting, Component import ...
import os import socket import uvloop from typing import Union from pathlib import Path from functools import partial import concurrent from concurrent.futures import ProcessPoolExecutor import click uvloop.install() click.option = partial(click.option, show_default=True) logging_level = "error" def echo(text, fg...
import os from os import environ, path as osp import torch import numpy as np import imageio import json import torch.nn.functional as F import cv2 from scipy.spatial.transform import Rotation as R trans_t = lambda t : torch.Tensor([ [1,0,0,0], [0,1,0,0], [0,0,1,t], [0,0,0,1]]).float() rot_phi = lam...
"""A zero-dependency Python library for getting the Kubernetes token of a AWS EKS cluster No AWS CLI, third-party client or library (boto3, botocore, etc.) required. """ import hmac import hashlib import datetime import base64 import re from urllib.parse import quote as urlquote from urllib.parse import urlsplit from ...
import curses from typing import List, Tuple from ..widget import Widget from ..event import Event from ..style import Style class Entry(Widget): def setup(self, **context) -> 'Entry': self.canvas_content = context.pop('content', '') style: Style = context.pop('style', Style(border=[0])) ...
# -*- coding: utf-8 -*- # @Date : 2017/11/3 # @Author : hrwhisper from lightgbm import LGBMClassifier from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import cross_validate from sklearn.model_selection impor...
#!/usr/bin/env python import re import binascii import crcmod.predefined import struct #DEVICE_HID_VID = 0x04d8 #DEVICE_HID_PID = 0x0f32 DEVICE_HID_VID = 0x03eb DEVICE_HID_PID = 0x2312 KIT_VERSION = "2.0.0" KIT_APP_COMMAND_SET_TIME = 0 def kit_crc(data): """Return bytes object of the crc based on the input data...
""" Base classes for processors """ from abc import ABC, abstractmethod from stanza.pipeline.registry import NAME_TO_PROCESSOR_CLASS, PIPELINE_NAMES, PROCESSOR_VARIANTS class ProcessorRequirementsException(Exception): """ Exception indicating a processor's requirements will not be met """ def __init__(self,...
import os from abc import ABCMeta, abstractmethod from pathlib import Path from typing import Tuple import numpy as np import feather import pandas as pd from pengle.data.target import ClassificationConverter class InterfaceDataLoader(metaclass=ABCMeta): def __init__(self) -> None: pass @abstractmet...
import os import sys import math import schemasim.schemas.l0_schema_templates as st import schemasim.schemas.l1_geometric_primitives as gp import schemasim.schemas.l2_geometric_primitive_relations as gpr class PrimitiveMovement(st.RoleDefiningSchema): def __init__(self, obj=None, relatum=None): super()._...
""" XML-RPC spec generator. 2nd approach by parsing Java code only (not taking to the consideration @xmlrpc* tags) """ from typing import List, Mapping from xml.dom import minidom import os import re import argparse class APISource: def __init__(self, namespace: str, path: str): self.namespace = namespace...
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# generated by appcreator from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.mixins import UserPassesTestMixin from django.http import HttpResponseForbidden from django.utils.decorators import method_decorator fro...
#!/usr/bin/env python import numpy as np from geometry_msgs.msg import Point # , TransformStamped # from tf import transformations from niryo_one_pose_converter.file_manager import FileManager from niryo_one_msgs.msg import RobotState, RPY class Workspace(object): """ Represents a workspace that is defined...
from __future__ import print_function import httplib2 import os from apiclient import discovery import oauth2client from oauth2client import client from oauth2client import tools from apiclient.http import MediaIoBaseDownload import io import simplejson import argparse # If modifying these scopes, delete your previou...
""" Module for adjusting viewing geometry using ISIS3. This module requires that the ISIS3 executables are in your PATH. """ import numpy as np import pandas as pd import quaternion, argparse, os, subprocess """ Compute the observer position given a ground point and distance parameters ---------- ground_point : arr...
from typing import Tuple import torch import torch.distributed as dist from torch import Tensor from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from .core import ensure_divisibility def divide(numerator, denominator): ensure_divisibility(numerator, de...
import pickle import re import requests from bs4 import BeautifulSoup class Stats: def __init__(self): pass @staticmethod def get_user_data(user): pass @staticmethod def get_user_data_link(user): pass class Fortnite(Stats): @staticmethod d...
#!/usr/bin/env python3 # Written by <NAME> (<EMAIL>) on 20 Jan 2022 # A script to filter blast hits with assigned taxonomy import datetime import pandas as pd import sys import argparse import warnings # Define that warnings are not printed to console warnings.filterwarnings("ignore") # Define funtion to print date...