content
stringlengths
5
1.05M
# # Copyright (C) 2021 Satoru SATOH <satoru.satoh@gmail.com> # SPDX-License-Identifier: MIT # """Functions to get some meta info of the test target modules.""" import inspect import itertools import pathlib import typing from . import constants, datatypes if typing.TYPE_CHECKING: import pytest def get_name_from...
""" Tests for legend. """ import pytest from pygmt import Figure from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import GMTTempFile from pygmt.helpers.testing import check_figures_equal @pytest.mark.mpl_image_compare def test_legend_position(): """ Try positioning with each of the four legend ...
"""Test all the tools. """ from gaphas.canvas import Context from gaphas.constraint import LineConstraint from gaphas.tool import ConnectHandleTool Event = Context # Test handle connection tool glue method def test_item_and_port_glue(simple_canvas): """Test glue operation to an item and its ports. """ ...
#! /usr/bin/python3 """ This file contains GUI code for Configuring of lora home automation Developed by - SB Components http://sb-components.co.uk """ import logging import os from tkinter import font import tkinter as tk from tkinter import messagebox from tkinter import ttk import time import webbrowser os_name = ...
import os import sys from flask import Flask from flask.ext.script import Manager from flask.ext.seasurf import SeaSurf from flask_collect import Collect import gru.utils.web import gru.utils.templates import gru.utils.logs import gru.utils.fs from gru.config import settings from gru.plugins.loader.registry import Pl...
try: from collections.abc import Mapping except ImportError: from collections import Mapping from bsm.cmd import Base from bsm.cmd import CmdError class Config(Base): def execute(self, config_type='', item_list=[]): if not config_type or config_type == 'all': return self._bsm.config_al...
from .FilesFunctions import Files from .USBKey import USBKey
# Copyright 2015 - Alcatel-Lucent # # 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 wri...
import random, re, argparse parser = argparse.ArgumentParser(description='Preprocess a corpus.') parser.add_argument('--corpus_path', help='path to the corpus', type=str, required=True) parser.add_argument('--out_path', help='path to the corpus', type=str, required=True) parser.add_argument('--vocab_size', help='vocab...
from math import sqrt, floor #Da biblioteca de matemática importe sqrt e floor. num = int(input('Digite um número: ')) raiz = sqrt(num) #Calcula a raiz quadrada de num print('A raiz de {} é igual a {:.2f}'.format(num, floor(raiz)))
from django.apps import AppConfig class CrosswalkConfig(AppConfig): name = "crosswalk"
import numpy as np from .lin_solve import SpookLinSolve from .quad_program import SpookL1 import scipy.sparse as sps from .utils import laplacian_square_S, dict_innerprod import os # from .utils import phspec_preproc from pbasex import pbasex from matplotlib import pyplot as plt class PhotonFreqResVMI: """ This is ...
import os, glob, shutil from PIL import Image import numpy as np import cv2 with open('mapFromADE.txt', 'r') as f: data = f.readlines() CATE_TO_ADE = {} # label 15,36,89 maps to two ADE categories for line in data: semantic_id, ade_id = map(int, line.strip().split()) CATE_TO_ADE.setdefault(semantic_id, ...
# 2.8 多行匹配模式 import re comment = re.compile(r'/\*(.*?)\*/') text1 = '/* this is a comment */' text2 = ''' /* this is a multiline comment */ ''' print(comment.findall(text1)) print(comment.findall(text2)) comment = re.compile(r'/\*((?:.|\n)*?)\*/') print(comment.findall(text2)) comment = re.compile(r'/\*(.*?...
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or without # ...
#importing the Kratos Library from Kratos import * from KratosULFApplication import * from KratosStructuralApplication import * from KratosMeshingApplication import * #import time def AddVariables(model_part): model_part.AddNodalSolutionStepVariable(PRESSURE); model_part.AddNodalSolutionStepVariable(DISPLACEME...
import os import json import time import requests import datetime import numpy as np from PIL import Image from io import BytesIO import tensorflow as tf # azureml imports from azureml.core.model import Model def init(): global model, image_size, index, categories try: path = Model.get_model_path('se...
# # lajollaS # www.fabiocrameri.ch/colourmaps from matplotlib.colors import LinearSegmentedColormap cm_data = [[0.99983, 0.99974, 0.79991], [0.10023, 0.10091, 0.0037913], [0.86973, 0.45582, 0.31068], [0.94802, 0.76354, 0.37498], ...
from .base import BaseRunner from rlutils.replay_buffers import GAEBuffer import rlutils.infra as rl_infra class OnPolicyRunner(BaseRunner): def setup_logger(self, config, tensorboard=False): super(OnPolicyRunner, self).setup_logger(config=config, tensorboard=tensorboard) self.sampler.set_logger(s...
from os import environ as env from .utils import DOES_NOT_EXIST API_REPLAY_RETRIES = int(env.get('API_REPLAY_RETRIES', 10)) API_REPLAY_BASE = int(env.get('API_REPLAY_BASE', 2)) DEBUG = env.get('DEBUG', True) REDIS_URL = env.get('REDIS_URL', DOES_NOT_EXIST) RQ_DEFAULT_URL = env.get('RQ_DEFAULT_URL', DOES_NOT_EXIST) SE...
"""uuid format to Meeting.id Revision ID: e541ec33fc8b Revises: 8005dddb1ef3 Create Date: 2021-07-11 11:26:54.447335 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = 'e541ec33fc8b' down_revision = '8005dddb1ef3' branch_labels = None depends_on = None def upgrad...
#!/usr/bin/env python # Copyright (c) 2017, Analog Devices Inc. # All right 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 # notice,...
"""Basic key mapping. Originally written by lunixbochs, version taken from the knausj_talon repo: https://github.com/knausj85/knausj_talon/blob/d330a6eb1fbfcc13f99a732a097f220fd0c10950/code/keys.py """ from typing import Set, List from talon import Module, Context, actions from user.utils import dictify, multi_ma...
def QuestionsMarks(str): is_true = "false" for index, char in enumerate(str): if char == "?": try: if (str[index + 1] == "?") and (str[index + 2] == "?"): is_true = "true" except: pass # code goes here return...
import logging import requests from requests.exceptions import RequestException from geo_bot.models import Result, SearchArea, TelegramUser def get_count_response(chat_id): """ Количество поисковых запросов по chat_id. """ message = [] user = TelegramUser.objects.filter(user_id=chat_id).order_by...
# from gpcharts import figure # # #simple line graph, as described in the readme. # fig1 = figure() # fig1.plot([8,7,6,5,4]) # # #another line graph, but with two data types. Also adding title # fig2 = figure(title='Two lines',xlabel='Days',ylabel='Count',height=600,width=600) # xVals = ['Mon','Tues','Wed','Thurs','Fri...
import labscript_utils.h5_lock import h5py import numpy as np import labscript_utils.properties as properties from labscript_utils import dedent class NI_DAQmxParser(object): def __init__(self, path, device): self.path = path self.name = device.name self.device = device def get_trace...
import tensorflow as tf PATCH_SIZE = 96 LR_SCALE = 4 BATCH_SIZE = 16 buffer_size = 1024 patch_per_image = 128 LOG_STEP=1000 log_dir=logs\ESRGan model_type='SRGAN_MSE' FP16=False image_dtype=tf.float32 use_div2k=True use_div8k=False blur_detection=True MSE_after_bicubic=False use_noise=True progres...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.PublicMsgKeyword import PublicMsgKeyword from alipay.aop.api.domain.PublicMsgKeyword import PublicMsgKeyword class AlipayOpenPublicTemplateMessageAddModel(object): def __init...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.password_service, name="password_service"), ]
""" This file contains methods for managing files and other helper classes, like formatters. """ import glob import os import shutil import subprocess from datetime import datetime class FileOperations: """ FileOperations class is used for handling file operations """ def __init__(self): pass @...
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
# Copyright 2015 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
""" WSGI config for project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os import platform from django.core.wsgi import get_wsgi_application from django.core.mana...
# This config is mostly for testing than for demonstration import os import sys import getpass import tempfile joinpath = os.path.join #username = getpass.getuser() # portable way to get user name #tmpdir = tempfile.gettempdir() # portable way to get temp directory iswin32 = os.sep == '\\' or sys.platform ==...
"""test start module.""" from itertools import product try: # py3 from unittest import mock except ImportError: # py2 import mock import pytest M_TEXT = 'query_text' NOT_WORKING_ON_FULL_TEST = "Not working on full test." @pytest.mark.xfail(reason=NOT_WORKING_ON_FULL_TEST) def test_import(): """test i...
from cycler import cycler from matplotlib import rc_context def supermongo(): """Context manager to emulate the style of the SuperMongo plotting library. Font is still not quite there yet. Usage: x = <data> y = <other data> with supermongo(): fig, ax = plt.subplots() ax.plot(x...
import collections from functools import reduce from datetime import datetime def clean_user(user): ''' arg: user: reddit.redditor('<username>') ''' out = collections.OrderedDict() out['id'] = user.id out['name'] = user.name # out['icon_img'] = user.icon_img out['pull_ts'] = datetime.utcnow().strftime('%Y...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'crash_dbg_form.ui' # # by: pyside-uic 0.2.15 running on PySide 1.2.4 # # WARNING! All changes made in this file will be lost! from sgtk.platform.qt import QtCore, QtGui class Ui_CrashDbgForm(object): def setupUi(self, CrashDbgForm...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # addressbook # https://github.com/tgorka/addressbook # # Copyright (C) 2016 Tomasz Gorka <http://tomasz.gorka.org.pl> # import uuid import datetime from addressbook import exception, trie class AddressBook: """ Address Book structure contains groups and perso...
# -*- coding: utf-8 -*- # Copyright (c) 2007-2011 NovaReto GmbH # cklinger@novareto.de import grok import zope.component import uvcsite.plugins from ukh.adhoc.interfaces import IUKHAdHocApp from ukh.adhoc.auth import UserAuthenticatorPlugin from zope.pluggableauth import PluggableAuthentication from zope.pluggableaut...
#!/usr/bin/python txt_dir = '/home/TestData/DPI_DATA/guangzhou_LTE/DPI_test_data/2' xml_dir = '/home/ligang/xml' xml_template = '/home/test_template.xml' exclude = ['pcapstc.txt', 'badfile.txt'] #------------------------------------------------------------------------------------------ import os #find all txt files...
values = [1, 2, 3, 4, 5] # You can check the veracity of either one statement or another statement; # if either check evaluates to True, the whole expression will be True statement = 1 in values or 6 in values print(f"{statement}: either 1 or 6 is in 'values'.") # Note that you can't write something like: # sta...
from __future__ import absolute_import, division, print_function import logging import math import iotbx.phil from cctbx.array_family import flex from cctbx import miller from dials.util import Sorry from scitbx import lbfgs from dials.algorithms.scaling.scaling_library import determine_best_unit_cell from dials.uti...
##################################################### # Content-Aware Detection of Timestamp Manipulation # # IEEE Trans. on Information Forensics and Security # # R. Padilha, T. Salem, S. Workman, # # F. A. Andalo, A. Rocha, N. Jacobs # ##################################################...
#!/usr/bin/env python from __future__ import absolute_import from __future__ import print_function import unittest from .context import engines HANDLE = 'string.Template' class TestStringTemplate(unittest.TestCase): def test_valid_engine(self): self.assertIn(HANDLE, engines.engines) engine ...
"""Pytorch interface for deodr.""" __all__ = [ "ColoredTriMeshPytorch", "Scene3DPytorch", "CameraPytorch", "LaplacianRigidEnergyPytorch", "TriMeshPytorch", "MeshRGBFitterWithPose", "MeshDepthFitter", ] from .differentiable_renderer_pytorch import CameraPytorch, Scene3DPytorch from .laplac...
#This script can be used to compare results from the C implementation with results from the TVM implementation from PIL import Image from matplotlib import pyplot as plt import numpy as np import os def convertImage(img_path): resized_image = Image.open(img_path).resize((96, 96)) #plt.imshow(resized_image) ...
from abc import ABC, abstractmethod import numpy as np class Node(ABC): def __init__(self): self._has_consumers = False # Sum of partial derivatives of each consumer-gate # with respect to this node self._cumulative_consumers_grad = 0.0 def __repr__(self): return '{}({...
x= int( input('Digite um número qualquer:')) print(f'O dobro é {2 * x}, o triplo é {3 * x} e a raiz quadrada é {x ** (1/2)}.')
class VigenereCipher: def __init__(self, message, key): self.message = message self.key = key * int(len(self.message)/len(key)) + key[:len(self.message) % len(key)] self.alphabet = {chr(i): i-97 for i in range(97, 123)} def cipher_decipher(self, to_cipher, t): if to_cipher: ...
# \MODULE\------------------------------------------------------------------------- # # CONTENTS : BumbleBee # # DESCRIPTION : Nanopore Basecalling # # RESTRICTIONS : none # # REQUIRES : none # # --------------------------------------------------------------------------------- # Copyright 2021 Pay Gies...
# -*- coding:utf-8 -*- from deeptables.preprocessing.transformer import MultiLabelEncoder, MultiKBinsDiscretizer, DataFrameWrapper, \ LgbmLeavesEncoder, CategorizeEncoder
from django.utils.translation import gettext as _ class Successfull(object): pass
#!/usr/bin/env python # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
def metric(tp, tn, fp, fn): tot = tp + tn + fp + fn acc = (tp + tn)/(tp + tn + fp + fn) prec = tp / (tp + fp) rec = tp / tp + fn f1 = 2*tp/(2*tp+fp+fn) FOR = fn / (fn + tn) return acc,prec,rec,f1,FOR
import numpy as np import cv2 import copy from osgeo import gdal, osr, ogr class GeoImage(): def __init__(self, imgPath, gap=100, subsize=1024): self.imgPath = imgPath self.gap = gap self.subsize = subsize self.slide = ...
#!/usr/bin/env python """ setup.py file for SWIG example """ import os from distutils.core import setup, Extension setup (name = 'kcore', version = '0.0.1', author = "Kuzzle", description = """Kuzzle sdk""", py_modules = ["kcore"], )
# Worker: Google
def FibonacciChecker(num): # code goes here fn = fn_1 = 0 fn_2 = 1 while fn <= num: if fn == num: return "yes" fn = fn_1 + fn_2 fn_2 = fn_1 fn_1 = fn return "no" # keep this function call here print(FibonacciChecker(input()))
import dataclasses from typing import Optional from esque.io.data_types import NoData, String from esque.io.messages import Data from esque.io.serializers.base import DataSerializer, SerializerConfig @dataclasses.dataclass(frozen=True) class StringSerializerConfig(SerializerConfig): encoding: str = "UTF-8" cla...
""" Class to interface with a redash server """ import click import requests from ruamel import yaml class Redash: """ Class to upload/download queries from redash """ def __init__(self, url, api_key): self.url = url self.api_key = api_key def getMaxOfList(self, list: li...
# Inside of __init__.py from pandas_ui.funct1 import pandas_ui, get_df, get_pivotdf, get_meltdf
#!/usr/bin/python3 import glob from PIL import Image # get all the jpg files from the current folder for infile in glob.glob("*.jpg"): im = Image.open(infile) # convert to thumbnail image im.thumbnail((500, 500), Image.ANTIALIAS) # don't save if thumbnail already exists if infile[0:2] != "T_": # prefix t...
# -*- coding: utf-8 -*- """ @file @brief Creates custom classes to interpret Python expression as column operations. """ from .column_operator import ColumnOperator from .others_types import NA class ColumnGroupOperator(ColumnOperator): """ Defines an operation between two columns. """ def __init__(...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Dalton(CMakePackage): """Molecular electronic-structure program with extensive func...
import json import requests from requests.exceptions import ConnectionError from django.core.exceptions import ObjectDoesNotExist import logging from django.conf import settings from requests.auth import HTTPBasicAuth from trust_monitor_driver.informationDigest import InformationDigest, MapDigest from trust_monitor.ver...
# -*- coding: utf-8 -*- ''' Clase Honda Crea una honda que se usará para lanzarle la comida a los osos ''' from OpenGL.GL import * from OpenGL.GLU import * import math # Clase Honda # Campos: # xpos (posición en x): float # ypos (posición en y): float # zpos (posicioón en z): float # sz (factor de escala): floatv #...
import sys import textwrap from okonomiyaki.errors import OkonomiyakiError from ..misc import parse_assignments, substitute_variables, substitute_variable from ..py3compat import StringIO if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestParseAssignments(unittest.Tes...
from flask import Flask, request from flask_celery import make_celery from pymongo import MongoClient , DESCENDING , ASCENDING import json from flask_cors import CORS from send import SendUrl , mysqlread , mysqlinsert from bson.objectid import ObjectId with open('config.json') as f: config = json.load(f) app = ...
from uuid import uuid4 from django.conf import settings from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.dispatch import receiver from django.utils.crypto import get_random_string from django.utils.translation im...
import json ''' This deals with reading and validating params. ''' class InputParametersProcess: def __init__(self, input_param_file): data = json.load(open(input_param_file)) self.framework = data['framework'] self.model = data['model'] self.source_image_folder = data['source_i...
# coding: utf-8 """ Example of a « echo » websocket server by using `tornado_websocket.WebSocket`. """
from binance.client import Client import time import matplotlib from matplotlib import cm import matplotlib.pyplot as plt from binance.enums import * import save_historical_data_Roibal from BinanceKeys import BinanceKey1 api_key = BinanceKey1['api_key'] api_secret = BinanceKey1['api_secret'] client = Cl...
import numpy as np import os import gym import torch import torch.nn as nn import collections import copy import random # hype-params learn_freq = 5 #经验池攒一些经验再开启训练 buffer_size = 20000 #经验池大小 buffer_init_size = 200 #开启训练最低经验条数 batch_size = 32 #每次sample的数量 learning_rate = 0.001 #学习率 GAMMA = 0.99 # reward折扣因子 class Mode...
def string_reverse(word): if len(word) == 1: return word else: return string_reverse(word[1:]) + word[0] print(string_reverse("hello")) """ --- """ def palindromCheck(word2): if len(word2) == 1 or len(word2) == 0: return True else: return word2[0] == word2[-1] and p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import threading from uuid import uuid4 from ..utils.func import next_chunk, Static from .base import WeChatTestCase class UtilFunctoolTestCase(WeChatTestCase): def test_next_chunk(self): """测试next chunk""" data = list(next_chunk(ra...
from nose.tools import * from shared import assert_equals_json import json import terrascript import terrascript.aws.r class Test_Output(object): def test_output_classes(self): output = terrascript.Output("name") assert isinstance(output, terrascript.Block) def test_output_example1(self): ...
import logging import os from functools import lru_cache from typing import Optional from pydantic import BaseSettings log = logging.getLogger("uvicorn") class Settings(BaseSettings): environment: Optional[str] = os.environ.get("ENVIRONMENT") testing: Optional[str] = os.environ.get("TESTING") db_name: O...
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='registration/logi...
# coding:utf-8 import sys import os import inspect import ast import torch.nn as nn import DLtorch from DLtorch.utils import * class Plugins(object): def __init__(self, plugin_root: str): self.plugin_root = plugin_root for root, dirs, files in os.walk(self.plugin_root, True): ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import abc import logging from typing import Dict, Tuple import reagent.core.types as rlt import torch logger = logging.getLogger(__name__) class MapIDList(torch.nn.Module): @abc.abstractmethod def forward(self,...
import utils from tf_imports import tf, K, TensorBoard class TensorBoard2(TensorBoard): def __init__(self, writer, histogram_freq=0, batch_size=None): super().__init__( log_dir=None, histogram_freq=histogram_freq, batch_size=batch_size, write_graph=False, ...
from agents import sac_networks as networks import tensorflow as tf import tensorflow_probability as tfp from agents.bijectors import ConditionalScale, ConditionalShift import tree class SACAgent(object): ACTOR_NET_SCOPE = 'actor_net' CRITIC_NET_SCOPE = 'critic_net' VALUE_NET_SCOPE = 'value_net' TARGE...
from typing import Dict, Union from math import sqrt from spacy.tokens import Doc from .basic_stats import BasicStats from .constants import READABILITY_STATS_DESC from .extractors import SentsExtractor, WordsExtractor class ReadabilityStats(object): """ Класс для вычисления основных метрик удобочитаемости...
import os import pytest from motifscan.cli.genome import run from motifscan.cli.main import configure_parser_main from motifscan.config import Config from motifscan.genome import Genome parser = configure_parser_main() def test_cli_genome_list(tmp_dir, capsys): config_file = os.path.join(tmp_dir, "test_cli_gen...
import os import sys import click from zipfile import ZipFile, ZIP_DEFLATED import pathlib import hashlib import re from loguetools import og, xd, common from loguetools import version XD_PATCH_LENGTH = 1024 def explode(filename, match_name, match_ident, prepend_id, append_md5_4, append_version, unskip_init): "...
""" The following code is not meant to be run because there's no input. Instead, analyze it's running time in terms of Big-O. The first two lines are already analyzed for you. Do the same for all the other lines. The input of the problem is ex_list, and assume it has n elements. At the end, put the total running time o...
from flask import Flask from flask_restful import Api app = Flask(__name__) api = Api(app) from views import Orders, SingleOrder api.add_resource(Orders, '/prod') api.add_resource(SingleOrder, '/prod/<int:id>') if __name__ == '__main__': app.run(debug = True)
import os import sys import itertools sys.path.append('../common') import spacy import numpy as np from spacy.en import English import re nlp = English() def replace_tokenizer(nlp): old_tokenizer = nlp.tokenizer nlp.tokenizer = lambda string: old_tokenizer.tokens_from_list(string.split()) replace_tokenizer(nlp...
# -*- coding: utf-8 -*- # SPDX-License-Identifier: GPL-3.0-or-later from json import loads from bases.FrameworkServices.UrlService import UrlService ORDER = [ 'queries', 'queries_dropped', 'packets_dropped', 'answers', 'backend_responses', 'backend_commerrors', 'backend_errors', 'cach...
def solution(number, k): answer = [number[0]] for num in number[1: ]: while answer and answer[-1] < num and k > 0 : answer.pop() k -= 1 answer.append(num) if k != 0 : answer.pop() return ''.join(answer) answer = solution("77777", 1) print(answer) # def so...
"""This module holds all custom exception class definitions.""" from __future__ import division, absolute_import, print_function from builtins import bytes, dict, int, range, str, super # noqa class FunkyError(Exception): """Base custom exception class.""" def __init__(self, *args, **kwargs): return...
class NameTooShortError(Exception): '''Name must be more than 4 characters''' class MustContainAtSymbolError(Exception): '''Email must contain @''' pass class InvalidDomainError(Exception): '''Domain must be one of the following: .com, .bg, .org, .net''' pass def check_name(email): name_le...
from .BTS import BTS from .CA import CA from .MIG import MIG from .DMI import DMI __all__ = ['BTS', 'CA', 'MIG', 'DMI'] __version__ = '0.0.5'
import numpy as np import pandas as pd from bs4.element import NavigableString, Comment, Doctype from report_parser.src.text_class import Text def print_tag(tag): print('printing tag:', type(tag), tag.name) if type(tag) not in [NavigableString, Doctype, Comment]: for child in tag.children: ...
n = int(input()) a = input().split() d=[] #빈 리스트 for i in range(24): d.append(0) #리스트 숫자형으로 변경 for i in range(n): a[i] = int(a[i]) #a리스트 값을 d로 이동 for i in range(n): d[a[i]] += 1 for i in range(1,24): print(d[i],end=" ")
from __future__ import print_function import argparse import os import random import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim from torch.optim.lr_scheduler import StepLR import torch.utils.data import torchvision.datasets as dset import torchv...
from typing import List from uuid import UUID from fastapi import APIRouter from fastapi.param_functions import Depends from sqlalchemy.orm.session import Session from starlette.status import HTTP_201_CREATED from src.core.controller import item from src.core.helpers.database import make_session from src.core.models ...
import abc # Componente class ArchivoComponent(metaclass=abc.ABCMeta): @abc.abstractmethod def imprimeEstructura(self): pass class ArchivoComposite(ArchivoComponent): def __init__(self): self.child_directory = [] def add(self, component): self.child_directory.append(A...