content
stringlengths
5
1.05M
""" https://gist.github.com/ShenTengTu/5e40217db8f7a218b28f365a13a14c00 """ __all__ = ["CLI"] import argparse class CLI(argparse.ArgumentParser): """ Custom Argument Parser """ def __init__(self, main_params: dict, sub_params: dict): # record name of the attribute under which sub-command na...
'''HIST data analysis module. The functions in the module compute the response function in trade time scale from the Historic Rate Data from HIST Capital data in a year. This script requires the following modules: * os * pickle * typing * pandas The module contains the following functions: * hist...
''' Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is ")()())", where the longest valid parentheses substring is "()()", which has len...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # #Beamline Configuration Server. Primarly used to service the Beamline configuration panel and provide flexibility in communication with 14IDB motors. #Configuration Modes #!/usr/bin/env python3 from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run from ca...
#!/usr/bin/env python import datetime import logging import time import dateutil.parser import dateutil.tz import requests # Use this for creating the minimum datetime. # Never use datetime.datetime.min, as it's not aware of timezones. DATETIME_MIN = datetime.datetime( datetime.MINYEAR, 1, 1, tzinfo=dateutil.tz...
# -*- coding: utf-8 -*- ''' greenery.v1 -- backwards compatibility shim for greenery version 2 The greenery version 1.x interface: import greenery To retain greenery version 1.x interface under greenery version 2.x: from greenery import v1 as greenery or import greenery.v1 as greenery ''' from greenery._...
import pygame from States.basestate import Base from classes.buttonClass import Button from constants import * class Start(Base): """ This class state appears when 'python main.py' is invoked Parameters: Base: This is the base state """ def __init__(self): super().__init__() ...
# -*- coding: utf-8 -*- def KGEDrHFxUaoeIUfbQgbAIfGsHWKjjkvNhMPRDYVlIIztdYJHMpXFEodbKJtEzAZP(IteZczQyQnYarDRbPaeLJpnQJstiGjNFJoioNbszYaWeOkRiTWnzxNuZRQHsZtFk, zvpAaISCxHcZPdMyoNQfcvhDnhomVLcWDybmzzDFQOBxDvzEPPLIsPcFhHizKDPw, fjLJwfuqyrVdUjVRBPYXnsHQbilFRZwNJFRmsjFeZrgGxxsKxSlWATFxpiJHynyL): IteZczQyQnYarDRbPaeLJpnQ...
default_app_config = "paper_admin.patches.dal.apps.Config"
# Python program to rotate a matrix def rotate_recursive(matrix): if not len(matrix): return matrix rows = len(matrix) if rows < 2: return matrix if len(matrix[0]) < 2: return matrix rotate_recursive(matrix) rows = len(sample) columns = len(sample[0]) #sample_...
from PIL import Image import numpy as np def convert_image_to_mosaic(image, size, gradiation_step): for x in range(0, len(image), size): for y in range(0, len(image[0]), size): image[x:x +size, y:y +size]=get_average_brightness( image[x:x + size, y:y + size], size, gradi...
# Local imports from lib.color import Color from lib.component import Component class Draw(Component): """Draw function""" def circle(self, color: list, center: list, radius: int) -> None: """Create a shape function""" arguments = (Color.get_rgba(*color), list(center), radius) self.ad...
import numpy as np print('Hello, World from Python 3 Applet') print('numpy.__version__ = {}'.format(np.__version__))
__version__ = "1.0.1" from pdns_protobuf_receiver.receiver import start_receiver
from math import * num1 = int(input("Enter first digit: ")) num2 = int(input("Enter second digit: ")) def lcm(num1, num2): val = int(num1 * num2 / gcd(num1, num2)) return val print(lcm(num1, num2))
from django.conf.urls import url, include urlpatterns = [ url(r'^', include('toyApp.urls')), ]
# from .run import trainProcess # 58 min 10 sec merge_orc_df_rule_before_reduce userprofile/model/gender/latest/sample/merge/sample_20201020.orc # 61 min 36 sec merge_orc_df userprofile/model/gender/latest/sample/merge/sample_data1000_20201020.orc # import findspark # # findspark.init() from autoflow.samples.transfo...
import pytest from pystratis.core.types import Money from pystratis import api @pytest.fixture(scope='package', autouse=True) def initialize_nodes( start_strax_regtest_node, strax_hot_node, strax_syncing_node, strax_offline_node, node_mines_some_blocks_and_syncs, node_c...
from django.views.generic import ListView from blog.blog1.views import BlogPostView as PostView from blog.blog2.models import Post, PostComment from blog.main.views import PostRelatedViewMixin class BlogPostListView(PostRelatedViewMixin, ListView): model = Post queryset = Post.objects.select_related( ...
from drupalorg.tests.plugins import authorization from drupalorg.tests.test_authentication import AuthenticationTests from gitexd.interfaces import IAuth __author__ = 'christophe' class PushctlTests(AuthenticationTests): pluginPackages = { IAuth: authorization } def testPushEnabled(self): self._setUp()...
import torch from torch import nn import torch.nn.functional as F from collections import namedtuple from collections import deque import random MultiVariateNormal = torch.distributions.Normal temp = MultiVariateNormal.log_prob MultiVariateNormal.log_prob = lambda self, val: temp(self, val).sum(-1, keepdim=True) tem...
from flask import Flask,render_template, redirect, url_for app = Flask(__name__) @app.route('/') def index(): return render_template('home.html') @app.route('/home') def home(): return redirect(url_for('index')) @app.route('/featured') def featured(): return render_template('featured.html') @app.route(...
def testme(sa): import screen_area SA = screen_area.ScreenArea() w = MiniButton(SA, rely=3, relx=3) w.edit() w.display() curses.napms(1500) if __name__ == '__main__': import curses.wrapper curses.wrapper(testme) print "Join me, and we will end this destructive conflict"
# -*- coding:utf-8 -*- from __future__ import absolute_import, unicode_literals from __future__ import division, print_function import re import warnings import scipy.stats as sps import scipy.spatial.distance as spsd from ..core.color import Color import PhloxAR.core.image from ..base import cv2, np, lazy_property fr...
from random import randint from time import sleep aleatorizador = randint(1,10) tentativas = 0 resultado = 0 print('\033[1;31mO computador pensara em um numero entre 1 e 10, tente acertar\033[m') print('\033[1;33mSorteando . . .\033[m') sleep(0.50) while resultado != aleatorizador: #repita se resultado for dife...
"""A string calculator.""" # ----------------------------------------------------------------------------- def parse_num_str(num_str: str) -> list: """Parse the num_str from the input string.""" if num_str == "": return [0] delimiter = ',' def split(string_): return string_.split(del...
import pandas as pd import pdb import pickle import matplotlib.pyplot as plt from Analysis_Utils import preprocessing_df as preprocessing import DataStream_Vis_Utils as utils from moviepy.editor import * import skvideo import cv2 import imageio import numpy as np from scipy import ndimage from errno import EEXIST, ENOE...
import urllib import json class NoArgumentsException(Exception): def __str__(self): return "No arguments were found." class BadJSONException(Exception): def __str__(self): return "The returned JSON was invalid." class NonexistentStyleException(Exception): def __str__(self): return "The requested AP...
# auto-generated file import _cffi_backend ffi = _cffi_backend.FFI('FFI._gles3ffi', _version = 0x2601, _types = b'\x00\x00\x35\x0D\x00\x00\x08\x01\x00\x00\x07\x01\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x08\x01\x00\x00\x00\x0F\x00\x00\x02\x0D\x00\x00\x08\x01\x00\x06\xDF\x03\x00\x00\x00\x0F\x00\...
import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow import keras class RandomProcessImage: def __init__(self, target_shape=(300, 300), magnitude=0, central_fraction=1.0, keep_shape=False): self.target_shape, self.magnitude, self.keep_shape = target_shape, magnitud...
''' Testing capabilities of opencv in OmniSynth. sources: 1) Shantnu Tiwari's Real Python articles: https://realpython.com/face-detection-in-python-using-a-webcam/ https://realpython.com/face-recognition-with-python/#opencv 2) https://github.com/shantnu/Webcam-Face-Detect ''' import cv2 cascade...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ script to convert BYU-MERS .sir file to geotiff. Here we preserve data values (no scaling to 0-255) like the c routine supplied by the BYU-MERS sir2geotiff.c routine. """ import os import sys import argparse import numpy as np from osgeo import gdal, osr from pathlib...
#!/usr/bin/env python # Builds the schema code out import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) from aud_build_utils import main main()
from typing import Any from tartiflette.types.type import GraphQLWrappingType __all__ = ("GraphQLList",) class GraphQLList(GraphQLWrappingType): """ Definition of a GraphQL list container. """ is_list_type = True # Introspection attributes kind = "LIST" def __eq__(self, other: Any) ->...
L=[1] n=int(input()) for i in range(1,n+1): L.append(0) for j in range(i): L[i] += L[j]*L[i-j-1] print(L[n])
# 2021-06-08 11:56:09 #! @author : @ruhend # imports here import hashlib # global variables here ### Write Code From Here ### class MakeAHash: def _EncodeString(_string): encoded_string = _string.encode() return encoded_string def _SHA256This(_string): sha256ed = hashlib.sha256(_s...
# 1. Import Flask from flask import Flask,jsonify import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt engine = create_engine("sqlite:///Resources/hawaii.sqlite") Base = automap_base() Base.prepare(engine,r...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-09-22 10:41 from __future__ import unicode_literals from django.db import migrations def update_services(apps, schema_editor): Service = apps.get_model('bdo_main_app', 'Service') clustering = Service.objects.get(title='Regression') clustering.inf...
class Command: def usePassword(self): return False def register(self, dictionary): dictionary[self._name] = self return self def storage(self, storage): self._storage = storage return self def _description(self, shortDescription, longDescription = None): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from ..models import GitHubObject class PagesInfo(GitHubObject): def _update_attributes(self, info): self._api = info.get('url') #: Status of the pages site, e.g., built self.status = info.get('status') #: CName used...
class QueryUpgradeSubTaskInDTO(object): def __init__(self): self.subOperationStatus = None self.pageNo = None self.pageSize = None def getSubOperationStatus(self): return self.subOperationStatus def setSubOperationStatus(self, subOperationStatus): self.subOperation...
# Generated by Django 3.1.2 on 2020-11-09 04:23 import cloudinary.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_US...
import socket import sys from control_flow_constants import * sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = (CHEETAH_MASTER_IP, CHEETAH_MASTER_PORT) msg = b'ACK' try: sent = sock.sendto(msg, server_address) finally: sock.close()
from corgie.stack import Stack from corgie.log import logger as corgie_logger from corgie.argparsers import create_layer_from_dict, create_layer_from_spec import json def spec_to_stack(spec, prefix, layers): """Create Stack by filtering a dict of layers Args: spec (dict): job_specs including src_img, ...
import Adafruit_ADS1x15 import time import traceback import logging # Note you can change the I2C address from its default (0x48), and/or the I2C # bus by passing in these optional parameters: #adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1) # Choose a gain of 1 for reading voltages from 0 to 4.09V. # Or pick ...
"""Functions related to decryption.""" import os from shutil import copyfile from zipfile import ZipFile from cryptography.fernet import Fernet from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import hashes from peewee import DoesNotExist from config import DB_FILE, D...
from colorama import Fore, Back, Style import time #print(Fore.GREEN) Base = '[+] ' Repl = 'repl.it: https://replit.com/@' About = 'About.me: https://about.me/' Github = 'Github: https://www.github.com/' Codecademy = 'Codecademy: https://www.codecademy.com/profiles/' Roblox = 'Roblox: https://www.roblox.com/user....
import contextlib import glob import os.path import re import sys __file__ = os.path.abspath(__file__) ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) INTERNAL = os.path.join(ROOT, 'Include', 'internal') STRING_LITERALS = { 'empty': '', 'dot': '.', } IGNORED = { 'ACTION', # Python/_w...
import jwt import json from app import log, config, redisBroker from app.constants import CRED_GEN from app.api.common import BaseResource from app.model.emailValidationTx import EmailValidationTx, EmailValidationStatus from app.errors import ( AppError, ) LOG = log.get_logger() class EmailConfirmation(BaseResou...
# 문제: https://www.acmicpc.net/problem/2879 # 풀이: 1. 현재 탭과 고칠 탭의 차 배열을 계산 # 2. 루프를 돌며 시작점부터 차이가 값이 0이 아닌 위치까지 한 그룹으로 탭을 넣거나(+1) 탭을 뺀다(-1) # 3. 한 그룹에 탭을 넣거나 빼면 카운트 증가 n = int(input()) current_tabs = list(map(int, input().split())) result_tabs = list(map(int, input().split())) differences = [current_tabs[i] - ...
onto_spec = 'http://theworldavatar.com/ontology/ontospecies/OntoSpecies.owl' gain_pref = 'http://purl.org/gc/' kin_pref = 'http://www.theworldavatar.com/ontology/ontokin/OntoKin.owl' table_pref = 'http://www.daml.org/2003/01/periodictable/PeriodicTable.owl' unit_pref = 'http://data.nasa.gov/qudt/owl/' species_entry_pre...
""" @brief test log(time=50s) """ import sys import os import unittest import warnings from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder try: import src except ImportError: path = os.path.normpath( os.path.abspath( os.path.join( ...
import cv2 import numpy as np import io as lib from imageio import imread from matplotlib import pyplot from Comparacao_Pascal import * import PIL from skimage import data, io, segmentation, color, morphology, img_as_ubyte #Pega os nomes dos arquivos e manda para uma lista from os import listdir from os.p...
import unittest import nifty import nifty.graph import nifty.graph.opt.mincut import numpy import random numpy.random.seed(7) class TestMincutSolver(unittest.TestCase): def generateGrid(self, gridSize): def nid(x, y): return x*gridSize[1] + y G = nifty.graph.UndirectedGraph ...
"""This file contains various constructions found in Euclid's Elements""" from geompy import Point, Construction from geompy.core.Construction import ConstructionMode def BaseConstruction(name='', construction_mode=ConstructionMode.DEFAULT): """A construction with two points a unit length apart. It is easier ...
import re import unittest from faker import Faker class TestBarcodeProvider(unittest.TestCase): """ Tests barcode provider """ num_sample_runs = 1000 def setUp(self): self.ean8_pattern = re.compile(r'^\d{8}$') self.ean13_pattern = re.compile(r'^\d{13}$') self.upc_a_pattern = re....
#!/usr/bin/python3 # Representation of formulas in Python. # # The basic connectives are NOT, AND and OR. # IMPL and EQVI are reduced to these through the obvious reductions. # We have a separate class for formulas with different outermost # connectives, as well as for atomic formulas (ATOM). # # Both AND and OR inhe...
def binary_search(arr, key, start, end): while start <= end: mid = (start + end) // 2 # taking floor value if arr[mid] == key: return mid elif key < arr[mid]: end = mid - 1 return binary_search(arr, key, start, end) else: start = mid +...
import dataclasses import math from platform import system from types import SimpleNamespace from typing import ( TYPE_CHECKING, Any, Callable, Dict, FrozenSet, List, Literal, Optional, Set, Tuple, Union, ) from dns.rdtypes.ANY.NS import NS from dns.resolver import Answer, N...
import unittest import sums as sums class TestRunningSum(unittest.TestCase): """Tests for sums.running_sum.""" def test_running_sum_empty(self): """Test an empty list.""" argument = [] expected = [] sums.running_sum(argument) self.assertEqual(expected, argument, "The li...
#/bin/python # Simple b64 wrapper import base64, sys class EZ_b64(): def encode(self, data): encoded = base64.b64encode(data) print encoded def decode(self, data): decoded = base64.b64decode(data) print decoded if __name__ == '__main__': try: opperation = sys.argv[1] data = sys.argv[2] b64 = EZ_...
#Import packages import matplotlib matplotlib.use('TkAgg') import caffe import lmdb import numpy as np from numpy import linalg as LA import matplotlib.pyplot as plt import matplotlib.mlab as mlab import matplotlib.image as mpimg import sys import math import csv import gc import os from scipy.stats import norm impor...
import sys import time import logging import os if os.name == 'nt': from neutron.agent.windows import utils as exc_utils else: from neutron.agent.linux import utils as exc_utils from runtime_CLI import ResType import networking_p4.agent.agent_drivers.bmv2.adaptor.bmv2.runtime_api from bm_runtime.standard.Sta...
from rest_framework import serializers from product.models import * from finance.models import * class ProductSerializer(serializers.HyperlinkedModelSerializer): brands = serializers.StringRelatedField() class Meta: model = Product fields = '__all__' class CategorySerializer(serializers.Hy...
KEY_VUE_APP_GOOGLE_CLIENT_ID = 'VUE_APP_GOOGLE_CLIENT_ID' KEY_VUE_APP_ADOBE_PDF_CLIENT_ID = 'VUE_APP_ADOBE_PDF_CLIENT_ID' KEY_VUE_APP_WEBSOCKET_PREFIX = 'VUE_APP_WEBSOCKET_PREFIX'
from intensity_normalization.utilities import io, mask, hist, quality
#!/usr/bin/python # -*- coding: UTF-8 -*- class Employee: '所有员工的基类' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print("Total Employee %d" % Employee.empCount) def displayEmploy...
"""Test the rayvision_sync manage functions.""" # pylint: disable=import-error import pytest from rayvision_api.operators import Query @pytest.fixture() def task_status_list(): """Get the task_status_list information.""" return [ { "task_status_code": "-1", "is_opener": "1", ...
#!/usr/bin/python3 from pathlib import Path from datetime import date, datetime import sys import time import holidays from prometheus_client import Gauge, start_http_server import yaml ''' Example of the configuration file: --- main: port: 9110 holidays: - country: CA province: ON - country: US state:...
from __future__ import print_function import sublime, sublime_plugin import subprocess from os import environ import re class jumptoregkeyCommand(sublime_plugin.TextCommand): def run(self, edit): regkey = self.view.substr(self.view.line(self.view.sel()[0].begin())) openbracketpos = regkey.find('[') cl...
#! /usr/bin/env python3 """Example map generator: King of the Hill Example This script demonstrates vmflib by generating a basic "king of the hill" style map. "King of the hill" is a game mode in Team Fortress 2 where each team tries to maintain control of a central "control point" for some total defined amount of ti...
#!/usr/bin/env python """ Check that Cython extensions in setup.py files match those in bento.info. """ import os import re import sys RE_CYTHON = re.compile("config.add_extension\(\s*['\"]([\S]+)['\"]") BENTO_TEMPLATE = """ Extension: {module_path} Sources: {dir_path}.pyx""" def each_setup...
############################################################################## # # Copyright (c) 2001 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS I...
""" Write a modified version of the Matrix class(that was defined in one of the example problems in this section) with an __add__ operation as well as a __sub__ operation. It should add matrices, assuming that they will be of the same length. Also, the unmodified Matrix class code will be given. """ """ This is the un...
# Copyright 2020 IBM Corp. # # 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 a...
#! /usr/bin/env python3 import os import argparse import config import config.user_input.console from build_all_examples import run_program from config.boards import list_of_boards, load_board_config from config.devices import list_of_devices, list_of_vendors, \ list_of_families, load_device_config from config.a...
import json import re import uuid from datetime import datetime from typing import Any, Optional, Sequence import httpx from pydantic import BaseModel from rich.align import Align from rich.columns import Columns from rich.console import Console from rich.panel import Panel from py_nest_thermostat.auth import Authent...
from .viewmayavi import ( MayaviTriMeshViewer3d, MayaviPointGraphViewer3d, MayaviTexturedTriMeshViewer3d, MayaviLandmarkViewer3d, MayaviVectorViewer3d, MayaviColouredTriMeshViewer3d, ) PointGraphViewer3d = MayaviPointGraphViewer3d TriMeshViewer3d = MayaviTriMeshViewer3d TexturedTriMeshViewer3d ...
""" NestedItem CMS plugin factories """ import factory from .defaults import NESTEDITEM_VARIANTS from .models import NestedItem class NestedItemFactory(factory.django.DjangoModelFactory): """ Factory to create random instances of NestedItem for testing. """ class Meta: model = NestedItem ...
################### # COLOR CONSTANTS ################### HEADER = '\033[95m' OK_BLUE = '\033[94m' OK_GREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' ########################### # ERROR MESSAGES CONSTANTS ########################### BASE_ERROR_MSG = '\...
from datasets.NamedEntityRecognitionDataset import NamedEntityRecognitionDataset
###################################################### # # BioSignalML Management in Python # # Copyright (c) 2010-2013 David Brooks # # 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 # # ...
#!/usr/bin/env python3 from __future__ import print_function import sys import os from array import array import cv2 import numpy as np import time import openncc as ncc import struct min_score = 0.8 media_head ='iII13I' def coordinate_is_valid( x1, y1, x2, y2): if((x1<0) or (x1>1)): ...
import base64 import math import random import cv2 import mmcv import numpy as np from ..builder import PIPELINES @PIPELINES.register_module() class CopyAndPaste(object): def __init__(self, to_float32=False, color_type='color', base_scale=(1333, 800), ...
from __future__ import unicode_literals from django import forms from utilities.forms import BootstrapMixin OBJ_TYPE_CHOICES = ( ('', 'All Objects'), ('Circuits', ( ('provider', 'Providers'), ('circuit', 'Circuits'), )), ('DCIM', ( ('site', 'Sites'), ('rack', 'Racks')...
from .base import BaseDetector from .single_stage import SingleStageDetector from .two_stage import TwoStageDetector from .two_stage_rgb import TwoStageRGBDetector from .two_stage_rgb_2 import TwoStageDetectorRGB2 from .two_stage_3d import TwoStageDetector3D from .two_stage_3d_parcel import TwoStageDetector3DParcel fro...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Aug 7 10:31:38 2019 @author: didelani """ import os import sys import numpy as np from collections import defaultdict, Counter import re import json output_dir = '../data/training/' def get_tagged_sentence(sent): tagged_sentence = '' for tok...
#!/usr/bin/env python # Copyright 2011 OpenStack LLC. # 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 #...
from collections import deque # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]: def dfs(node, parent...
# -*- coding: utf-8 -*- """ TODO try to use inherit mehcanism to integrate multiple canned template, not doable yet """ import pytest from troposphere_mate.canned import iam def test(): can_common_lbd_func_iam_role = iam.CannedCommonLambdaFunctionIamRole( PROJECT_NAME="my_project", STAGE="dev", ...
import unittest from unittest.mock import patch, MagicMock from sawpit import RestRequest class RestRequestTests(unittest.TestCase): def test_create_rest_request_with_uri_and_method(self): rest_request = RestRequest('https://example.com', 'POST') self.assertEqual(rest_request.uri, 'https://examp...
import os import tempfile import pyaudio from recording import Recording class AudioRecorder: def __init__(self, recording_device_name): self.audio = pyaudio.PyAudio() self.device_index = self._get_recording_device_index(recording_device_name) self._current_recording = None self....
""" Active Directory In Windows Active Directory, a group can consist of user(s) and group(s) themselves. We can construct this hierarchy as such. Where User is represented by str representing their ids. """ class Group(object): def __init__(self, _name): self.name = _name self.gr...
from qtpy.QtCore import (QPointF) from qtpy.QtGui import (QPainterPath) from .base import BaseSymbolIcon class RGASymbolIcon(BaseSymbolIcon): """ A widget with a residual gas analyzer symbol drawn in it. Parameters ---------- parent : QWidget The parent widget for the icon """ pa...
""" pypreclin preprocessing ======================= Credit: A Grigis & J Tasserie WORK IN PROGRESS The preprocessing and analysis of nonhuman primate (NHP) magnetic resonance imaging (MRI) data presents some unique challenges. 1. non standard orientation, sphinx position. 2. strong intensity bias. 3. non brain tiss...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # feedjit.py # # Copyright 2010 Javier Rovegno Campos <tatadeluxe<at>gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
n = int(input("How many nums: ")) nums =[] mas = -1 for i in range(n): a = int(input("Inserisci un numero: ")) if a > mas: mas = a print("Il massimo fra questi", n, "numeri è", mas)
#!/usr/bin/env python # -*- coding: utf-8 -*- import keras import tqdm from collections import defaultdict import numpy as np from keras.models import save_model class TqdmProgressCallback(keras.callbacks.Callback): def on_train_begin(self, logs=None): self.epochs = self.params['epochs'] def on_epoc...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...