content
stringlengths
5
1.05M
import os import sys import argparse import numpy as np from PIL import Image import signal import time signal.signal(signal.SIGINT, signal.SIG_DFL) import OpenGL.GL as gl from glfwBackend import glfwApp import imgui from imgui.integrations.glfw import GlfwRenderer # Local imports from fieldanimation import FieldAnim...
from bs4 import BeautifulSoup html = '<div><p>Testing</p></div><div class="feedflare"><p>Feedflare</p></div>' soup = BeautifulSoup(html, 'html.parser') print(type(soup)) print(isinstance(soup, BeautifulSoup)) for div in soup.findAll('div', 'feedflare'): div.decompose() print(str(soup))
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import pytest from pants.backend.go.target_types import GoModule, GoPackage from pants.backend.go.util_rules import external_module, sdk from pants.backend.go.util_rules.external_module i...
import torch import torchvision.transforms as transforms import random import numpy as np __imagenet_stats = {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]} __imagenet_pca = { 'eigval': torch.Tensor([0.2175, 0.0188, 0.0045]), 'eigvec': torch.Tensor([ [-0.5675, 0.7192,...
import numpy as np import pandas as pd from process_tweets import * from matplotlib import pyplot as plt import nltk from collections import defaultdict import re from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer, HashingVectorizer, CountVectorizer, TfidfTransformer from skle...
""" Compiled SQL function objects. """ from contextlib import contextmanager import sqlalchemy from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import BindParameter import threading _locals = threading.local() @contextmanager def _compile_context(multiparams, params): _locals.compile_...
# 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 # distributed under t...
import asyncio import json import os import re from inspect import isawaitable from sanic import Blueprint from config import Config from framework.ws import RedisChannelWebsocket from utils import to_str, to_bytes ws_bp = Blueprint('ws', url_prefix='/ws') class WebsocketHandler(RedisChannelWebsocket): async de...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-07-03 07:47 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('driver...
import json from pathlib import Path from unittest.mock import ANY, Mock, call, patch import pytest import tornado from jupyterlab_git.git import Git from jupyterlab_git.handlers import ( GitAllHistoryHandler, GitBranchHandler, GitLogHandler, GitPushHandler, GitUpstreamHandler, setup_handlers, ...
import os datasets = [ 'iris', 'heart', 'arrhythmia', #'abalone', 'wine', 'segment', #'sensorless_drive', ] #model = ['jehmo', ] mix = ['none', 'random'] for i_mix in mix: for i_d in datasets: print('Current M...
from pomdpy.pomdp import HistoricalData from .util import INDEX_TO_ACTION class Belief(): def __init__(self, p_green=float(1/3), p_yellow=float(1/3), p_red=float(1/3), belief_d=None, confidence_d = None): self.green = p_green self.yellow = p_yellow self.red = p_red self.dist = beli...
""" (c) 2020 Spencer Rose, MIT Licence Python Landscape Classification Tool (PyLC) Reference: An evaluation of deep learning semantic segmentation for land cover classification of oblique ground-based photography, MSc. Thesis 2020. <http://hdl.handle.net/1828/12156> Spencer Rose <spencerrose@uvic.ca>, June 2020 Uni...
# # Copyright SAS Institute # # 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...
''' simple RPC over HTTP ''' import threading import json import socket try: from BaseHTTPServer import BaseHTTPRequestHandler from SocketServer import TCPServer except: from http.server import BaseHTTPRequestHandler from socketserver import TCPServer class Client: def __init__(...
# -*- coding: utf-8 -*- import os import logging import httplib2 from gtd_tasks import tasks_datamodel from gtd_tasks import visitors from gtd_tasks.gtd_model import Recipient from apiclient.discovery import build from django import forms from django.contrib.auth.decorators import login_required from django.core.ur...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: José Sánchez-Gallego (gallegoj@uw.edu) # @Date: 2020-07-15 # @Filename: calibration.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) from __future__ import annotations import asyncio import struct from typing import Dict, List, T...
# coding: utf-8 """ @brief test log(time=1s) """ import unittest import pandas import numpy from scipy.sparse.linalg import lsqr as sparse_lsqr from pyquickhelper.pycode import ExtTestCase, ignore_warnings from pandas_streaming.df import pandas_groupby_nan, numpy_types class TestPandasHelper(ExtTestCase): d...
#!/usr/bin/env python """ @package mi.dataset.driver.adcpa_n @file mi/dataset/driver/adcpa_n/auv/adcpa_n_recovered_driver.py @author Jeff Roy @brief Driver for the adcpa_n instrument Release notes: Initial Release """ from mi.dataset.dataset_driver import SimpleDatasetDriver from mi.dataset.parser.adcp_pd0 import A...
# -*- coding: utf-8 -*- # File: layer_norm.py from ..compat import tfv1 as tf # this should be avoided first in model code from ..utils.argtools import get_data_format from ..utils.develop import log_deprecated from .common import VariableHolder, layer_register from .tflayer import convert_to_tflayer_args __all__ ...
from micropython import const import ntptime import ubinascii import uhashlib import uos import ure import utime import uuurequests import config IRQ_SCAN_RESULT = const(5) IRQ_SCAN_DONE = const(6) EPOCH_OFFSET = const(946681200) # seconds between 1970 and 2000 ONBOARD_LED = const(2) __DEPOT_SSIDS = set() __DEPO...
import ctypes import logging logger = logging.getLogger("elasticapm.utils") class TraceParent(object): __slots__ = ("version", "trace_id", "span_id", "trace_options") def __init__(self, version, trace_id, span_id, trace_options): self.version = version self.trace_id = trace_id self.s...
from lpdm_missing_power_source_manager import LpdmMissingPowerSourceManager from lpdm_battery_discharge_while_charging import LpdmBatteryDischargeWhileCharging from lpdm_battery_not_discharging import LpdmBatteryNotDischarging from lpdm_battery_already_discharging import LpdmBatteryAlreadyDischarging from lpdm_battery_...
from typing import TYPE_CHECKING, List if TYPE_CHECKING: from Platforms.Web.main_web import PhaazebotWeb import json from aiohttp.web import Response, Request from Utils.Classes.storagetransformer import StorageTransformer from Utils.Classes.webrequestcontent import WebRequestContent from Utils.Classes.webrole import...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== from .. import cntk_py from ..tensor import ArrayMixin from ..utils import typemap...
#!/usr/local/bin/python2.7 import os, ConfigParser, inspect, hashlib, json class TweetBotConfig(object): ''' TweetBotConfig cls ''' def __init__(self,cfgFile='config'): # Bool initializer str_to_bool = lambda x : x.strip()=='True' path = os.path.dirname(os.path.abspath(inspe...
import torch from irislandmarks import IrisLandmarks gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net = IrisLandmarks().to(gpu) net.load_weights("irislandmarks.pth") ############################################################################## batch_size = 1 height = 64 width = 64 x = torch....
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('lcurves', '0035_auto_20150430_1553'), ] operations = [ migrations.AlterField( model_name='lightcurve', ...
from questlog import QuestLog class Category(): '''A category is a subfolder of a QuestLog and contains itself another QuestLog''' def __init__(self, title, ql_title, ql_parent, ql_desc=''): self.title = title self.questlog = QuestLog(ql_title, desc=ql_desc) self.ql_parent = ql_parent ...
import urllib.parse import json import datetime import requests from pgsheets.exceptions import _check_status class Client(): """Represent an application's Google's client data, along with methods for getting a refresh token. A refresh token is required to intialize a Token object. """ def __i...
from django.contrib import admin from .models import * models = [ Post, Comment, Heart, ] admin.site.register(models)
# coding: utf-8 from django.core.management.base import NoArgsCommand from django.conf import settings from wagtail.wagtailcore.models import Page class Command(NoArgsCommand): def set_subtree(self, root, root_path, lang=None): update_fields = ['url_path_'+lang] if hasattr(root.specific, 'url_path_'+lan...
from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import redirect from django.views import View from church_site.views import AdminListView, BaseDetailView from contactus.models import ContactMessage class AdminContactMessageListView(PermissionRequiredMixin, AdminListView): pe...
# https://gist.github.com/omz/6762c1e55e8c3a596637 # coding: utf-8 #!python2 ''' NOTE: This requires the latest beta of Pythonista 1.6 (build 160022) Demo of using Pythonista's own internals to implement an editor view with syntax highlighting (basically the exact same view Pythonista uses itself) IMPORTANT: This is...
import os import random from typing import Any, Dict, List, Text import structlog from aiohttp import ClientSession from rasa_sdk import Action, Tracker from rasa_sdk.events import ActionExecuted, BotUttered, EventType, SlotSet, UserUttered from rasa_sdk.executor import CollectingDispatcher from rasa_sdk.forms import ...
Profile {'000001.SZ': {'address1': 'No. 5047, Shennan East Road', 'address2': 'Luohu District', 'city': 'Shenzhen', 'zip': '518001', 'country': 'China', 'phone': '86 21 3882 4910', 'website': 'http://www.bank.pingan.com', 'industry': 'Banks—Regional', 'sector': 'Financial Services', 'longBusinessSummary': "Ping An Bank...
from django.db import models import datetime as dt from django.db.models import Q class Editor(models.Model): first_name = models.CharField(max_length =30) last_name = models.CharField(max_length =30) email = models.EmailField() phone_number = models.CharField(max_length = 10,blank =True) def __st...
import time from vibora import Vibora from vibora.responses import Response from vibora.utils import Timeouts app = Vibora() @app.route('/') def home(): time.sleep(10) return Response(b'123') if __name__ == '__main__': app.run(debug=False, port=8000, host='0.0.0.0', workers=1, timeouts=Timeouts( ...
default_app_config = "mytemplatetags.apps.myTemplateTagsConfig"
from colossalai.context import ParallelMode from colossalai.nn.layer import WrappedDropout as Dropout def moe_sa_args(d_model: int, n_heads: int, d_kv: int, attention_drop: float = 0, drop_rate: float = 0, bias: bool = True): ...
# -*- coding: utf-8 -*- import lemoncheesecake.api as lcc from lemoncheesecake.matching import check_that, equal_to, require_that, is_true, is_false from common.base_test import BaseTest SUITE = { "description": "Method 'call_contract_no_changing_state'" } @lcc.prop("main", "type") @lcc.prop("positive", "type")...
# -*- coding: utf-8 -*- # # Copyright (C) 2019 CESNET. # # invenio-oarepo-ui is free software; you can redistribute it and/or modify it under # the terms of the MIT License; see LICENSE file for more details. """Version information for invenio-oarepo-ui. This file is imported by ``invenio_oarepo_ui.__init__``, and pa...
import time import json import re from django.db import models from django_extensions.db.models import TimeStampedModel from url_store.models import URL from .api_base import api class TwitterUser(TimeStampedModel): username = models.CharField(blank=True, max_length=100, primary_key=True) source = models.Ch...
# This code is based on and adapted from https://github.com/Qiskit/qiskit-qcgpu-provider/blob/master/qiskit_qcgpu_provider/qasm_simulator.py # and https://github.com/qulacs/cirq-qulacs/blob/master/cirqqulacs/qulacs_simulator.py # # Adapted by Daniel Strano. # Many thanks to the qulacs team for providing an open source ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_mysql_query_tool are the test associated with the mysql_query_tool copyright: 2015, (c) sproutsocial.com author: Nicholas Flink <nicholas@sproutsocial.com> """ import logging import mock import mysql_query_tool import unittest logging.basicConfig(level=loggin...
#!/usr/bin/env python """Module for calculating sine and cosine function solely using parametrization of unit circle by arc-length; i.e. no power series, no circular definitions in terms of complex exponentials, and no right triangles. Caleb Levy, March 2015. """ import numpy as np import matplotlib.pyplot as plt ...
# Generated by Django 2.2 on 2021-05-27 06:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_pdf_bundels'), ] operations = [ migrations.RemoveField( model_name='file', name='pdf_path', ), ]
# Section 12.3.1 snippets # Loading the Data from pathlib import Path from textblob import TextBlob blob = TextBlob(Path('RomeoAndJuliet.txt').read_text()) from nltk.corpus import stopwords stop_words = stopwords.words('english') # Getting the Word Frequencies items = blob.word_counts.items() # Eliminating the S...
# ######################################################################################## # Subdomain Frequency Data Processing # We copied the table of data available here: # bitquark_20160227_subdomains_popular_1000_with_count.txt # Downloaded from # https://github.com/bitquark/dnspop/blob/master/results/bitquark_20...
"""Matcher object.""" # This file is part of the 'xarray-regex' project # (http://github.com/Descanonge/xarray-regex) and subject # to the MIT License as defined in the file 'LICENSE', # at the root of this project. © 2021 Clément Haëck import re class Matcher(): """Manage a matcher inside the pre-regex. P...
from django.test import TestCase from django.utils import timezone from django.contrib.auth.models import User from django.shortcuts import reverse from django.db.models import Q from web.models import Event from datetime import timedelta from bs4 import BeautifulSoup class EventViewTest(TestCase): @staticmethod...
from CommonCode.convertPbToJSON import ConvertPbToJSON from CommonCode.strings import Strings from Enums.databaseTables import Tables from protobuff.workertype_pb2 import WorkerTypeEnum class DatabaseHelper: m_pbConvertor = ConvertPbToJSON() BASE_QUERY = "SELECT * FROM" BASE_UPDATE_QUERY = "UPDATE" BA...
from distutils.util import strtobool def boolean_argument(value): """Convert a string value to boolean.""" return bool(strtobool(value))
__version__ = "0.0.3dev0" from . import dhn_from_osm # noqa: F401 from . import graph # noqa: F401 from . import helpers # noqa: F401 from . import input_output # noqa: F401 from . import model # noqa: F401 from . import network # noqa: F401 from . import plotting # noqa: F401 from . import simulation # noqa: ...
from PyQt5.QtWidgets import QWidget, QGridLayout, QLineEdit, \ QMessageBox, QSpinBox, QHBoxLayout, QPushButton, QDialog, QSplitter, \ QVBoxLayout, QLabel, QTextEdit, QSizePolicy from PyQt5.QtGui import QFontMetrics, QIcon from PyQt5.QtCore import Qt from app.resources.resources import RESOURCES from app.data.d...
import threading import socket #define host address, port number host = '127.0.0.1' #localhost (can also be the ip of the server if it's running on web server) port = 49800 #random port - not from well-known ports (0-1023) or registered ports (1024-49151) #starting the server server = socket.socket(socket.AF_...
from __future__ import absolute_import, division, print_function from ete3 import Tree import sys #read in a rooted treelist, print out a .trees file that RootAnnotator might (?) like trees = [] inh = open(sys.argv[1]) for line in inh: ct = Tree(line.rstrip()) trees.append(ct) inh.close() leaf_names = []...
# coding: utf-8 """ OrganizationAuthorizationApi.py Copyright 2016 SmartBear Software 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 ...
#! import jax.numpy as np from jax import jit, random, vmap from jax.ops import index_add, index_update, index import matplotlib.pyplot as plt import functools import itertools from scipy import optimize from scipy.special import gamma from tqdm import tqdm import numpy as np2 import pandas as pd import pickle import o...
from collections import Counter import json import re from bs4 import BeautifulSoup as Soup import time print 'using new' class AnnotatedTextException(Exception): pass class AnnotatedText(object): MATCH_TAG = re.compile(r'^\((\S+)\s*') MATCH_END_BRACKET = re.compile(r'\s*\)\s*$') MATCH_TEXT_ONLY = re.compile(r'^[...
import os from pydub import AudioSegment path = os.getcwd() print(path) # In Windows this is the root path is different: We will change it to the right path os.chdir("C:\\Users\\s157874\\Documents\\GitHub\\wavegan\\data\\dir_long_audio_files\\houspa") path = os.getcwd() audio_files = os.listdir() print(audio_files...
import pandas as pd from autoscalingsim.deltarepr.node_group_delta import NodeGroupDelta from autoscalingsim.utils.error_check import ErrorChecker from .platform_scaling_info import PlatformScalingInfo class PlatformScalingModel: def __init__(self, simulation_step : pd.Timedelta): self.platform_scaling...
''' These are tests to assist with creating :class:`.LinearOperator`. ''' import numpy as np from numpy.testing import assert_allclose def adjointTest(O, rtol=1e-7): ''' Test for verifying forward and adjoint functions in LinearOperator. adjointTest verifies correctness for the forward and adjoint functions ...
import base64 import hashlib # Imports required by the __main__ case below import sys def cqlDigestGenerator(schemaPath): buff = "" with open(schemaPath) as schema: for line in schema: realLine = line.strip() if len(realLine) == 0 or realLine.isspace(): continue...
################################################################################ ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2.1 of the License, or (at your op...
# # The MIT License (MIT) # # This file is part of RLScore # # Copyright (c) 2008 - 2016 Tapio Pahikkala, Antti Airola # # 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, ...
############################## # spider for school of business # filename:spider_bs.py # author: liwei # StuID: 1711350 # date: 2019.12.1 ############################## import scrapy import os from teacherInfo.items import TeacherinfoItem import re snapshots_path = '../query_system/templates/snapshots' ...
import multiprocessing from mrhttp import Application from mrhttp import Request import mrhttp import socket import mrjson as json import asyncpg import weakref import random from jinja2 import Template from nats.aio.client import Client as NATS from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers...
# 定义类属性 class Dog(object): tooth = 30 # 创建对象 wangcai = Dog() xiaohei = Dog() # 用类和对象调用类属性 print(Dog.tooth) print(wangcai.tooth) print(xiaohei.tooth)
from datetime import datetime from rest_framework import serializers from mangacache.models import Chapter, Manga, Author class MangaDetailSerializer(serializers.Serializer): name = serializers.CharField(required=True, allow_blank=False, max_length=255) url = serializers.URLField() description = seriali...
from typing import Dict, Any, Tuple from datetime import datetime import re def checkName(name: str) -> bool: """ Checks if a string is a valid name Only spaces and alphabets allowed Parameters ---------- name: str The name to be Tested Returns ------- bool True/F...
import json import pandas from django.contrib.auth.decorators import login_required, user_passes_test from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from utils.tweepy.helpers import TweePy @login_required(login_url='/signin') def home(request): return render(reque...
from time import sleep, time from random import randint import os import sys _path = os.path.abspath(os.path.join(os.path.abspath(__file__), "../../"))+"/schema" sys.path.append(_path) from brain.queries.writes import transition_expired CHECKING_PERIOD = 3 # seconds if __name__ == "__main__": while True: ...
from django.db import models import base64 import numpy import pickle import datetime from django.db.models import Q, Max, Min import matplotlib.pyplot as plt import filename_database.models from io import BytesIO from Key import Key import plot_constants CHARGE = 'chg' DISCHARGE = 'dchg' POLARITIES = [(CHARGE, 'CHAR...
#!/usr/bin/python import sys import os import re import codecs import operator import datetime import nltk import warnings from unidecode import unidecode def usage(): print ''' tokenize a directory of text and count unigrams. usage: %s input_dir ../data/english_wikipedia.txt input_dir is the root directory wh...
_base_ = './retinanet_r50_fpn_1x_bdd100k.py' model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
"""Tests for inmcm4 fixes.""" import unittest from iris.cube import Cube from cf_units import Unit from esmvalcore.cmor.fix import Fix from esmvalcore.cmor._fixes.cmip5.inmcm4 import Gpp, Lai, Nbp class TestGpp(unittest.TestCase): """Test gpp fixes.""" def setUp(self): """Prepare tests.""" ...
# # Generated by erpcgen 1.7.3 on Tue Mar 24 16:58:24 2020. # # AUTOGENERATED - DO NOT EDIT # import erpc from . import common, interface # Client for Bootloader class BootloaderClient(interface.IBootloader): def __init__(self, manager): super(BootloaderClient, self).__init__() self._clientManager...
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 import math import torch.nn as nn import torch class Hyper_synthesis(nn.Module): def __init__(self, num_filters=128): super(Hyper_synthesis, self).__init__() self.conv1 = nn.ConvTranspose2d(num_filters, num_filters, 3, stride=1, padd...
from motion import Motion from message_receiver import MessageReceiver from image_slicer import ImageSender from remote_control import RemoteControl from config import Config remote_control = RemoteControl(Config.ws_connection_url) ImageSender(remote_control) MessageReceiver(remote_control, Motion())
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_experiment ---------------------------------- Tests for `Experiment` class provided in pypsych.experiment module. """ import unittest import pandas as pd import numpy as np pd.set_option('display.max_rows', 50) pd.set_option('display.max_columns', 500) pd.set_o...
from numpy import diagonal, transpose from modules.helpers import anti_diagonal, noop SIGN = { '0': 'X', 'X': '0' } WINNING_FUNCTIONS = [diagonal, anti_diagonal, transpose, noop]
# Copyright IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 # import unittest import subprocess tool_directory = '../../tools/LTE/scripts' class smoke_ledger(unittest.TestCase): def test_FAB_9708_LevelDB_VaryNumTxs(self): ''' In this smoke test, we conduct a single, hopef...
from abaqusConstants import * class Cell: """Cells are volumetric regions of geometry. Attributes ---------- index: int An Int specifying the index of the cell in the CellArray. isReferenceRep: Boolean A Boolean specifying whether the cell belongs to the reference representation o...
# import keras import numpy as np from tensorflow import keras from utils.compute_overlap import compute_overlap class Anchor(object): """Anchor class for anchor-based object detectors.""" def __init__(self, min_level = 3, max_level = 7, num_scales = None, ...
#!/usr/bin/env python3 import io import numpy as np import cv2 import fcntl, os from PIL import Image import pycrow as crow import threading crow.create_udpgate(12, 10011) crow.set_crowker(".12.192.168.1.93:10009") thr = threading.Thread(target=crow.spin, args=()) thr.start() #crow.diagnostic_enable() data = Non...
################################################################################### # Nosetest settings ################################################################################### # biothings specific options - these should be identical to the production server # you are testing for... For example, JSONLD_CO...
import numpy as np from numpy.fft import fft2, ifft2, fftshift, ifftshift import skimage.io as io import matplotlib.pyplot as plt from skimage.metrics import peak_signal_noise_ratio as compute_psnr from pypher.pypher import psf2otf from pdb import set_trace from fspecial import fspecial_gaussian_2d img = io.imread('b...
"""Linting module.""" import shlex import subprocess from dataclasses import dataclass from functools import wraps from typing import Callable, List, Optional, Union, overload import typer from typing_extensions import Literal PACKAGE_NAME = 'roboto' def run_command( command: Union[str, List[str]], *args, **kwa...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def splitListToParts(self, root, k): cur = root for N in xrange(1001): if not cur: break ...
from gpiozero.pins.mock import MockFactory from gpiozero import Device, LED import config.ENVIRONMENT as Config import sqlite3 import sys from time import sleep if Config.SHOULD_MOCK_GPIOZERO: Device.pin_factory = MockFactory() GPIO_REGISTRY_LED = dict() for gpioId in Config.GPIO_REGISTRY: GPIO_REGISTRY_LED[gpioId...
from django.contrib.admin import AdminSite class RecruitrAdminSite(AdminSite): site_header = 'Recruitr Administration' admin_site = RecruitrAdminSite()
# Predigame Levels from copy import deepcopy from .Globals import Globals class Level: def __init__(self): self.globals = None def setup(self): """ setup all the sprites needed for this level """ raise NotImplementedError('Level.setup() cannot be called directly') def completed(self): """ execute an object...
import struct import typing from typing import Optional from .config import Config from .dao import AirCon, Device, get_device_by_aircon, AirConStatus from .base_bean import BaseBean from .ctrl_enum import EnumCmdType, EnumDevice, EnumControl, EnumFanDirection, EnumFanVolume class Encode: def __init__(self): ...
import unittest from mdssdk.connection_manager.errors import CLIError from mdssdk.vsan import Vsan from mdssdk.zone import Zone from mdssdk.zoneset import ZoneSet from tests.test_zoneset.vars import * log = logging.getLogger(__name__) class TestZoneSetRemoveMembers(unittest.TestCase): def __init__(self, testNam...
print("validação masculina/ feminina") resp = 1 while resp ==1: sexo = str(input("informe o se sexo: [F/M]")).strip().upper() if sexo == 'F' or sexo == 'M': resp = resp +1 else: print("os dados informados estão incorretos, digite novamente:") if sexo == "F": print("tenha um bom dia s...
import copy import datetime import logging import os import torch from tqdm import tqdm from .datasets import ToTensorflow from .evaluation import evaluate as e from .utils import load_dataset, load_model logger = logging.getLogger(__name__) MAX_NUM_MODELS_IN_CACHE = 3 def device(): return torch.device("cuda:0...
l = float(input('Qual a largura da parede em metros?')) a = float(input('Qual a altura da parede em metros?')) area = l*a tinta = area/2 print(f'A área da parede será de {area} metros quadrado sendo necessário a utilização de {tinta} litros de tinta')
from PIL import Image import pytesseract image = Image.open("ocr_example.jpg") text_convert = pytesseract.image_to_string(image, lang = 'eng') print(text_convert)
from rest_framework import generics, permissions as drf_permissions from rest_framework.exceptions import NotFound from rest_framework.views import Response from api.base import permissions as base_permissions from api.base.exceptions import Gone from api.base.views import JSONAPIBaseView from api.base.renderers impor...