text
stringlengths
3.07k
12.6k
import numpy as np from scipy.spatial.transform import Rotation def project_vertices(vertices, angles, source_origin): # rotation matrix for view M_left = Rotation.from_quat([np.sin(np.pi/4), 0, 0, np.cos(np.pi/4)]).as_dcm() view_vector = np.array([[0,0,-source_origin]]) M_bx3x3 = compute_M(idangles) ...
import numpy as np import torch import torch.nn as nn import torch.utils.data import argparse import model_unet as model import scipy.io as io import h5py from astropy.io import fits def dice_coeff(input, target): smooth = 1. iflat = input.view(-1) tflat = target.view(-1) intersection = (iflat * tflat...
from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from .. import pilot from ..context import Context from ..template.moyatemplates import MoyaTemplateEngine from ..docgen.theme import Theme from ..docgen.doc import Doc from .. import bbcode from .. imp...
from math import ceil from warnings import warn from functools import wraps import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import gradient_boosting as gb from sklearn.base import clone def _recall_bias(df, frac...
# utils.py # This are functions that are not necessarily in any subcategory import os import string import pandas as pd import numpy as np import pandas as pd from datetime import timedelta TRAIN_COLUMNS = ['Div','Date','HomeTeam','AwayTeam','FTHG','FTAG','FTR','HTHG','HTAG','HTR','Referee','HS','AS','HST','AST','HF'...
from pywingui.windows import * from pywingui.wtl import * from ctypes import c_char try: LoadLibrary("SciLexer.DLL") #except Exception, e: except:# for compatibility with Python 3 version MessageBox(0, "The Scintilla DLL could not be loaded.", "Error loading Scintilla", MB_OK | MB_ICONERROR) #~ raise e from .scint...
from helpers import sample_uniform, make_homogeneous, make_homogeneous_T import numpy as np from scipy.spatial import cKDTree as KDTree import time def icp(src, target, src_normals=None, target_normals=None, max_iterations=200, tolerance=1e-15, sampling=None, sample_size=1000, weight_type=None, outlier_rejecti...
#!/usr/bin/env python3 # @file parse_descs.py # @brief Parses course information from course descriptions pages on # http://coursecatalog.web.cmu.edu/ into a JSON file. # # Usage: python parse_descs.py [INFILE] [OUTFILE] # # INFILE: A file containing a list of links of pages to parse. # OUTF...
from __future__ import annotations import csv import json import sys from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union from dateutil.parser import parse from imctools.data.acquisition import Acquisition, AcquisitionDict from imctools.data.channel import...
from torch.utils.data import Dataset import os.path import torch import random import time from utils.upscale import Upscale from netCDF4 import Dataset as Nc4Dataset from datetime import datetime class ClimateDataset(Dataset): def __init__(self, opt, phase): self.root = opt.dataroot self.scale_fa...
#!/usr/bin/env python # coding=utf-8 import sys import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GLib, Gio, Gtk """ Application Gtk.Application 包含很多可复用的功能,这些功能都是一个程序需要的。 比如处理多个实例,d-bus激活、打开文件、命令行解析、启动/关闭、菜单管理、窗口管理等 虽然Gtk.Application能够和普通Gtk.Windows一起正常的工作,不过通常建议与Gt...
''' Based on parseExpression.py (C)opyright 2011-2012 Bernhard -HotKey- Slawik, http://www.bernhardslawik.de This is some kind of general-purpose parser. A really simple one. But I like simple things. ''' from bootstrap_lib import * from src.htk.py.lib import * from bootstrap_tokenizer import * #from bootstra...
from math import * W = 1200 H = 800 class Vec2: def __init__(self, x = 0, y = 0): self.x = x self.y = y def add(self, p): return Vec2(self.x+p.x, self.y+p.y) def sub(self, p): return Vec2(self.x-p.x, self.y-p.y) def dot(self, p): return self.x*p.x...
import bpy import io import sys import site import subprocess import importlib.util from pathlib import Path from zlib import decompress from array import array from .formats import test_formats, BIP_FORMATS, PIL_FORMATS, MAGIC_LENGTH from . import settings USER_SITE = site.getusersitepackages() if USER_SITE not in s...
import os import re import socket from threading import Thread import pytest from pyhttpd.conf import HttpdConf from pyhttpd.result import ExecResult class UDSFaker: def __init__(self, path): self._uds_path = path self._done = False def start(self): def process(self): s...
#!/usr/bin/python # -*- coding: utf8 -*- """ Name: PyFred Description: This Python class object provides several useful functions for retrieving, parsing, and formatting data to be used with Alfred 2 Workflows. Based on the PHP class Workflows by David Ferguson Author: <NAME> (@rhostettler) License: ...
#!/usr/bin/python3 # Script for adversarial training procedure # See arXiv 1611.01046 import tensorflow as tf import numpy as np import pandas as pd import time, os, sys import argparse # User-defined from network import Network from utils import Utils from data import Data from model import Model from config import...
from __future__ import annotations import collections import math import os import re from collections.abc import Iterator, Sequence from typing import NamedTuple, Optional import more_itertools Arrangement = tuple['Vec', 'Tile'] HEAD_RE = re.compile(r'Tile (?P<id>\d+):') def main(): this_dir = os.path.dirnam...
import math import numpy as np def CheckType(operation): def _operation(instance, o): assert type(o) is ComplexNumber or type(o) is float or type(o) is np.float64 or type(o) \ is int or isinstance(o, ComplexNumber), "%s is not of type \"ComplexNumber\" or \"float\" or \"int\"!" % str(o) ...
''' Example script for constructing a 3-layer deep denoising convolutional autoencoder using Keras. ''' from absl import flags import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from pyrsostf.mnist import MNIST flags.DEFINE_integer("batch_size", 100, he...
from KafNafParserPy import * from lxml import etree import sys import os def get_token_id_from_term(nafobj, termId): term = nafobj.get_term(termId) tokenId = term.get_span().get_span_ids()[0] return tokenId def create_tokens(nafobj, root): ''' Adds the tokens from NAF to CAT ''' number ...
############################################################### # ███████╗ █████╗ ████████╗██╗ ██╗██████╗ ███╗ ██╗███████╗ # ██╔════╝██╔══██╗╚══██╔══╝██║ ██║██╔══██╗████╗ ██║██╔════╝ # ███████╗███████║ ██║ ██║ ██║██████╔╝██╔██╗ ██║█████╗ # ╚════██║██╔══██║ ██║ ██║ ██║██╔══██╗██║╚██╗██║██╔══╝ # ██...
import os import pathlib import time import traceback import Ice import IceStorm from rich.console import Console, Text console = Console() Ice.loadSlice("-I ./src/ --all ./src/PoseBasedGestureRecognition.ice") import RoboCompPoseBasedGestureRecognition class NumPyData(list): def __init__(self, iterable=list()):...
# Language Model and extractive summarize # pip install bert-extractive-summarizer, torch from transformers import * from summarizer import Summarizer import torch import os from spacy.lang.en import English import time from tqdm import tqdm tqdm.pandas() class SentenceHandler(object): """ Sentence tokeniz...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/1/17 9:55 上午 # @File : login_bilibili.py # @author : Bai # @Software: PyCharm import base64 import requests from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_condit...
#write import statements for homework 6 functions from src.homework.homework6 import get_point_mutations from src.homework.homework6 import get_dna_complement from src.homework.homework6 import dna_into_rna from src.homework.homework6 import get_gc_content from src.homework.homework6 import find_motif_in_dna from...
# -*- coding: utf-8 -*- # Copyright (c) 2019-2021 <NAME>. # All rights reserved. # Licensed under BSD-3-Clause-Clear. See LICENSE file for details. from django.conf import settings from django.shortcuts import redirect, render from django.views.generic import TemplateView, View from Functie.rol import Rollen, rol_...
#!/usr/bin/env python # pylint: disable=too-many-arguments """Docker sign command line interface.""" import logging import os import sys from pathlib import Path from traceback import print_exception from typing import TypedDict import click from click.core import Context from docker_registry_client_async import ...
#! /usr/bin/env python """Performs ingestion of HST/ACS data into the ``acsql`` database and filesystem. This script is a wapper around ``acsql.ingest.ingest.py`` to ingest multiple rootnames into the system. The user may supply a list of individual rootnames to ingest, or (by default) ingest whichever rootnames exi...
#!/usr/bin/env python from __future__ import absolute_import, print_function import os.path from os.path import join from distutils.dep_util import newer import sys if sys.version_info[:2] < (2, 7) or (3, 0) <= sys.version_info[:2] < (3, 4): raise RuntimeError("Python version 2.7 or >= 3.4 required.") if sys.ver...
import torch.nn as nn import torch from selector.cls_train import train, evaluate from classification.mlp import MLP from classification.cnn import CNN from classification.resnet import ResNet from classification.mobilenetv2 import MobileNetV2 from classification.mobilenetv3 import MobileNetV3 from classifica...
import base64 import contextlib import json import logging import os import re import signal import subprocess import sys import tempfile logger = logging.getLogger(__name__) def get_allocated_port(output): """ Extract the allocated port from the output stream. """ for line in output: line =...
import sys from django.utils.timezone import now from django.template.defaultfilters import default try: from django.db import models except Exception: print("There was an error loading django modules. Do you have django installed?") sys.exit() from django.conf import settings import uuid # Instructor mo...
# Functions to load delay data produced by the raytracer import numpy as np from numpy import exp Planck_constant = 6.62606979e-34 light_speed = 299792458.0 def load_raw(fname): # Read numerical data raw_data = np.loadtxt(fname, skiprows=7) # Read metadata. Wavelength is converted from nanometers to ...
from __future__ import print_function import numpy as np from .pysir import * import os.path import shutil __all__ = ["listLinesSIR", "buildModel", "initializeSIR", "synthesizeSIR"] def listLinesSIR(): """List the lines available in SIR for synthesis """ if (not os.path.exists('LINEAS')): ...
# ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems 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.apa...
"""Traffic Light Grid example.""" from flow.controllers import GridRouter from flow.core.experiment import Experiment from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams from flow.core.params import VehicleParams from flow.core.params import TrafficLightParams from flow.core.params import SumoC...
#!/usr/bin/env python3 #################### # Import libraries # #################### import csv #import unicodecsv import os import codecs import shutil import sys import json ############# # Variables # ############# dir = os.path.dirname(__file__) jsonStr = "*json*" jsonSep = "." jsonStrLen = len(jsonStr) ######...
#!/usr/bin/env python """Advent of Code Programming Puzzles 2019 Edition - Day 10 Puzzle Solution in Python """ import argparse import logging import math import os import sys from collections import defaultdict from pathlib import Path from typing import Iterator log = logging.getLogger(__name__) # Common Metho...
import datetime from decimal import Decimal from urllib.parse import quote_plus from sqlalchemy import engine_from_config from pyramid.config import Configurator from pyramid.renderers import JSON from pyramid.authorization import ACLAuthorizationPolicy from .controllers.security import myJWTAuthenticationPolicy, Secur...
# coding=utf-8 # Copyright (c) 2015 EMC 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 # #...
# Copyright 2013 B1 Systems GmbH # # 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 ag...
import unittest import json from cornflow.tests.custom_test_case import CustomTestCase from cornflow.tests.const import SCHEMA_URL from unittest.mock import patch, Mock from cornflow_client.schema.dict_functions import gen_schema, ParameterSchema, sort_dict from cornflow_client import get_pulp_jsonschema from marshmal...
import numpy as np import pandas as pd import pytest from hypothesis import assume, given from pandas.testing import assert_frame_equal from janitor.testing_utils.strategies import ( categoricaldf_strategy, df_strategy, ) def test_case_when_1(): """Test case_when function.""" df = pd.DataFrame( ...
######################### # Star Wars Dice Roller # ######################### import gc import random from ..menus import base_menus as m # Define the dice class dice: def __init__(self, colour, name, sides, results, swpoolcount): self.colour = colour self.name = name self.sides = sides ...
# -*- coding: utf-8 -*- import numpy as np import matplotlib import matplotlib.pyplot as plt import skimage.data as data import skimage.segmentation as seg import skimage.filters as filters import skimage.draw as draw import skimage.color as color import cv2 as cv #image = cv.imread('images for adaptive threshold/211...
import util from db import db, Equipment, Ship, Stats, Resources, Remodel, Usable, RecipeResources, Expedition # from helpers import ResourceHelper data = util.load_datadump('api_start2.json') def items(): items = data["api_mst_useitem"] count = 0 for item in items: old = db.session.query(Usable)...
# Adapted from https://github.com/quick2wire/quick2wire-python-api # And packaged into an i2c only module for convinience # Warning: not part of the published Quick2Wire API. # # Converted from i2c.h and i2c-dev.h # I2C only, no SMB definitions from ctypes import c_int, c_uint16, c_ushort, c_short, c_ubyte, c_char, P...
import torch import torchvision import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt import copy import time import PIL import scipy.ndimage as nd import os MY_DIR = os.path.dirname(os.path.abspath(__file__)) transformers = {'t...
""" Formatting of UML elements like attributes, operations, stereotypes, etc. """ import io import re from functools import singledispatch from gaphor.UML import uml2 as UML @singledispatch def format(el): """ Format an UML element. """ raise NotImplementedError( "Format routine for type %s...
import gdb import gdb.printing import gdb.types def dynamic_cast(val): assert val.type.code == gdb.TYPE_CODE_REF val = val.cast(val.dynamic_type) return val def eval_on_val(val, eval_str): if val.type.code == gdb.TYPE_CODE_REF: val = val.referenced_value() address = val.address eval_...
# -*- coding: utf-8 -*- """ httperf-plot original moduleauthor:: limseok <<EMAIL>> modified by:: YukioZzz <<EMAIL>> """ import argparse import re import subprocess import time import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg class Canvas(object): def __init__(self, tit...
# -*- coding: utf-8 -*- # # Copyright 2017-2021 - Swiss Data Science Center (SDSC) # A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and # Eidgenössische Technische Hochschule Zürich (ETHZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in c...
#!/usr/bin/env python """ .. py:currentmodule:: log.su8230.exported_ras .. moduleauthor:: <NAME> <<EMAIL>> Read exported RAS data file. """ # Script information for the file. __author__ = "<NAME> (<EMAIL>)" __version__ = "0.1" __date__ = "Mar 2, 2015" __copyright__ = "Copyright (c) 2015 Hendrix Demers" __license__ = ...
import re import os import requests from bs4 import BeautifulSoup def parse_version(version): exp = '(?P<vendor>sles|rhel|centos|ubuntu|opensuse|tumbleweed)(?:(?P<major>\d{1,2})(?:(?P<sp>sp)*(?P<minor>\d+))?)?' return re.match(exp, version).groups() def parse_flavor(flavor): flavor_major = None flav...
# -*- coding: utf-8 -*- """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ### Alias : CertServer.init & Last Modded : 2022.02.24. ### Coded with Python 3.10 Grammar by IRACK000 Description : This is a generator script to generate a CertSercer-signed certificate. Reference : [CA certificate] ...
# Description # People love to see their results as they're running to their goal. # So, let's learn how to show the user the score of the game. # When the game starts, the user should enter his/her name. # After that, the program should greet the user and read a file namedrating.txt . # This is a file containing cur...
"""Semiliterate module handles document extraction from source files.""" import os import re from mkdocs import utils class LazyFile: """Create the file only if a non-empty string is written. Like a file object, but only ever creates the directory and opens the file if a non-empty string is written. ...
import re import tarfile from datetime import datetime from pathlib import Path from tempfile import TemporaryDirectory from urllib.request import urlretrieve import click import geopandas as gpd import pandas as pd import rasterio from dateutil.parser import parse from rasterio.io import MemoryFile from rasterio.wind...
from django.urls import reverse from selenium.common.exceptions import NoSuchElementException from accounts.factories import UserFactory from functional_tests.base import FunctionalTest from functional_tests.pages.matches import MatchesPage from functional_tests.pages.nav import NavPage from matches.factories import F...
""" Copyright 2018 <NAME>. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distribut...
# Copyright 2020 IBM Corporation # # 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, ...
# Virtual memory analysis scripts. # Developed 2012-2014 by <NAME>, <EMAIL> # Copyright (c) 2012-2014 <NAME> and University of Washington # Graph 500 benchmark. # # NOTE: with 4 cores, a 1 GB per-core buffer for trace events may not # be enough for g500_size=24; 1.5 GB per-core buffer does seem to # be enough. from a...
from django.http import HttpResponse from django.conf import settings from django.template import RequestContext from django.template.loader import render_to_string from django.shortcuts import redirect, render_to_response, get_object_or_404 from django.views.decorators.http import require_POST from django.contrib.auth...
''' - Convert rule to mesh (c, v, t) - Convert system to mesh (triangulation object) ''' import numpy as np import mesh.shapes as shapes from mesh import prepare_system ## Function to convert system to Triangulation def triangulate_system(*tria_generator_args, tria_generator=None, external_flow_field=None): ''' ...
import sys import argparse from pathlib import Path import time import string # digit value to wire representation digit_to_str = { 0 : 'abcefg', 1 : 'cf', 2 : 'acdeg', 3 : 'acdfg', 4 : 'bcdf', 5 : 'abdfg', ...
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.weight_norm import weight_norm import math, copy, time from torch.autograd import Variable from collections import OrderedDict import pdb from models.modules import * class DSTNet(nn.Module): def __init__(s...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from SVM import SVM np.random.seed(0) def linear_data(N): X_1_pos = np.random.rand(N) X_2_pos = X_1_pos + np.random.normal(0, 0.3, N) + 0.5 X_pos = np.array([[x_1, x_2, 1] for x_1, x_2 in zip(X_1_pos, X_2_pos)]) X_1_neg = np.random....
# Copyright 2020 University of Groningen # # 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 i...
import re from email.header import decode_header from email.parser import BytesHeaderParser from .utils import * parser = BytesHeaderParser() # Creates a header parser # BODYSTRUCTURE is a complex header containing multiple parts of informations # This function extracts the attachment part of the bodystructure def...
# -*- coding: utf-8 -*- """ Created on Wed May 29 09:52:25 2019 @author: gh2668 """ import pandas as pd import matplotlib.pyplot as plt # This import registers the 3D projection, but is otherwise unused. from mpl_toolkits.mplot3d import Axes3D from matplotlib import gridspec import seaborn as sns import numpy as np...
import logging import os import shutil import subprocess import sys import urllib.request from context import Context class Downloader: """ Abstract base class for things that can be downloaded. :return: The directory the target was installed to. """ def __init__(self, os_family, distro, instal...
import tensorflow as tf import numpy as np from sklearn.metrics import accuracy_score, mean_squared_error, roc_auc_score, confusion_matrix, precision_recall_curve, \ auc def get_record_parser(max_len, dim): def parse(example): features = tf.parse_single_example(example, ...
import operator from numpy import * import os def createDataSet(): group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) labels = ['A', 'A', 'B', 'B'] return group, labels # inX 分类的输入向量,也就是需要预测的样本,比如[1.2,1.3] # dataet 训练样本集 # labels 标签向量 def classify0(inX, dataSet, labels, k): dataSetSize = data...
# -*- coding: utf-8 -*- # pylint:disable=invalid-name """ Utilities for manipulating quaternions. """ import numpy as np def quat_conjugate(q): """ Obtains the conjugate of a quaternion. """ assert len(q) == 4 result = [q[0], -q[1], -q[2], -q[3]] return np.asarray(result) def quat_multip...
from abc import ABCMeta, abstractmethod from sklearn.exceptions import NotFittedError from sklearn.base import BaseEstimator import json import pickle import numpy as np from warnings import warn h5py_msg = 'h5py not installed, hdf5 features will not be supported.\n'\ 'Install h5py to use hdf5 features: htt...
from ecrlgcm.misc import get_logger, land_years from ecrlgcm.data import co2_series, ecc_series, obl_series from ecrlisca.experiment import Experiment import ecrlisca.environment import os import netCDF4 as nc import numpy as np import glob import xarray as xr import xesmf as xe import warnings warnings.filterwarnings...
""" MIT License Copyright (c) 2021 atlas_core 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, di...
import os import time import cv2 from PIL import Image import glob import numpy as np import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as viz_utils from distutils.version import StrictVersion # module level variables ######################...
#!/usr/bin/env python # -*- coding: utf-8 -*- from biomarker_nlp.negation_negbert import * def negation_detect(text, modelCue): """Dectect if a sentence contains any negation cues. This function predicts if a sentence contains any negation words by using a pre-trianed negation dectection model that was pre-train...
'''<NAME> - acse-nt719 Module Containing visualization functions. Requires plotly, hvplot, holoviews and panel installed. Requires notebook widgets for holoviews visualizations. Jupyter Notebook is known to work best. Functions: data_plot(df_day, df_month, df_test, x_val ,y_val, title, day='Day', month='Mo...
#!/usr/bin/env python #----------------------------------------------------------------------------- # Title : pysmurf util tools #----------------------------------------------------------------------------- # File : pysmurf/util/tools.py # Created : 2018-08-29 #------------------------------------------...
from Transactions import Transaction, Base, MyTime from sqlalchemy import Column, Integer, String, ForeignKey, create_engine, FLOAT from sqlalchemy.orm import relationship, backref from datetime import datetime class OverdrawError(Exception): pass class TransactionLimitError(Exception): pass class Transacti...
#!/usr/bin/env/ python3 import sys import time import os import pyfiglet import random from datetime import datetime # import nmap # import argparse # OS ?! # if (os.name == "posix"): # print(os.system("uname -a")) # else: # print("Unknown OS") # Use ARGPARSE for custom commands ?...
#coding:utf-8 import hotshot, hotshot.stats from os import getpid from cStringIO import StringIO import os import re import time from os.path import abspath, dirname, join from tempfile import gettempdir import sys tempdir = gettempdir() PROFILE_LOG_FILENAME_PATTERN = join(tempdir, 'profile-%s.prof') PROFILE_PICKLE_F...
from panda3d.core import * import numpy as np from Geometry import normalizer def TupleSum(args): # used in ''' concatenates tuples inside lists ''' assert type(args) == list # just in case u were still wondering S=() for x in args: S+=x return S class RectangleSurface: def __...
import os import numpy as np import matplotlib.pyplot as plt import cv2 import mrcnn.config import mrcnn.utils from mrcnn.model import MaskRCNN from pathlib import Path from matplotlib import pyplot as plt from matplotlib import patches import random import colorsys # Configuration that will be used by the Mask-RCNN ...
from twisted.words.protocols import irc from twisted.internet import reactor, protocol, defer from re import search, IGNORECASE from random import ( choice, randint ) import random import time import os serv_ip = "coop.test.adtran.com" serv_port = 6667 clas...
# # This file is part of ravstack. Ravstack is free software available under # the terms of the MIT license. See the file "LICENSE" that was provided # together with this source file for the licensing terms. # # Copyright (c) 2015 the ravstack authors. See the file "AUTHORS" for a # complete list. from __future__ impo...
import speech_recognition as sr from time import ctime import time import threading import cv2 import sys import logging as log import datetime as dt import os import pyjokes import wikipedia import requests from pygame import mixer from gtts import gTTS mixer.init() os.system("jack_control start") os.system("arecord ...
import re import datetime from pyparsing import oneOf, Regex, QuotedString, Literal, delimitedList, Optional """ query :- action + collection + "where" + filter_clauses + compact_clauses action :- "select" collection :- ("\"" + [a-zA-Z0-9_\.]+ + "\"") OR ("\'" + [a-zA-Z0-9_\.]+ + "\'") filter_clauses :- single_fil...
import numpy as np import torch from torch.optim import Adam from torch.utils.data import DataLoader from tqdm import tqdm import torch.nn as nn class Encoder(nn.Module): def __init__(self, in_dim, hidden_layers, latent_dim, device): super(Encoder, self).__init__() shape_layers = [in_dim] + hidden...
import typing as tp from pathlib import Path import dataclasses import collections import itertools import pickle import logging import cv2 import imutils import numpy as np import shapely.geometry import matplotlib.pyplot as plt from .line import Line from .colors import Colors from .image_utils import get_image...
import re, torch, json, os from common.vocab import VocabEntry from collections import defaultdict number_of_surf_tokens = 0; number_of_surf_unks = 0 number_of_tense_tokens = 0; number_of_tense_unks = 0 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def read_trndata_makevocab(args, surf_voc...
import datetime from core.forms import ServiceRatingForm from core.models import EvictionNotice, MoveOutNotice, ServiceRating from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required, user_passes_test from django.http import HttpRespon...
__all__ = ['ChannelLogger'] import asyncio from typing import Optional, Union from pyrogram.errors import ChatWriteForbidden from pyrogram.types import Message as RawMessage from pyrogram.errors.exceptions import MessageTooLong from Ubot import config from Ubot.utils import SafeDict, get_file_id_of_media, parse_butt...
import random from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.http import HttpResponseForbidden from django.db.models import Q, Prefetch, Case, When, Value, BooleanField from django.shortcuts import get_object_or_404 from django.template.response import TemplateRe...
from __future__ import print_function, unicode_literals import click import winrm from pyinfra import logger from pyinfra.api import Config from pyinfra.api.exceptions import ConnectError, PyinfraError from pyinfra.api.util import memoize from .util import make_win_command def _raise_connect_error(host, message, d...
''' SPC's module with visualization utils. ''' def format_plus_minus_error(value, error, format_value='.1f', format_error='.1f'): ''' Takes in two iterables of floats and combines them to form a value+-error Parameters ---------- value: iterable of floats containing the values. error: it...