content
stringlengths
5
1.05M
import socket from typing import Any import orjson from fastapi.responses import ORJSONResponse as O from pydantic import BaseModel def default_encode(obj): if isinstance(obj, BaseModel): return obj.dict() raise NotImplementedError class ORJSONResponse(O): def render(self, content: Any) -> byte...
# Copyright 2018 the Deno authors. All rights reserved. MIT license. """ Computes the SHA256 hash and formats the result. """ import argparse from hashlib import sha256 import os import sys def main(): parser = argparse.ArgumentParser(description=__doc__) # Arguments specifying where input comes from. #...
import bs4 as bs import urllib.request def get_article(site='https://www.brainpickings.org/2016/08/16/friendship/'): # Scraping data using urllib and then parsing using beautifulsoup (by paragraph) scraped_data = urllib.request.urlopen(site) article = scraped_data.read() parsed_artic...
"""Contains all exposed elements from the handlers. """ # Run an OS scrape of the handlers folder and return # the read_x and write_x for each handler. __all__ = []
import tensorflow as tf import numpy as np n_inputs = 3 n_neuros = 5 n_steps = 2 seq_length = tf.placeholder(tf.int32, [None]) X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) X_seqs = tf.unstack(tf.transpose(X, perm=[1, 0, 2])) basic_cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neuros) output_seqs, ...
# -*- coding: utf-8 -*- import click from rich.console import Console from .add import add from .mklib import mklib CONSOLE = Console() @click.group() def main(): pass mklib = main.command(help="Create new empty library.")(mklib) add = main.command(help="Add model to existing library.")(add)
from mongoengine.errors import (DoesNotExist, MultipleObjectsReturned, InvalidQueryError, OperationError, NotUniqueError) from mongoengine.queryset.field_list import * from mongoengine.queryset.manager import * from mongoengine.queryset.queryset import * f...
from com.xhaus.jyson import JysonCodec as json from ij.plugin.frame import RoiManager from ij.io import OpenDialog from ij.gui import Roi, PolygonRoi import sys def get_roi(data): if data['type'] == 'polygon': return PolygonRoi(data['x'], data['y'], data['count'], Roi.POLYGON) elif data['type'] == 'co...
# RC4 # https://en.wikipedia.org/wiki/RC4 # Key-scheduling algorithm (KSA) def ksa(key): s = [] for i in range(0, 256): s.append(i) j = 0 for i in range(0, 256): j = (j + s[i] + ord(key[i % len(key)])) % 256 s[i], s[j] = s[j], s[i] return s # Pseudo-random generation algor...
# -*- coding: utf-8 -*- # The above encoding declaration is required and the file must be saved as UTF-8 import random class LotoTron: pass def __init__(self, min_num=1, max_num=90): self._min_num = min_num self._max_num = max_num self._src_list = list(range(self._min_num, self._max_...
import pytest from texthooks.fix_ligatures import parse_args as fix_ligatures_parse_args from texthooks.fix_smartquotes import ( DEFAULT_DOUBLE_QUOTE_CODEPOINTS, DEFAULT_SINGLE_QUOTE_CODEPOINTS, ) from texthooks.fix_smartquotes import parse_args as fix_smartquotes_parse_args def test_fix_ligatures_arg_parsin...
#!/usr/bin/env python """ Calculate the number of increases in a list of subsequent measurements which are smoothed in a sliding window. Measurements are read from file """ import fileinput import sys if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: day1_sonar_sweep_part2.py <measurements...
import sys from inference_model import InferenceModel from shared_latent_space import SharedLatentSpace from decoder_train import DecoderTrain from training import Training from testing import Testing from reconstructor import Reconstructor from visualizer import Visualizer import warnings warnings.filterwarnings("igno...
import numpy as np from scipy.stats import multivariate_normal from to.probabilistic_model import ProbabilisticModel class MixtureModel(object): def __init__(self, allModels, alpha=False): self.model_list = allModels.copy() self.nModels = len(allModels) if alpha is False: self.a...
from collections import namedtuple DetectedObjectTuple = namedtuple('DetectedObject', 'id label x y w h score frame timestamp') class DetectedObject(DetectedObjectTuple): @property def cx(self): return self.x + self.w / 2 @property def cy(self): return self.y + self.h / 2 @staticmethod def fro...
from abc import ABCMeta, abstractmethod import logging import time import pause logging.basicConfig() class Timer(object): """ Timer abstract base class represents interface for a periodic timer. """ __metaclass__=ABCMeta @abstractmethod def wait(self): pass @abstractmethod def ...
# Create a block storage from oneandone.client import OneAndOneService, BlockStorage client = OneAndOneService('<API-TOKEN>') block_storage = BlockStorage(name='My new block storage', description='My block storage description', size=20, ...
import chainer from chainer.dataset import convert from chainer.training import StandardUpdater def fetch(iterators, converter, device=None): return converter(iterators['main'].next(), device) class TrainingStep(StandardUpdater): def __init__(self, iterator, optimizer, metrics_func, conve...
# -*- coding: utf-8 -*- # # Copyright 2017 Google 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 # # Unless requir...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: root.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf i...
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# coding: utf-8 from keras.applications.imagenet_utils import preprocess_input from keras.preprocessing import image from scipy.misc import imread import tensorflow as tf from keras import backend as K import time from plot_util import * from flow_util import * from ssd_v2 import SSD300v2 from ssd_conv4_3...
""" .. module:: PickleWrapper :synopsis: Wrapper for cPickle object saving package .. moduleauthor:: Ambra Demontis <ambra.demontis@unica.it> .. moduleauthor:: Marco Melis <marco.melis@unica.it> """ import pickle import gzip from secml.utils import fm # Remember to add any new method to following list __all__ = ...
#!/usr/bin/env python3 import argparse import pygamer import numpy as np import pyvista as pv import pyacvd import vtk from pathlib import Path from lightdock.pdbutil.PDBIO import create_pdb_from_points def parse_command_line(): """Parses command line arguments""" parser = argparse.ArgumentParser(prog='surfa...
import numpy as np from .contrib import transformations from . import math_utils def translation_matrix(offset): mat = np.eye(4, dtype=offset.dtype) mat[:3, 3] = offset return mat def apply_translation(mat, offset): offset_mat = translation_matrix(offset) print(offset, offset_mat) mat[...] =...
import os import numpy as np import json from PIL import Image from model import * kernels = buildKernels() def detect_red_light(I): ''' This function takes a numpy array <I> and returns a list <bounding_boxes>. The list <bounding_boxes> should have one element for each red light in the image. Each el...
import warnings from functools import partial from typing import Any, List, Optional, Type, Union from ...models.resnet import BasicBlock, Bottleneck, ResNet from ..transforms.presets import ImageNetEval from ._api import Weights, WeightEntry from ._meta import _IMAGENET_CATEGORIES __all__ = ["ResNet", "ResNet50Weig...
import os import gzip import torch from torch.utils.data import Dataset import numpy as np import cv2 from .utils import IMAGE_CHANNELS, IMAGE_HEIGHT, IMAGE_WIDTH, cache_path, ImageDataset, one_hot, file_md5, download_file from vaetc.utils import debug_print from struct import unpack def read_binary_matrix(file_pat...
from django.db import models from Category.models import Category class City(models.Model): name = models.CharField(max_length=20, unique=True) categories = models.ManyToManyField(Category) def __str__(self): return self.name # class Area(models.Model): # name = models.CharField(max_length...
""" dlam trying to make this old 'shorturls' package compatible with 2.0! """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured try: from importlib import import_module except: from django.utils.importlib import import_module from shorturls import baseconv default_conver...
from thenewboston_node.business_logic.models import ( NodeDeclarationSignedChangeRequestMessage, SignedChangeRequestMessage ) def test_can_deserialize_from_base_class(): instance = SignedChangeRequestMessage.deserialize_from_dict({ 'signed_change_request_type': 'nd', 'node': { 'net...
import random # TODO: Get this outta here! spinner_choice = random.choice(['aesthetic', 'arc', 'arrow3', 'betaWave', 'balloon', 'bounce', 'bouncingBar', 'circle', 'dots', 'line', 'squish', 'toggle10', 'pong']) # TODO: Replace these removed soundtracks soundtrack_files = [ "talc_soundtrack.mp3", "talc_soundtrac...
from lime.lime_image import * import pandas as pd import yaml import os import datetime import dill import cv2 import numpy as np from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image import ImageDataGenerator from src.visualization.visualize import visualize_explanation from src.pred...
# 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.package import * class Libslirp(MesonPackage): """General purpose TCP-IP emulator""" homepage = '...
from libya_elections.admin_models import LibyaAdminModel from libya_elections.admin_site import admin_site from .models import Subscription class SubscriptionAdmin(LibyaAdminModel): list_display = ['__str__', 'get_subscription_type_display'] list_filter = ['subscription_type'] raw_id_fields = ['user'] a...
"""The expected interface for all learner implementations.""" from abc import ABC, abstractmethod from typing import Any, Sequence, Dict, Union, Tuple, Optional from coba.simulations import Context, Action, Key class Learner(ABC): """The interface for Learner implementations.""" @property @abstractmetho...
try: from unittest import mock except ImportError: import mock from rest_framework import status from rest_framework.reverse import reverse url = reverse("rest-email-auth:password-reset") @mock.patch( "rest_email_auth.views.serializers.PasswordResetSerializer.save", autospec=True, ) def test_reques...
from .capeval.cider import Cider
import asyncio import logging import types import typing import enum from dataclasses import dataclass from ..types import ASGIApp, Message from ..exceptions import LifespanUnsupported, LifespanFailure, UnexpectedMessage class LifespanCycleState(enum.Enum): """ The state of the ASGI `lifespan` connection. ...
from gii.core import * from gii.moai.MOAIEditCanvas import MOAIEditCanvas from gii.AssetEditor import AssetPreviewer from gii.qt.helpers import addWidgetWithLayout from PyQt4 import uic from PyQt4 import QtGui def _getModulePath( path ): import os.path return os.path.dirname( __f...
# Build Single Element # # Create an OpenMC model of just a single lonely fuel element import numpy import openmc import sys; sys.path.append('../..') import treat class SingleFuelElementBuilder(treat.CoreBuilder): def __init__(self, material_lib, name="Single Fuel Element"): super().__init__(material_lib, 1, nam...
import unittest from context import src from context import config class TestEnvironment(unittest.TestCase): def setUp(self): self.env = src.simulation.environment.Environment(config) def test_instance(self): self.assertIsNotNone(self.env) def test_add_patch(self): ...
# # Copyright (C) 2020 IBM. All Rights Reserved. # # See LICENSE.txt file in the root directory # of this source tree for licensing information. # import json import os from clai.emulator.emulator_docker_bridge import EmulatorDockerBridge # pylint: disable=too-many-instance-attributes from clai.server.command_runner.c...
import functools import re from unittest import mock import numpy import pytest try: import scipy.sparse scipy_available = True except ImportError: scipy_available = False import cupy from cupy import testing from cupy.cuda import runtime from cupyx.scipy import sparse from cupyx.scipy.sparse import _cons...
from datetime import datetime from flask import Flask, render_template import json import requests from spotify_api.api import SpotifyApi app = Flask(__name__) s_api = SpotifyApi() LASTFM_API_KEY = "b9ba81a4f80bbff4fa3fcf7df609947e" LASTFM_API_SECRET = "65f9cf1308e52e3369c5eeb992fa846a" def getRecentTracks(user): ...
# coding: utf-8 """ syntropy-controller No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 0.1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 imp...
from IProcess import IProcess, EDataType from PIL import Image import numpy as np import math import cv2 class CropImageByClass(IProcess): def __init__(self): IProcess.__init__(self) self.cropped = True def getType(self): return EDataType.CroppedPic def toId(self): return str(__class__.__name__) def d...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GeneratorControl.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_GeneratorControlMain(object): def setupUi(self, GeneratorCo...
import logging import requests logger = logging.getLogger(__name__) URLS = { "get_message_from_sqs_queue": "/api/jobs/challenge/queues/{}/", "delete_message_from_sqs_queue": "/api/jobs/queues/{}/", "get_submission_by_pk": "/api/jobs/submission/{}", "get_challenge_phases_by_challenge_pk": "/api/challe...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torchvision import torchvision.transforms as transforms import numpy as np import math import matplotlib.pyplot as plt import torch.optim as optim from torch.utils.data import Dataset, DataLoader from sklearn....
# -*- coding: utf-8 -*- ''' Tests for the Git state ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import functools import inspect import os import shutil import socket import string import tempfile # Import Salt Testing libs from tests.support.case import ModuleCase...
from sqlalchemy.sql import sqltypes from georef_ar_etl.utils import ValidateTableSizeStep from georef_ar_etl.exceptions import ProcessException from . import ETLTestCase class TestValidateTableSizeStep(ETLTestCase): def test_eq(self): """El validador debería retornar la tabla de entrada si su tamaño es el...
# -*- coding: utf-8 -*- # @Time : 2022/02/10 16:39:46 # @Author : ddvv # @Site : https://ddvvmmzz.github.io # @File : json2tree.py # @Software : Visual Studio Code # @WeChat : NextB from io import StringIO _branch_extend = '│ ' _branch_mid = '├─ ' _branch_last = '└─ ' _spacing = ' ' lan...
# # Tests for LG M50 parameter set loads # import pybamm import unittest class TestChen(unittest.TestCase): def test_load_params(self): anode = pybamm.ParameterValues({}).read_parameters_csv( pybamm.get_parameters_filepath( "input/parameters/lithium-ion/anodes/graphite_Chen2020...
# By manish.17, contest: ITMO Academy. Дерево отрезков часть 1. 1, problem: (A) Segment Tree for the Sum # https://codeforces.com/profile/manish.17 from math import inf, log2 class SegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2**(int(log2(self.n-1))+1) if self...
# https://www.codewars.com/kata/517abf86da9663f1d2000003/train/python # Complete the method/function so that it converts dash/underscore delimited # words into camel casing. The first word within the output should be capitalized # only if the original word was capitalized (known as Upper Camel Case, also # often...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from chainlibpy import CROCoin, GrpcClient, Transaction, Wallet from chainlibpy.generated.cosmos.bank.v1beta1.tx_pb2 import MsgSend from chainlibpy.grpc_client import NetworkConfig # Recommend to use [pystarport](https://pypi.org/project/pystarport/) to setup a testnet ...
# # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 7 11:51:53 2019 @author: carsault """ #%% import pickle import torch from utilities import chordUtil from utilities.chordUtil import * from utilities import testFunc from utilities.testFunc import * from utilities import distance from utilities.di...
import pytest from antidote import config, is_compiled config.auto_detect_type_hints_locals = True def pytest_runtest_setup(item): if any(mark.name == "compiled_only" for mark in item.iter_markers()): if not is_compiled(): pytest.skip("Compiled only test.")
from collections import deque from featuretools.variable_types.variable import Discrete import warnings import numpy as np import string import pandas import re import math from datetime import datetime, timedelta from pyzipcode import ZipCodeDatabase from pandas import Series from scipy.signal import savgol_filter ...
import time import pvl import pytest import docker import numpy as np from aiohttp.test_utils import loop_context from web import redis_cache, pdsimage TEST_REDIS_PORT = 6380 @pytest.fixture(scope='function', autouse=True) def turn_off_sentry(mocker): mocker.patch('web.constants.DSN', '') m...
from typing import Optional, Callable, Mapping, Any, List import abc import torch as tc from drl.agents.architectures.abstract import Architecture class StatelessArchitecture(Architecture, metaclass=abc.ABCMeta): """ Abstract class for stateless (i.e., memoryless) architectures. """ def __init__( ...
import cocotb from cocotb.clock import Clock import cocotb.triggers as triggers from cocotb.triggers import Timer import hashes import bit_handle as bh report = open('report.txt','w') @cocotb.test() async def test(dut): """Try accessing the design.""" dut._log.info("Running test...") cocotb.fork(Clock(du...
import tempfile from unittest import mock from unittest.mock import call import pytest from click.testing import CliRunner from zhinst.labber.cli_script import main from zhinst.labber import generate_labber_files def test_cli_script_main(): runner = CliRunner() result = runner.invoke(main, ["--help"]) as...
#!MF_PYTHONBIN # Copyright (C) 2010 The MITRE Corporation. See the toplevel # file LICENSE for license terms. import os, sys MAT_PKG_PYLIB = "MF_MAT_PKG_PYLIB" sys.path.insert(0, MAT_PKG_PYLIB) # Must import MAT so that sys.path is enhanced. import MAT PLUGIN_DIR = MAT.PluginMgr.LoadPlugins() # # Toplevel # fro...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 VMware, Inc. # 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/lic...
import importlib import os class EnvSettings: def __init__(self): pytracking_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) self.results_path = '{}/tracking_results/'.format(pytracking_path) self.segmentation_path = '{}/segmentation_results/'.format(pytracking_path)...
import logging import unittest import numpy as np from bokeh.models.widgets import DataTable from pandas import DataFrame from cave.utils.bokeh_routines import array_to_bokeh_table class TestCSV2RH(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(42) def test_array_to_bokeh_ta...
from scraper import * s = Scraper(start=112266, end=114047, max_iter=30, scraper_instance=63) s.scrape_letterboxd()
import pandas as pd from ms_mint.Resampler import Resampler def test__Resampler_50ms_minutes_dt(): chrom = pd.Series([0, 10, 5], index=[0, 0.9, 1]) result = Resampler(smooth=False, tau="50ms", unit="minutes").resample(chrom) tau_in_seconds = result.index[1] * 60 assert tau_in_seconds == 0.05 def tes...
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Rusty Joomla RCE - Unauthenticated PHP Object Injection in Joomla CMS''', "description": '''Unauthenticated PHP Object Injection in Joomla CMS from the release 3.0.0 to the 3.4.6 (releases from 2012 to...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Style: Google Python Style Guide: http://google.github.io/styleguide/pyguide.html @version 1.0.00 @author-name Wayne Schmidt @author-email wayne.kirk.schmidt@gmail.com @license-name APACHE 2.0 @license-url http://www.apache...
# ============================================================================ # # # # This is part of the "GrainSizeTools Script" # # A Python script for characterizing grain size from thin sections ...
""" Tools to draw a chord diagram in python """ from collections.abc import Sequence import matplotlib.patches as patches from matplotlib.colors import ColorConverter from matplotlib.path import Path import numpy as np import scipy.sparse as ssp from .gradient import gradient from .utilities import _get_normed_lin...
import sys from kapacitor.udf.agent import Agent, Handler, Server from kapacitor.udf import udf_pb2 import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(name)s: %(message)s') logger = logging.getLogger() class GroupBuffer(object): def __init__(self): self._points =...
from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.views import exception_handler def custom_exception_handler(exc, context): if isinstance(exc, ValidationError) and any( 'unique' in err_codes for err_codes in exc.get_codes().values()): exc....
# -*- coding: utf-8 -*- """Logistic_Regression ML.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1lMtFkIGC4EIQ5UNVEs1ob-zUOBImv7fs """ import pandas as pd df = pd.read_csv("/content/drive/MyDrive/Social_Network_Ads.csv") df x = df.iloc[:,2:4]...
test = { 'name': 'Question', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> list2 [7, 14, 21, 28, 35, 42, 49] """, 'hidden': False, 'locked': False }, { 'code': r""" >>> list_divisible(5, 19...
def trigger_breakpoint(owner=None): pass
#coding=gb18030 ''' Copyright(c) Funova FileName : UIOptimizeChecker.py Creator : pengpeng Date : 2014-12-25 11:11 Comment : ModifyHistory : ''' __version__ = '1.0.0.0' __author__ = 'pengpeng' import os import sys import re import string import csv import argparse # import yaml...
# Python practice exercises # Course: Automate the Boring Stuff with Python # Developer: Valeriy B. # Intro # Password check def password(): passwordFile = open('practice/secretPasswordFile.txt') secretPassword = passwordFile.read() yourPassword = input("Type the pasword: ") if yourPassword == secret...
""" @author - Anirudh Sharma """ def romanToInt(s: str) -> int: # Dictionary of roman numerals roman_map = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} # Length of the given string n = len(s) # This variable will store result num = roman_map[s[n - 1]] # Loop for each c...
class Solution: def XXX(self, head: ListNode) -> ListNode: if head == None or head.next== None: # 考虑空链表或者有头空链表 return head p = head # 定义一个指针,指向头结点 while True: if p.val == p.next.val: # 找到重复结点元素 p.next = p.next.next # 直接改变指向,删除该元...
from PIL import Image import pickle from torch.utils.data import Dataset, DataLoader import torch from torchvision import transforms import os class shirtDataset_train(Dataset): def __init__(self, path, transform=None): # read the h5 file self.full_data = None with open(path, 'rb') as f: ...
config.load_autoconfig(False) config.source("gruvbox.py") c.content.default_encoding = "utf-8" c.colors.webpage.prefers_color_scheme_dark = True c.content.images = False c.content.javascript.enabled = False c.content.cookies.accept = "never" c.content.webrtc_ip_handling_policy = "disable-non-proxied-udp" c.tabs.last_c...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: Ampel-core/ampel/template/ChannelWithProcsTemplate.py # License: BSD-3-Clause # Author: valery brinnel <firstname.lastname@gmail.com> # Date: 16.10.2019 # Last Modified Date: 05.01.2022 # Last Modified By: v...
# Longest Increasing Subsequence class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ # tails[i] = the smallest tail of all increasing subseq with length i+1 # for example given [4, 5, 6, 3], # tails[1] = 5 (from [4, 5...
""" Tests for application package. """
from .generator_discriminator_v1 import (StyleGAN1Discriminator, StyleGANv1Generator) from .generator_discriminator_v2 import (StyleGAN2Discriminator, StyleGANv2Generator) from .mspie import MSStyleGAN2Discriminator, MSStyleGANv2Generator...
''' Store the references to the dependent data information for a given dataProxy ''' class DataHistory(object): def __init__(self, proxy): self.proxy = proxy self.history = dict() self.updateDataRef() def updateDataRef(self): self.history[self.proxy.type] = self.proxy.getData(...
# Generated by Django 3.2 on 2021-05-10 19:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('network', '0001_initial'), ] operations = [ migrations.AddField( model_name='account', name='account_type', ...
from typing import List, NoReturn from _thread import start_new_thread import time import tempfile import os import base64 from .stargate_listen_loop import StargateListenLoop from .stargate_send_loop import StargateSendLoop from .helpers import * from .event_hook import EventHook class StargateNetwork(): """Clas...
# -*- coding: utf-8 -*- """ @author: mwahdan """ from dialognlu import BertNLU from dialognlu.readers.goo_format_reader import Reader train_path = "../data/snips/train" val_path = "../data/snips/valid" train_dataset = Reader.read(train_path) val_dataset = Reader.read(val_path) save_path = "../saved_models/joint_be...
class Capture(object): def __init__(self, client): self.client = client def create_capture(self, payment_id, **kwargs): headers = self.client._get_private_headers() payload = dict() payload.update(kwargs) endpoint = '/payments/{}/captures'.format(payment_id) ret...
number1 = 10 number2 = 20 number3 = 30 number4 = 40 number = 50 number = 505050505050 for i in range(5): print(i) gaoshenghedahaoren w s ni d laoban
############################################################################# # # VFRAME Synthetic Data Generator # MIT License # Copyright (c) 2019 Adam Harvey and VFRAME # https://vframe.io # ############################################################################# import click from vframe.settings import app...
#!/bin/python3 # Complete the separateNumbers function below. def separateNumbers(s): n = len(s) i = 1 while i <= n // 2: j = i a = int(s[:i]) flag = 1 while j < n: b = str(a + 1) if s[j:j + len(b)] != b: flag = 0 brea...
# coding=utf-8 # Copyright 2022 The HuggingFace Datasets Authors and DataLab Authors. # # 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 # # Unless required by applicable law or agreed to in wri...
#!/usr/bin/env python3 #-*- coding: iso-8859-1 -*- ############################################################################### # # This module implements the performance graph displaying HTTP interface. # If the "performance" interface has been started in config_interfaces.py, # this module is called to process HTT...