content
stringlengths
5
1.05M
from http import HTTPStatus from pathlib import Path from io import BytesIO from flask import request from ..articles.models import Article from ..articles.tags.models import Tag from .utils import login def test_create_draft_requires_authentication(client): response = client.get('/en/article/draft/new/') a...
import httpretty from tests import FulcrumTestCase class ChildRecordTest(FulcrumTestCase): @httpretty.activate def test_records_from_form_via_url_params(self): httpretty.register_uri(httpretty.GET, self.api_root + '/child_records?form_id=cf6f189e-7d50-404f-946a-835952da5083', body='{"tota...
from stack import Stack def reverse_string(input_str): stack = Stack() for i in range(len(input_str)): stack.push(input_str[i]) rev_string="" while not stack.is_empty(): rev_string+=stack.pop() return rev_string input_string = input("Enter your string: ") print(reverse_strin...
from ex110 import resumo preco = float(input('Digite o preço: ')) resumo(preco, 90, 35)
# Copyright 2015 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # License: © 2021 Achille-Tâm GUILCHARD All Rights Reserved # Author: Achille-Tâm GUILCHARD # Usage: python3 build_docker_and_launch_inference.py --workdir <DIR> --imgdir <DIR> import os import subprocess import argparse import shutil from termcolor import colored def p...
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ShareBandwidthTypeShowResp: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict):...
import functools import logging from datasets import config, load_dataset from torch.utils.data import DataLoader from transformers import default_data_collator from bsmetadata.metadata_utils import add_metadata_and_chunk_examples logger = logging.getLogger(__name__) load_dataset = functools.partial(load_dataset,...
def main(request, response): """ Returns a response with a Set-Cookie header based on the query params. The body will be "1" if the cookie is present in the request and `drop` parameter is "0", otherwise the body will be "0". """ same_site = request.GET.first("same-site") cookie_name = reque...
import streamlit as st from core.utils.financial_plots import * from core.utils.financial_data import * st.title('FORECASTING') ticker = 'AAPL' company_name = 'APPLE' close_prices = get_data(ticker) st.plotly_chart(plot_historical_price(ticker,company_name,close_prices)) st.plotly_chart(plot_return_price(ticker,co...
# Naam: Robert Rijksen # Functie: Het netjes schrijven van alle resultaten in een csv bestand waarna # al dit bestand gebruikt kon worden om alles tegelijk te inserten in mysql # in de tabel Resultaten_Blast import mysql.connector import pickle def main(): input_file = open('Volledige_blast', 'rb') # Het be...
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''...
import os import sys import site import platform from setuptools import setup from setuptools.command.install import install def post_install(): try: baseDir=site.getsitepackages() except AttributeError: baseDir=[os.path.join(site.PREFIXES[0],'lib','site-packages')] assert baseDir and 'site-packages'==baseDir...
import datetime import numpy as np from datetime import datetime from unittest import TestCase from algotrader.technical.pipeline.pairwise import Plus, Minus, Times, Divides, PairCorrelation from algotrader.trading.context import ApplicationContext class PairwiseTest(TestCase): def setUp(self): self.app_...
import pandas as pd # Permite Importar dados do Google Drive from google.colab import drive drive.mount('/content/drive') # Caminho para dados do arquivo csv csv = '/content/drive/My Drive/Colab Notebooks/Alura/aluguel.csv' dados = pd.read_csv(csv, sep = ";") dados.head(10) # Método para filtrar NaN numbers e tranf...
import sys from typing import Optional import click import requests import valohai_cli from valohai_cli.messages import warn @click.command() def update_check() -> None: data = get_pypi_info() current_version = valohai_cli.__version__ latest_version = data['info']['version'] click.echo('Your version...
from __future__ import division import numpy as np # define target list mmol=338.66 # g/mol Th_length=687. # [Aa] # target masses in GeV and number of nucleons #Hydrogen m_H=0.9389 A_H=1. Z_H=1. n_H=6.+44. # Carbon m_C=11.188 A_C=(12.*98.9+13.*1.1)/100. Z_C=6. n_C=2.+22. # lists mT_list=[m_H,m_C] AT_list=[A_H,A_C] ZT...
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 16:06:11 2015 @author: jnewman """ #Functions for initial processing of WindCube data before TI adjustment is applied. from functools import reduce def import_WC_file(filename): encoding_from='iso-8859-1' encoding_to='UTF-8' #Reads in WINDCUBE ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models import os from django.db.models import query from requests.api import head import jwt import uuid import hashlib import json from urllib.parse import urlencode import time import requests from dotenv import load_dotenv from ....
import logging import os import shutil import subprocess import pytest import salt.utils.platform log = logging.getLogger(__name__) @pytest.fixture(scope="package", autouse=True) def skip_on_tcp_transport(request): if request.config.getoption("--transport") == "tcp": pytest.skip("Multimaster under the T...
#200. 岛屿数量 class Solution: dx=[-1,1,0,0] dy=[0,0,-1,1] def numIslands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]:return 0 self.max_x=len(grid);self.max_y=len(grid[0]);self.grid=grid; self.visited=set() return sum([self.BFS(i,j)for i in range(self.max_x)f...
import os from mtcnn import MTCNN from image import draw_boxes, show_image, image_load def detection(image_name): """ Run detector on single image """ detector = MTCNN() try: return detector.detect(image_name) except ValueError: print("No sign detected") return [] def...
import pandas_datareader as pdr import pandas_datareader.data as web import datetime import requests_cache expire_after = datetime.timedelta(days=3) session = requests_cache.CachedSession(cache_name='cache', backend='sqlite', expire_after=expire_after) start = datetime.datetime(2021, 5, 1) end = datetime.datetime(2021...
import argparse import sys import time import numpy as np import pandas as pd from epics import PV from scipy.signal import peak_widths, periodogram time0 = time.time() def initArgs(): """Initialize argparse arguments. """ parser = argparse.ArgumentParser() parser.add_argument("--calc_streak", actio...
import logging import os from itertools import product from conftest_markers import DIMENSIONS_MARKER_ARGS from framework.tests_configuration.config_utils import get_enabled_tests from xdist import get_xdist_worker_id def parametrize_from_config(metafunc): """ Apply parametrization to all test functions load...
"""CLI utilities for vcspull. vcspull.cli ~~~~~~~~~~~ """ import logging import click from ..__about__ import __version__ from ..log import setup_logger from .sync import sync log = logging.getLogger(__name__) @click.group() @click.option( "--log-level", default="INFO", help="Log level (DEBUG, INFO, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import os import sys module_path = os.path.abspath(os.path.join("./src/")) if module_path not in sys.path: sys.path.append(module_path) from timeit import default_timer as timer import numpy as np import pandas as pd import torch from model.autoencoder...
# https://leetcode.com/problems/longest-common-prefix/ # Related Topics: String, Array # Difficulty: Easy # Initial thoughts: # We are going to look at each index of every string # at the same time, comparing them to their counterpart # in the first string, adding the character to our results # if all of the strings ...
#!/usr/bin/env python import torch import torch.distributed as dist import torch.multiprocessing as mp import torch.nn as nn import torch.optim as optim from torch.nn.parallel import DistributedDataParallel as DDP def run(rank): # create local model model = nn.Linear(10, 10).to('cpu') # define loss functi...
import gitlab from .aio_gitlab import AioGitlab class Gitlab(gitlab.Gitlab): def __init__( self, url, private_token, oauth_token=None, ssl_verify=True, http_username=None, http_password=None, timeout=None, ...
# 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 Nettle(AutotoolsPackage, GNUMirrorPackage): """The Nettle package contains the low-level c...
# -*- coding: utf-8 -*- from django.conf.urls import include, url from noticeboard.views import NoticeBoardView urlpatterns = [ url(r'^$', NoticeBoardView.as_view(), name='notice-board'), ]
import falcon import simplejson as json import mysql.connector import config class MenuCollection: @staticmethod def __init__(): pass @staticmethod def on_options(req, resp): resp.status = falcon.HTTP_200 @staticmethod def on_get(req, resp): cnx = mysql.connector.conn...
from hummingbot.script.script_base import ScriptBase from decimal import Decimal from hummingbot.core.event.events import ( BuyOrderCompletedEvent, SellOrderCompletedEvent ) from os.path import realpath, join s_decimal_1 = Decimal("1") LOGS_PATH = realpath(join(__file__, "../../logs/")) SCRIPT_LOG_FILE = f"{L...
# -*- coding: utf-8 -*- """ folklore.service ~~~~~~~~~~~~~~~~ This module implements service runner and handler definition interface. Available hooks: - before_api_call Hooks to be executed before api called. - api_called Hooks to be executed after api called. - api_timeout Hooks to be execu...
from pydht import Dht import pydht.magic as magic import random import numpy class Bin: def __init__(self, dht: Dht) -> None: self.dht = dht def __str__(self) -> str: return "bin" def __repr__(self) -> str: return self.__str__() def __get(self) -> int: if self.dht ==...
""" argparse boilerplate code """ import ast import argparse import textwrap from randtest import __version__ def read_data(ifname): """Read in data: assuming no header, only numbers""" with open(ifname, "r") as fobj: data = (ast.literal_eval(num.strip()) for num in fobj.readlines()) return data ...
from .Die import Die
from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenRefreshView from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class CryptoTokenObtainPairSerializer(TokenObtain...
import torch import torch.nn as nn import torch.nn.functional as F import math '''注意力机制''' # ∑softmax(W*tanh(V*h)) class SelfAttention(nn.Module): def __init__(self, hidden_size): super(SelfAttention, self).__init__() self.relation = nn.Sequential( nn.Linear(hidden_size, hidden_size//...
import dataset import librosa from torch.utils.data import DataLoader, random_split import torch import torch.nn.functional as F from utils import * import torchvision.models as models from torch.optim.lr_scheduler import StepLR from torch.utils.tensorboard import SummaryWriter import argparse import yaml from pathlib ...
'''Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character sh...
import flask as fl from flask_login import login_required import time from werkzeug.utils import environ_property from sse.eventStack import getEventStackHandler eventStackHandler = getEventStackHandler() eventStackHandler.start() #eventStackgenerator = eventStackHandler.getGenerator() sseBP = fl.Blueprint("sse",...
import sys import traceback import aergo.herapy as herapy def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) print(*args, **kwargs) def run(): try: aergo = herapy.Aergo() print("------ Export New Account -----------") aergo.new_account(skip_state=True) ...
# 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 ...
import requests import time import urllib.parse import hashlib import hmac import base64 class API(object): def __init__(self, secret='', key=''): self.url = 'https://api.kraken.com/0/' self.session = requests.Session() self.response = None self.call_rate_limit = 15 def publ...
import os import ee import geemap.foliumap as geemap import streamlit as st def app(): st.title("NAIP Imagery") st.markdown( """ NAIP: National Agriculture Imagery Program. See this [link](https://developers.google.com/earth-engine/datasets/catalog/USDA_NAIP_DOQQ) for more information. """ ...
import asyncio import time import unittest from collections import deque from typing import ( Deque, Optional, Union, ) import hummingbot.connector.exchange.binance.binance_constants as CONSTANTS from hummingbot.connector.exchange.binance.binance_order_book import BinanceOrderBook from hummingbot.connecto...
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 as # published by the Free Software Foundation. You may not use, modify or # distribu...
# coding: utf-8 """ Metal API This is the API for Equinix Metal. The API allows you to programmatically interact with all of your Equinix Metal resources, including devices, networks, addresses, organizations, projects, and your user account. The official API docs are hosted at <https://metal.equinix.com/dev...
from hashtables.hashtables import * import pytest def test_left_join(): hash1 = HashTable() hash1.add('fond', 'enamored') hash1.add('wrath', 'anger') hash1.add('diligent', 'employed') hash1.add('outfit', 'garb') hash1.add('guide', 'usher') hash2 = HashTable() hash2.add('fond', 'avers...
import json import matplotlib import pylab import sys import matplotlib.pyplot as plt train = json.loads(open(sys.argv[1]).read()) test = json.loads(open(sys.argv[2]).read()) key_maps = {} i = 0 for k, v in train.items(): if k in key_maps.keys(): continue key_maps[k] = i i = i + 1 for k, v in test...
# api/serializers from rest_framework import serializers from .models import Order class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('id', 'date', 'first_name', 'last_name', 'city', 'state', 'card', 'company', 'cost', 'status', )
# -*- coding: utf-8 -*- from __future__ import unicode_literals from wechatpy.client.api import WeChatMenu from ..models import Material, Menu, WeChatApp from .base import mock, WeChatTestCase class MenuTestCase(WeChatTestCase): def test_sync(self): """测试同步菜单""" permenant_media = "permenant_medi...
# -*- coding: utf-8 -*- """ sphinx.config ~~~~~~~~~~~~~ Build configuration file handling. :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from os import path, getenv from six import PY2, PY3, iteritems, string_types, binary_...
from django.apps import AppConfig from pickle import load import os import numpy as np import pandas as pd class ChatbotConfig(AppConfig): name = 'chatbot' #modelPath = os.path.join(projectPath,'finalized_model.sav') model = load(open("finalized_model.sav", "rb")) data_set = pd.read_pickle("main_data_...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Public Domain 2014-present MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source ...
#!/usr/bin/env python # You need jsshell and a directory with tests to run this script import os import glob import sys import optparse import types import time from collections import defaultdict import random import subprocess import re import platform try: import json except ImportError: import simplejson a...
from cmdtools.ext import command class Ping(command.Command): def __init__(self): super().__init__(name="ping") def ping(self): print("Pong!") class Say(command.Command): def __init__(self): super().__init__(name="say") def say(self, text): print(text) def error_say(self, error): print(error)
import six class CollectionScorecards(object): """ This class should be used to interact with collection scorecards. It is instantiated for you as an attribute of the :class:`proknow.Collections.CollectionItem` class. """ def __init__(self, collections, collection): """Initializes the Co...
# coding: utf-8 ''' @author: eju ''' import numpy as np import PIL import sys import cv2 sys.path.insert(1, 'D:\\program\\pytorch-layoutnet') import pano_lsd_align cutSize = 320 fov = np.pi / 3 xh = np.arange(-np.pi, np.pi*5/6, np.pi/6) yh = np.zeros(xh.shape[0]) xp = np.array([-3/3, -2/3, -1/3, 0/3, 1/3, 2/3, -3...
from __future__ import division import math import os import sys import time import numpy as np import scipy.stats from scipy.optimize import curve_fit from math import log10 import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy import pi as nombrepi ##### Lecture du fichier de donnees (frequences/Inte...
# # basicMLpy.cross_validation module import numpy as np import itertools from .utils import check_for_intercept, split_indices class CrossValidation: """ Class that performs the cross validation given a certain function. Methods: fit(X,y) -> Performs the cross validation algorithm on t...
# Copyright 2022 The KerasCV 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# # Copyright 2015 Naver Corp. # # 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...
import logging import numpy as np import tensorflow as tf from keras.datasets import cifar10 from keras.utils import np_utils logger = logging.getLogger(__name__) def _create_tf_dataset(x, y, batch_size): return tf.data.Dataset.zip((tf.data.Dataset.from_tensor_slices(x), tf.data.D...
'''This is a macro for ccpn analysis. The only thing this macro does is compile c extentions necesarry for Malandro. If you downloaded a 'pre-compiled' version of Malandro you don't have to run this macro. If you do want to compile the c code (again) you can use this macro. The reason this is written in...
import os import sys from dotenv import load_dotenv load_dotenv() def get_env_name() -> str: env_name: str = os.getenv('ENV_NAME', 'dev') script_name: str = sys.argv[0] if script_name.startswith('tests/'): env_name = 'test' return env_name class Config: DATABASE_URL: str = os.environ...
# 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...
#!/usr/bin/env python # Copyright 2021 Citrix Systems, Inc. All rights reserved. # Use of this software is governed by the license terms, if any, # which accompany or are included with this software. import logging import re class PILex(object): """ Class to parse Advanced expressions. """ @static...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 19 12:21:06 2019 @author: mishugeb """ from SigProfilerExtractor import subroutines as sub import numpy as np import pandas as pd import SigProfilerExtractor as cosmic import os def decompose(signatures, activities, samples, output, signature_...
from .video import VideoEntity ENTITY_CLASSES = [VideoEntity] ENTITY_TYPE_CHOICES = [ (VideoEntity.name, 'Video'), ] ENTITY_TYPE_NAME_TO_CLASS = { k.name: k for k in ENTITY_CLASSES }
# # This file is 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 # distr...
import net_arch.mobilenet_v3 import tensorflow as tf def EfficientNetB3(shape): model = tf.keras.applications.EfficientNetB3( input_shape=shape, classifier_activation=None, include_top=False, weights='imagenet') return model def MobileNetV2(shape): model = tf.keras.applic...
from django.utils import simplejson from django.test.client import Client from correx.tests import ChangeTestCase from correx.models import Change, ChangeType from django.db.models import get_model from django.contrib.contenttypes.models import ContentType class CorrexViewTests(ChangeTestCase): def setUp(self): ...
#! /usr/bin/python import os import re import sys import ssl import json import time import uuid import copy import socket import urllib import Cookie import thread import urllib import base64 import httplib import datetime import traceback import mimetypes import multiprocessing import SimpleHTTPSServer import consta...
class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.tot = 0 self.size = size self.q = [] def next(self, val): """ :type val: int :rtype: float """ ...
"""Checks import position rule""" # pylint: disable=unused-import import os try: import ast except ImportError: def method(items): """docstring""" value = 0 for item in items: value += item return value import sys
"""Contrastive Explanation [WIP]: pedagogical (model-agnostic) method for persuasive explanations based on the user's outcome of interest. Marcel Robeer (c) 2018 - 2019 TNO, Utrecht University Todo: * Add more domain_mappers (image, text) * Add more methods to obtain a foil * Define new strategies for Dec...
import unittest # Importing the unittest module from user import User # Importing the User class class TestUser(unittest.TestCase): """Test Class for defining test cases for user class behaviours Args: unittest.TestCase: TestCase class that helps in creating test cases """ def setUp(self...
from mesh.generic.nodeHeader import createHeader, packHeader, headers from struct import pack class TestNodeHeader: def setup_method(self, method): self.nodeHeaderIn = ['NodeHeader', [3, 4, 5]] self.minimalHeaderIn = ['MinimalHeader', [3]] self.sourceHeaderIn = ['SourceHeader', [3, 4]...
# -*- coding: utf-8 -*- # # Copyright 2020 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...
_base_ = [ '../_base_/models/upernet_swin.py', '../_base_/datasets/ade20k.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] model = dict( backbone=dict( embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, ape=False, ...
from django.core.management.base import BaseCommand, CommandError from estatisticas_facebook.pages.models import * from estatisticas_facebook.posts.models import getPostInfo from estatisticas_facebook.comments.models import getCommentInfo from estatisticas_facebook.reactions.models import getReactionInfo class Comman...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 18-7-10 上午10:22 # @Author : Tom.Lee # @File : manager.py # @Product : PyCharm # @Docs : # @Source : import sys from flaskapp import app from flaskapp import manager if __name__ == '__main__': # 初始化 ...
import os from conans import ConanFile, tools class FastNoise(ConanFile): name = "fastnoise" version = f"1.0.1" license = "MIT" url = "https://github.com/Auburn/FastNoise" description = "coherent noise-generating library for C++" topics = ("noise") settings = "os", "arch", "compiler", "bui...
from molsysmt._private.exceptions import * from molsysmt._private.digestion import * def to_file_pdb(item, atom_indices='all', structure_indices='all', output_filename=None, check=True): if check: digest_item(item, 'string:pdb_id') atom_indices = digest_atom_indices(atom_indices) structur...
import wrapped_flappy_bird as game import numpy as np import matplotlib.pyplot as plt import time import os import glob import h5py t0 = time.time() ALPHA = .7 # learning rate GAMMA = 0.95 # discount factor # EPISODES = 100_000 # 17 minute run time # EPISODES = 600_000 # 36 minute run time # EPISODES = 600_000 # 93 mi...
import turtle import pandas screen = turtle.Screen() screen.title("U.S. States Game") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) data = pandas.read_csv("50_states.csv") all_states = data.state.to_list() guessed_states = [] while len(guessed_states) < 50: answer_state = screen.text...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def checkSubTree(self, t1: TreeNode, t2: TreeNode) -> bool: return self.preorder_traversal(t1, t2) def preorder_traversal(self, p: Tr...
"""Load a yaml resource from a python package.""" import pkgutil import types import yamlsettings from yamlsettings.extensions.base import YamlSettingsExtension class PackageExtension(YamlSettingsExtension): """Load a yaml resource from a python package. Args: resource: The resource to load from the p...
# -*- coding: utf-8 -*- from collections import defaultdict class Annotation(object): """This class represents an annotation.""" def __init__(self, id, representation, spans, labels=()): """ Create an annotation object. :param id: (string) The id of the current annotation. :p...
import pytest from src.graph.graph import Graph from src.graph.concomp import concomp0, concomp1, concomp2 CONNECTED_COMPONENTS = [concomp0, concomp1, concomp2] @pytest.mark.parametrize("concomp", CONNECTED_COMPONENTS) def test_one_edge(concomp): msg = "{} failed".format(concomp.__name__) g = Graph() ...
{'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'bgTemplate', 'title':'Standard Template with File->Exit menu', 'size':(400, 300), 'style':['resizeable'], 'menubar': {'type':'MenuBar', 'men...
from uuid import UUID from pydantic import BaseModel class LaaApplication(BaseModel): reference: str | None id: UUID | None status_code: str | None description: str | None status_date: str | None effective_start_date: str | None effective_end_date: str | None contract_number: str | No...
# -*- coding:utf-8 -*- from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys driver = webdriver.PhantomJS(executable_path="./phantomjs-2.1.1-macosx/bin/phantomjs") driver.get("http://baidu.com/") driver.find_element_by_id("kw").send_keys(u"长城") sleep(10) driver.find_ele...
from decimal import Decimal from typing import Iterable, Optional, TypeVar from stock_indicators._cslib import CsIndicator from stock_indicators._cstypes import List as CsList from stock_indicators._cstypes import Decimal as CsDecimal from stock_indicators._cstypes import to_pydecimal from stock_indicators.indicators....
import logging import torch import wrapt import tqdm from .recording import Recorder logger = logging.getLogger('pystematic.torch') class DDPModuleProxy(wrapt.ObjectProxy): """Delegates any unknown getattr calls to the underlying module. Makes the DDP module completely transparent. """ def __getatt...
import numpy as np from numpy import arange, sin, pi, float, size import matplotlib from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure from matplotlib.collections import LineCollection from matplotlib.widgets import Button import Tkinter as Tk from spike_sort.ui i...
#!/usr/bin/python ''' Program: This is a standard code shows the style of my program. Usage: std_code.py Editor: Jacob975 20170216 ################################# update log 20170206 alpha 1 It can run properly. 20170216 alpha 2 Make code more efficient, add a link code to find darks and subd...