content
stringlengths
5
1.05M
#!/usr/bin/env python # --------------------------------------------------------------------------------------------- """ local/api.py The API for the example customer support system. Copyright (c) 2015 Kevin Cureton """ # --------------------------------------------------------------------------------------------- ...
# coding: utf-8 """ InfluxDB OSS API Service. The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://openapi-generator.tech """ from __future__ import absolute_...
"""Support for Verisure devices.""" from __future__ import annotations from contextlib import suppress import os from homeassistant.config_entries import ConfigEntry from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import Con...
from .bert import * #from .language_model import BERTLM
# pyLattice.py """ class module for the Lattice class to be used with pyNFC """ import numpy as np class Lattice(object): """ define the layout and adjacency of the LBM lattice """ def __init__(self,Nx,Ny,Nz): """ basic constructor Nx - number of lattice points in ...
import click import os.path import src.clipping import src.anki @click.command() @click.option("--clippings", default="", help="path to My Clippings.txt file") def import_clippings(clippings): if not os.path.isfile(clippings): raise click.ClickException("Clippings file not found") try: print("...
#! /usr/bin/env python3 # coding: utf-8 from __future__ import annotations import pytest from gargbot_3000 import __main__ def test_main(): with pytest.raises((SystemExit, Exception)): __main__.main()
import math from typing import List, Optional import numpy as np __all__ = ["line_length", "is_closed", "interpolate", "crop_half_plane", "crop", "reloop"] def line_length(line: np.ndarray) -> float: """Compute the length of a line.""" return float(np.sum(np.abs(np.diff(line)))) def is_closed(line: np.nda...
class Solution: res_set = set() def subsetsWithDup(self, nums): nums = sorted(nums) return self.subsetsWithDup2(nums) def subsetsWithDup2(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) == 1: return [[num...
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ # Test case ID : C15096737 # Test Case Title : Verify that a change in the default material library material i...
from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField from django.utils import timezone import os STATUS = ( (0, "Draft"), (1, "Publish"), (2, "Withdrawn"), ) RESPONSE = ( (0, "NOT ...
# Generated by Django 2.1.7 on 2019-04-01 09:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20190331_1036'), ] operations = [ migrations.AddField( model_name='pictures', name='ipAddress', ...
import sys import os if sys.version_info < (3, 8): raise ImportError("nanobind does not support Python < 3.8.") def include_dir() -> str: "Return the path to the nanobind include directory" return os.path.join(os.path.abspath(os.path.dirname(__file__)), "include") def cmake_dir() -> str: "Return the ...
from typing import Optional, Tuple, List import tensorflow as tf import numpy as np from tensorflow.keras.layers import CuDNNLSTM as LSTM from tensorflow.keras.layers import Embedding, Dropout from sacred import Ingredient from rinokeras.layers import Stack from .AbstractTapeModel import AbstractTapeModel lstm_hpar...
from flask import current_app as app from flask import send_from_directory @app.route('/') @app.route('/<path:path>') def send_file(path = ""): if("login" in path and "." in path): return send_from_directory('./hidden/', path) elif("login" in path): return send_from_directory('./hidden/', path + "/index.html") ...
''' Loads the SVHN Datasets. Note: this uses the 2011 version Paper: http://ufldl.stanford.edu/housenumbers/nips2011_housenumbers.pdf Website: http://ufldl.stanford.edu/housenumbers/ ''' import os import cv2 from scipy.io import loadmat import glob import random import numpy as np from bunch import Bu...
# Blender import system clutter import sys from pathlib import Path UTILS_PATH = Path.home() / "Documents/python_workspace/data-science-learning" SRC_PATH = UTILS_PATH / "graphics/l_systems" sys.path.append(str(UTILS_PATH)) sys.path.append(str(SRC_PATH)) import LSystem import importlib importlib.reload(LSystem) from ...
# example of usage exceptions as break point class Exitloop(Exception): pass try: while True: while True: for i in range(10): if i > 3: raise Exception print('loop3: {}'.format(i)) print('loop2') print('loop1') ex...
import functools from sentry.utils.strings import ( soft_break, soft_hyphenate, ) ZWSP = u'\u200b' # zero width space SHY = u'\u00ad' # soft hyphen def test_soft_break(): assert soft_break('com.example.package.method(argument).anotherMethod(argument)', 15) == \ ZWSP.join(['com.', 'example.', '...
#!/usr/bin/env python # encoding: utf-8 """ A Python interface to the The Echo Nest's web API. See http://developer.echonest.com/ for details. """ import os from decorators import memoized import config import util class Track(object): def __init__(self, identifier): if len(identifier)==18: s...
class DoubleNode: def __init__(self, value): self.value = value self.next = None self.previous = None class DoublyLinkedList: def __init__(self): self.head = None self.tail = None def append(self, value): if self.head == None: self.head = Dou...
""" Test 'RadioRedirect' """ from simx.base.testutil import import_assert_functions import_assert_functions(globals()) from simx.base import TossimBase from simx.base import Node from TOSSIM import Tossim _tossim = Tossim([]) tossim = None radio = None a = None b = None c = None def setUp(): global tossim, radi...
# Copyright 2020 The Bazel Authors. 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 applicable la...
import numpy as np "iterative LQR with Quadratic cost" class iterative_LQR: """ iterative LQR can be used as a controller/trajectory optimizer. Reference: Synthesis and Stabilization of Complex Behaviors through Online Trajectory Optimization https://homes.cs.washington.edu/~todorov/papers/TassaI...
from django.apps import AppConfig class PoemConfig(AppConfig): name = 'Poem.poem' verbose_name = 'POEM'
import random as ra import matplotlib.pyplot as plt import numpy as np overall_max = [] overall_prop = [] for k in range(10000): peter = [] paul = [] max_peter = 0 prop_count = 0 for i in range(40): roll = ra.random() if roll < 0.5: peter.append(-1) paul.app...
from django.db import models from django.contrib.auth.models import User class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default='') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() hp_no = ...
""" Code used by checkviewaccess management _output """ from django.conf import settings from django.contrib.auth import get_user_model from django.utils import timezone try: from django.utils.translation import gettext as _ except: from django.utils.translation import ugettext as _ from django_roles_access.mo...
# Init import os import sys import platform import json import smtplib import zipfile import shutil import logging import random import email.mime.text import email.utils import email.header import urllib.request # Init-Version version_list = json.loads(open('version.json', encoding = 'utf8').read()) print('Version...
"Exit codes we can use to describe different error conditions programatically." CONNECTION_ERROR = 1 RESOURCE_MISSING = 2
import time from pynamodb.constants import (CAMEL_COUNT, ITEMS, LAST_EVALUATED_KEY, SCANNED_COUNT, CONSUMED_CAPACITY, TOTAL, CAPACITY_UNITS) class RateLimiter(object): """ RateLimiter limits operations to a pre-set rate of units/seconds Example: Initialize a RateLi...
n = int(input()) print(n) res = (n // 50) * 7 n = n % 50 if n >= 30: res += 4 res += (res-30)//10 else: res += res//10 print(res)
import sys import csv import math from gensim.test.utils import common_texts from gensim.models.doc2vec import Doc2Vec, TaggedDocument args = sys.argv dir = args[2] vec_dir = args[3] print("Reading preprocessed test cases ...", file=sys.stderr) texts = [] with open(args[1]) as table_file: reader = csv.reader(tab...
import requests ## libreria para hacer el request a los navegadores from bs4 import BeautifulSoup ## libreria utilizada para parsear el html from flask import Flask, jsonify ## librerias de flask a utilizar import os ## libreria para el manejo de files. import sqlite3 ## app = Flask(__name__) DATABASE = '../test/d...
# Author : Relarizky # Github : https://github.com/relarizky # File Name : help/exception.py # Last Modified : 01/25/21, 11:23 PM # Copyright © Relarizky 2021 class ValueLengthError(Exception): """ raised when user input value with invalid length """ def __init__(self, message: str) -> None: ...
from setuptools import find_packages, setup setup( name='smisc', version='0.1-alpha', packages=find_packages(), author='sakurain', author_email='1457488119@qq.com', description='just utils', classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apa...
#utils.py import socket, json from data import addPoints import urllib.request from init import saveData import cfg import time, _thread def openSocket(): s = socket.socket() s.connect((cfg.HOST, cfg.PORT)) s.send(("PASS " + cfg.PASS + "\r\n").encode('utf-8')) s.send(("NICK " + cfg.NICK + "\r\n").encod...
import pipe import DynamicPassword class DiskOP: DiskArray = [] VolumeArray = [] def __init__(self,IP,Port,Password): self.p_Diskpart = pipe.RemotePipe(IP,Port,DynamicPassword.DynamicPassword(Password,8)+"diskpart.exe".encode("GB2312")) def GetDiskList(self): CMDresult = self.p_Diskpart....
#! /usr/bin/python # $Id: setup.py,v 1.3 2012/03/05 04:54:01 nanard Exp $ # # python script to build the libnatpmp module under unix # # replace libnatpmp.a by libnatpmp.so for shared library usage from distutils.core import setup, Extension from distutils import sysconfig sysconfig.get_config_vars()["OPT"] = '' syscon...
import time, os, requests, re, csv, time from lxml import etree from selenium import webdriver img_folder = 'D:\\dataset_object_detect\\open_image_dataset\\train_00\\train_00' img_files = list() for root, dirs, files in os.walk(img_folder): for name in files: file_path = os.path.join(img_folder, name) ...
from picamera import PiCamera import time import cv2 import numpy as np from config import WIDTH, HEIGHT, CHANNEL, MINIMUM_DISTANCE, CP_WIDTH, CP_HEIGHT from ultrasonic import getDistance camera = PiCamera() def getImage(): camera.resolution = (HEIGHT, WIDTH) errors = False im = np.empty(( WIDTH, HEIGHT, 3), dtype...
def list_max(input_list): max_val = input_list[0] for i in range(1, len(input_list), 1): if(input_list[i] > max_val): max_val = input_list[i] return max_val list1 = [-2, 1, 2, -10, 22, -10] max_val = list_max(list1) print(max_val)
#!/usr/bin/python """ WARNING: This is an automatically generated file. It is based on the EPW IDD specification given in the document Auxiliary EnergyPlus Programs - Extra programs for EnergyPlus, Date: November 22 2013 Do not expect that it actually works! Generation date: 2014-12-01 """ from collections import Or...
import xml.etree.ElementTree import os.path class FMI3ModelDescription: fmu_name="unknown" fmi_version="unknown" model_name="unknown" instantiation_token="{0}" fmu_var_dict=dict() def parse_model_description( self, fmu_name, fmu_path ): self.fmu_name=fmu_name # Parse and store...
"""Build and check configuration for quattor documentation.""" import os from vsc.utils import fancylogger from repo import Repo logger = fancylogger.getLogger() def build_repository_map(location): """Build a repository mapping for repository_location.""" logger.info("Building repository map in %s.", locatio...
import logging from typing import List from typing import NamedTuple from typing import Optional import phue log = logging.getLogger(__name__) #: Maximum hue light brightness MAX_BRIGHTNESS = 254 LightGroupStatus = NamedTuple('LightGroupStatus', [ ('group_id', int), ('is_on', bool), ('brightness', int)...
""" Tests for the attrdict module """
# # Copyright (c) 2019 One Identity # # 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...
# # PySNMP MIB module ADTRAN-AOS-OVER-TEMP-PROTECTION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-OVER-TEMP-PROTECTION-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:58:49 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Usi...
# Copyright (c) 2009-2014 Denis Bilenko and gevent contributors. See LICENSE for details. from __future__ import absolute_import # standard functions and classes that this module re-implements in a gevent-aware way: _implements = ['create_connection', 'socket', 'SocketType', ...
from pathlib import Path import numpy as np from scipy import ndimage from self_supervised_3d_tasks.data.generator_base import DataGeneratorBase import os class SegmentationGenerator3D(DataGeneratorBase): def __init__( self, data_path, file_list, batch_size=8, ...
from django.contrib import admin # Register your models here. from .models import CarOwner admin.site.register(CarOwner) from .models import DrivingLicense admin.site.register(DrivingLicense) from .models import Owning admin.site.register(Owning) from .models import Car admin.site.register(Car) from .models import...
import logging import plistlib from django.db import transaction from django.http import HttpResponse from django.views.generic import View from zentral.contrib.inventory.models import MetaBusinessUnit from zentral.contrib.inventory.utils import commit_machine_snapshot_and_trigger_events from zentral.contrib.mdm.events...
''' Kattis - browniepoints Annoying problem description which needs to be read closely. The line drawn passes through the point in the center of the input sequence. Time: O(n), Space: O(n) ''' class point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(" + ...
class FakeDeserializer: def __init__(self, output): self.output = output self.input = None def serialize(self, obj): return "" def deserialize(self, body): self.input = body return self.output
# -*- coding: utf-8 -*- from pkg_resources import resource_filename import pandas def load_example_data(): """ Loads example data for pyexample. Parameters ---------- None Returns ------- example : pandas.DataFrame The example data for pyexample Example ------- ...
### ----------------- IMPORTS ----------------- ### import pandas as pd import numpy as np ### ------------------------------------------- ### # Create dropdown column elements dropdown_cols = ['Source', 'Search Function'] drop_options =[{'total_channels', 'file_name', 'channel_name', 'comment_text'}, {'contains', 'st...
import os import time import logging import datetime from copy import deepcopy from smartmicro.Helper.basicThreadHelper.threadHelper import ThreadHelper class canReceive(ThreadHelper): """ This is an internal class and should not be used by the user The user should use the communicationModule...
from exatrkx.src.processing.feature_construction import FeatureStore from exatrkx.src.embedding.layerless_embedding import LayerlessEmbedding from exatrkx.src.embedding.layerless_embedding import EmbeddingInferenceCallback from exatrkx.src.filter.vanilla_filter import VanillaFilter from exatrkx.src.filter.vanilla_fil...
from .consts import FEISHU as FEISHU from .consts import ONEBOT as ONEBOT from .consts import QQGUILD as QQGUILD from .consts import TELEGRAM as TELEGRAM from .deps import AdapterName as AdapterName from .deps import EventName as EventName from .deps import ImageSegmentMethod as ImageSegmentMethod from .deps import Mes...
#!/usr/bin/env python """ Page getter for Fanfiction.net and ao3 """ import sys import argparse import logging from dyrm import ffmonthly, do_you_read_ao3 def main(): parser = argparse.ArgumentParser() parser.add_argument( "-n", "--nomonth", help="no monthly", action="...
# ==== Versions # --pre # constraints # ==== Specific files # hashes # ==== Tag stuff # --platform # --python-version # --implementation # --abi # ==== Wheels or sdists # --no-binary (all, none, package...) # --only-binary (all, none, package...) # ==== Python version # data-requires-python # Normalized project na...
# Time: O(2^n) # Space: O(1) # The gray code is a binary numeral system where two successive values differ in only one bit. # # Given a non-negative integer n representing the total number of bits in the code, # print the sequence of gray code. A gray code sequence must begin with 0. # # For example, given n = 2, ...
from typing import Dict, Optional from datasets import datasets import torch from torch.utils.data import DataLoader from catalyst.contrib import nn from catalyst.contrib.models.cv.encoders import ResnetEncoder from catalyst.data.dataset.self_supervised import SelfSupervisedDatasetWrapper def add_arguments(parser) ...
# Solution of; # Project Euler Problem 199: Iterative Circle Packing # https://projecteuler.net/problem=199 # # Three circles of equal radius are placed inside a larger circle such that # each pair of circles is tangent to one another and the inner circles do not # overlap. There are four uncovered "gaps" which are ...
class Solution: """ @param: num: a positive number @return: true if it's a palindrome or false """ def isPalindrome(self, num): # write your code here string = str(num) l = list(string) length = len(l) i = 1 while i < length / 2 + 1: if l[...
from kusto_tool.database import KustoDatabase from kusto_tool.expression import Limit, TableExpr def test_limit(): """limit prints.""" assert str(Limit(1000)) == "| limit 1000" def test_limit_tbl(): """limit works on a tbl.""" assert ( str(TableExpr("tbl", KustoDatabase("c", "db")).limit(100...
import argparse from frontend import FrontEnd def run(): f = FrontEnd() parser = argparse.ArgumentParser( prog='hoard', epilog="See '%(prog)s <command> --help' for more help on a specific command." ) sub_parsers = parser.add_subparsers(title='Commands') get_parser = sub_parsers...
# SPDX-License-Identifier: MIT import contextlib import os import pathlib import pytest package_dir = pathlib.Path(__file__).parent / 'packages' @contextlib.contextmanager def cd_package(package): cur_dir = os.getcwd() package_path = package_dir / package os.chdir(package_path) try: yield ...
""" Copyright 2013 The Trustees of Princeton University 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 applicab...
""" You can define these configurations and call using environment variable `ENVIRONMENT`. For example: `export ENVIRONMENT=ProductionConfig` """ import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) class Config(): """Base configuration with default flags""" DEBUG = False TESTING = False ...
from .enums import Reagent, Temperature def get_transcriptic_inventory(include_lowercase=True): inventory = { Reagent.dmem_fbs_ps: 'rs197gzgq2fufr', Reagent.mem: 'rs196bbjnnayuk', Reagent.methanol: 'rs196bbr78dppk', Reagent.fbs: 'rs196baqxcecxs', Reagent.pennstrep: 'rs196b...
""":mod:`MainShopInventory` -- Represents an item in a user shop .. module:: MainShopInventory :synopsis: Represents an item in a user shop .. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com> """ from neolib.item.Item import Item import logging class UserShopFrontItem(Item): """Represents an item in...
from math import prod class Package: def __init__(self, binary_input): self.bin = binary_input self.version = int(self.bin[:3], 2) self.type = int(self.bin[3:6], 2) if self.type == 4: # Literal value groups = [] index = 6 while True: ...
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from .models import Book from django.contrib.auth.models import User # Create your tests here. class ShoppingCartFeatureTests(APITestCase): book1 = Book.objects.get(id=1).__dict__ del book1['_state']...
# # Copyright (c) 2021, 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 appl...
fig = plt.figure(figsize=(3, 3)) h = Hodograph() h.plot_colormapped(u[mask], v[mask], windspeed[mask]) # Plot a line colored by wind speed h.add_grid(increment=20)
from collections import namedtuple from datetime import datetime from os import environ import asyncio import discord import re client = discord.Client() trailhead = discord.Game("%help", start=datetime(1970, 1, 1, 0, 0, 0)) Command = namedtuple("Command", ["name", "desc", "usage", "regex", "action"]) commands = {}...
import threading from django.http import HttpResponse from django.shortcuts import render, redirect from django.conf import settings from django.core.mail import EmailMessage from django.http import JsonResponse import os import subprocess from . import models from project.settings import BASE_DIR # index.html file a...
""" Task:MaxNonoverlappingSegments Find a maximal set of non-overlapping segments. Located on a line are N segments, numbered from 0 to N − 1, whose positions are given in arrays A and B. For each I (0 ≤ I < N) the position of segment I is from A[I] to B[I] (inclusive). The segments are sorted by their ends, which mea...
import numpy as np from pynwb.testing import TestCase from ndx_csd import CSD class TestCSDConstructor(TestCase): def test_constructor_1d_probe(self): """Test that the constructor for CSD sets values as expected.""" num_times = 101 num_channels = 32 data = np.random.rand(num_tim...
from setuptools import setup setup( name="pymold", version="0.1.3", description="A simple, fast template engine for Python.", long_description="https://github.com/Bogdanp/mold", packages=["mold"], install_requires=[], author="Bogdan Popa", author_email="popa.bogdanp@gmail.com", url=...
import argparse import json import os import time import requests import tqdm from pexels_api import API PEXELS_API_KEY = os.environ['PEXELS_KEY'] MAX_IMAGES_PER_QUERY = 100 RESULTS_PER_PAGE = 10 PAGE_LIMIT = MAX_IMAGES_PER_QUERY / RESULTS_PER_PAGE def get_sleep(t): def sleep(): time.sleep(t) return...
import math import unittest from xnmt.eval import metrics from xnmt import events from xnmt.utils import has_cython from xnmt.vocabs import Vocab class TestBLEU(unittest.TestCase): def setUp(self): events.clear() self.hyp = ["the taro met the hanako".split()] self.ref = ["taro met hanako".split()] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import os import time import warnings import pandas as pd import sys import numpy as np warnings.simplefilter(action='ignore', category=FutureWarning) '''this section is to label junction starts/ends as main (a.k.a. canonical) and not main''' def gene_counter(...
import os import fire from commander import CommanderImpl, Response class CLI(object): def __init__(self): self.sub_process = CommanderImpl() def CaptureProcess(self, command: str, capture_name): response: Response = self.sub_process.call(command) os.makedirs('./tests/{}'.format(ca...
"""Constants that define languages""" CZECH = 'cs' ENGLISH = 'en' FRENCH = 'fr' GERMAN = 'de' POLISH = 'pl' SPANISH = 'es'
from django.apps import AppConfig class StufbgConfig(AppConfig): name = "openpersonen.contrib.stufbg" verbose_name = "StUF-BG backend"
#!/usr/bin/env python3 from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import logging from importlib import util if util.find_spec('neo4j') is None: print('[-] Neo4j library is not installed, please execute the following before: pip3 install --upgrade neo4j') exit() from neo4j import Auth,...
from typing import Dict, List, Optional, Set, Type, TypeVar, cast from black import FileMode, format_str from blockkit.components import Component from blockkit.elements import Image, MarkdownOption, OptionGroup, PlainOption from blockkit.objects import ( Confirm, DispatchActionConfig, Filter, Markdow...
# Modules normally used #import numpy as np import cv2 # Load an image in grayscale img = cv2.imread('img_name.jpg', 0) print(type(img)) print(img.shape[0]) print(img.shape[1]) print(img.shape[2]) height, width, depth = img.shape k = cv2.waitKey(0) if k == 27: # Wait for ESC key to exit cv2.destroyAllWindow...
import os import joblib import xgboost import argparse import numpy as np import pandas as pd from azureml.core.run import Run from xgboost import XGBClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from azureml.data...
import threading from queue import Queue from spider import Spider from domain import * from general import * ALL_OF_MY_CATEGORYS = read_file('category.txt') i = read_file('category.txt')[0] PROJECT_NAME = ALL_OF_MY_CATEGORYS[0].split('\n')[0] DOMAIN_NAME = get_domain_name('https://w3techs.com/sites/') NUMBER_OF_THREA...
from timeit import default_timer as timer import logging from scipy.spatial.distance import cosine import numpy as np import json from nltk.tokenize import sent_tokenize from typing import List, Union from .objects import ( Phrase, Keyphrase, Request, GraphQueryRequest, GraphSegmentResponse, Co...
""" "id" (https://docs.python.org/3/library/functions.html#id): Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same "id()" value. CPython implementation detail: This is the...
import unittest from pyfinder import Crawler class TestCrawler(unittest.TestCase): def setUp(self): self.crawler = Crawler() self.n = 10 def test_crawl(self): self.crawler.run() @unittest.skip("Skipping test_build") def test_build_test(self): images = self.crawler.bui...
import logging log = logging.getLogger(__name__) from collections import deque, namedtuple from copy import copy from functools import partial from queue import Empty, Queue import numpy as np from scipy import signal from atom.api import (Unicode, Float, Typed, Int, Property, Enum, Bool, Calla...
from django.views.generic import list_detail from debugged.stream.models import StreamEntry def entries(request, paginate_by=10, page=None, template_name=None, extra_context=None, template_object_name='entry'): return list_detail.object_list(request, queryset=StreamEntry.objects.order_by('-pub...
from manim import * from manim_ml.image import GrayscaleImageMobject from manim_ml.neural_network.layers.parent_layers import NeuralNetworkLayer from PIL import Image class ImageLayer(NeuralNetworkLayer): """Single Image Layer for Neural Network""" def __init__(self, numpy_image, height=1.5, show_image_on_cr...
""" config tests. """ import os import sys import numpy as np import pickle import platform import pytest from unittest import mock import wandb from wandb import wandb_sdk from wandb.errors import LogMultiprocessError, UsageError from wandb.proto.wandb_internal_pb2 import RunPreemptingRecord def test_run_step_prop...