content
stringlengths
0
894k
type
stringclasses
2 values
# Generated by Django 3.2.7 on 2021-09-09 18:17 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('auctions', '0008_add_expiry_alter_category_on_listing'), ] operations = [ migrations.A...
python
import pytest from astropy.io import fits import numpy as np from numpy.testing import assert_array_equal from lightkurve import search_lightcurve from lightkurve.io.qlp import read_qlp_lightcurve from lightkurve.io.detect import detect_filetype @pytest.mark.remote_data def test_qlp(): """Can we read in QLP lig...
python
__version__ = 0.1 import os import logging import configparser import daiquiri import daiquiri.formatter _ROOT = os.path.dirname(os.path.abspath(__file__)) _CONFIG = os.path.join(_ROOT, 'config.ini') FORMAT = ( "%(asctime)s :: %(color)s%(levelname)s :: %(name)s :: %(funcName)s :" "%(message)s%(color_stop)...
python
import numpy as np from ._CFunctions import _Cgcpm import DateTimeTools as TT def GCPM(x,y,z,Date,ut,Kp=1.0,Verbose=False): ''' Calculates the Global Core Plasma Model at some given position(s) and time(s). Inputs ====== x : float scalar or array of x_SM (Solar Magnetic coordinates) component of the posit...
python
# Generated by Django 3.1.5 on 2021-01-23 02:13 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Cliente', fields=[ ('id', models.AutoField(...
python
# Natural Language Processing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('googleplaystoreuserreviews.csv') dataset.dropna(inplace=True) X = dataset.iloc[:,0].values # Cleaning the texts import re import nltk nltk.do...
python
from linebot.models import TextSendMessage, FlexSendMessage from app.config import CELEBRATING_TARGET from app.crud.leaderboard import update_amount, get_list_of_amount from . import line_bot_api, exception_handler @exception_handler def celebrating_birthday(line_event): group_id = line_event.source.group_id ...
python
#!/usr/bin/env python3 import unittest import timeout_decorator from challenges.codility.lessons.q019.stone_wall_v001 import * MAX_N = 100000 MIN_ELEMENT = 1 MAX_ELEMENT = 1000000000 class StoneWallTestCase(unittest.TestCase): def test_description_examples(self): self.assertEqual(7, solution([8, 8, 5, 7, 9...
python
# Create CSS using GitHub's colour scheme from a JSON source like (https://github.com/doda/github-language-colors) import json with open('github_colors.json') as colors: with open('github_colors.css', 'w') as css: m = json.loads(colors.read()) for lang in m: color = m[lang] lang_saf...
python
TRAINING_DATA = [ ( "i went to amsterdem last year and the canals were beautiful", {"entities": [(10, 19, "TOURIST_DESTINATION")]}, ), ( "You should visit Paris once in your life, but the Eiffel Tower is kinda boring", {"entities": [(17, 22, "TOURIST_DESTINATION")]}, ), ...
python
""" @leofansq Basic function: show_img(name, img): Show the image find_files(directory, pattern): Method to find target files in one directory, including subdirectory Load function: load_calib_cam2cam(filename, debug=False): Only load R_rect & P_rect for need load_calib_lidar2cam(filename, debug=Fal...
python
from dotenv.main import find_dotenv import tweepy import time import random from dotenv import load_dotenv import os import requests load_dotenv(find_dotenv()) API_KEY = os.getenv('API_KEY') API_SECRET_KEY = os.getenv('API_SECRET_KEY') ACCESS_TOKEN = os.getenv('ACCESS_TOKEN') ACCESS_TOKEN_SECRET = os.getenv('ACCESS_TO...
python
# Copyright 2017 Hosang Yoon # # 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 ...
python
from .mlp_score_head import MLPScoreHead __all__ = [ 'MLPScoreHead' ]
python
import pytest from game import seed_grid, parse_args, print_grid, get_neighbours, live_or_die def test_parser(): with pytest.raises(BaseException): parse_args(["-x", "-y", "-c"]) args = parse_args(["-x 10", "-y 20", "-c (1,1),(2,2),(5,4)"]) assert args.x == 10 assert args.y == 20 assert a...
python
# -*- coding: utf-8 -*- import scrapy import pandas as pd class FirstSpider(scrapy.Spider): name = 'first' def start_requests(self): urls = ['https://www.worldometers.info/coronavirus/#countries'] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): table = pd....
python
from future import standard_library standard_library.install_aliases() import datetime import json import os import re import time from collections import namedtuple, defaultdict from urllib.parse import urlparse, urljoin from io import BytesIO import flask import sqlalchemy.sql from flask import abort from flask impo...
python
import os from datetime import datetime import numpy import xarray as xr from esdl.cate.cube_gen import CateCubeSourceProvider class OzoneTemisProvider(CateCubeSourceProvider): def __init__(self, cube_config, name='ozone_temis', dir=None, resampling_order=None): super().__init__(cube_config, name, dir, ...
python
# # This example demonstrates using Lark with a custom lexer. # # You can use a custom lexer to tokenize text when the lexers offered by Lark # are too slow, or not flexible enough. # # You can also use it (as shown in this example) to tokenize streams of objects. # from lark import Lark, Transformer, v_args from lar...
python
import json from .errors import JrsNodeNotFound from .refs_resolver import RefsResolver class Context(object): def __init__(self): self.schemas = {} self.nodes = {} self.refsResolver = RefsResolver(self) def addSchema(self, schema): self.schemas[schema.id] = schema def ...
python
# Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino. # Return the number of pairs(i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent t...
python
from ralph.accounts.api import RalphUserSimpleSerializer from ralph.api import RalphAPIViewSet, router from ralph.assets.api.serializers import RalphAPISerializer from ralph.sim_cards.models import CellularCarrier, SIMCard, SIMCardFeatures class CellularCarrierSerializer(RalphAPISerializer): class Meta: m...
python
"""Test runway.config.components.runway._test_def.""" # pylint: disable=no-self-use,protected-access # pyright: basic import pytest from pydantic import ValidationError from runway.config.components.runway import ( CfnLintRunwayTestDefinition, RunwayTestDefinition, ScriptRunwayTestDefinition, YamlLintR...
python
""""@package This package enables the research group usage for the database. """ from src.models.employee import EmployeeDataAccess class ResearchGroup: """ This class defines a research group """ def __init__(self, name, abbreviation, logo_location, description_id, address, telephone_number, ...
python
# MIT License # # Copyright (C) IBM Corporation 2018 # # 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, including without limitation the # rights to use, copy, modify, merge...
python
import jimi, requests def reloadModule(module): # Apply system updates clusterMembers = jimi.cluster.getAll() for clusterMember in clusterMembers: headers = { "x-api-token" : jimi.auth.generateSystemSession() } requests.get("{0}{1}system/update/{2}/".format(clusterMember,jimi.api.base,jimi....
python
""" A coordinate transformation module. Made as a separate chunk of code to allow for easier implementation of newer/better reference frame translation methods. Generally used to project a trajectory in ECEF coordinates (eg lat/lon) into a projected reference system. ##just getting started! """ #collect dependenci...
python
from __future__ import absolute_import from six.moves.urllib.parse import urlparse from django.utils.translation import ugettext_lazy as _ from django import forms from sentry import http from sentry.web.helpers import render_to_response from sentry.identity.pipeline import IdentityProviderPipeline from sentry.identi...
python
''' Created by Sidhant Nagpal Feb 1, 2018 ''' from matplotlib import pyplot as plt from random import shuffle import numpy as np import json plt.figure(figsize=(12,6)) data = json.load(open('data.json')) a = [(k,v) for k, v in data.iteritems()] for i in xrange(2,len(a)): if a[i-2]>a[i] and a[i-2]>a[i-1]: a[i-2]...
python
# -*- coding: utf-8 -*- """Simple ClaSP test.""" __author__ = ["patrickzib"] __all__ = [] import numpy as np from sktime.annotation.clasp import ClaSPSegmentation from sktime.datasets import load_gun_point_segmentation def test_clasp_sparse(): """Test ClaSP sparse segmentation. Check if the predicted chan...
python
from string import ascii_uppercase from tkinter import * from analyst import BoardAnalyst from board import Board, Color class MainMenuWindow: """ A class that represents a Main Menu. Can branch to a NameWindow, to an AboutWindow or to a GoodByeWindow On button 1: Branch to a NameWindow, which will event...
python
from typing import List class Solution: def plusOne(self, digits: List[int]) -> List[int]: carry = (digits[-1] + 1) > 9 digits[-1] = (digits[-1] + 1) % 10 for i in reversed(range(len(digits) - 1)): temp = carry carry = (digits[i] + carry > 9) digits[i] ...
python
# Import libraries from collections import Counter, OrderedDict from itertools import chain from more_itertools import unique_everseen import numpy as np import pandas as pd import random import tensorflow as tf from keras import models import warnings import functools import operator warnings.filterwarnings("ignore")...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Define linear function approximator. Dependencies: - `pyrobolearn.models` - `pyrobolearn.states` - `pyrobolearn.actions` """ from pyrobolearn.approximators.approximator import Approximator from pyrobolearn.models.basics.polynomial import Polynomial, PolynomialFunction ...
python
import requests from bs4 import BeautifulSoup server_address = 'http://127.0.0.1:5000' def getElementById(html, theId): soup = BeautifulSoup(html, 'html.parser') r = soup.find(id=theId) return r def register(uname, pword, twofa, session=None): url = server_address + '/register' if session is None...
python
import random import gym import numpy as np M = 5.0 T = 1.0 GOAL = 0.001 class WeightEnv(gym.Env): metadata = {'render.modes': ['human']} def __init__(self): super(WeightEnv, self).__init__() self.reward_range = (-float('inf'), 0.0) self.state = np.array([0, 0, 0]) # position, velocit...
python
PATTERN = r"(doge|shib)" TRANSFORMER_MODEL = 'cardiffnlp/twitter-xlm-roberta-base-sentiment' SENTIMENT_MAPPING = { 'Positive' : 1, 'Neutral' : 0, 'Negative' : -1 }
python
"""Two Number Sum Write a function that takes in a non-empy array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the function should re...
python
from .bmp180 import bmp180
python
"""Pull git repos and update the local schemes and templates files """ import os import sys import shutil import asyncio from .shared import get_yaml_dict, rel_to_cwd, verb_msg, compat_event_loop def write_sources_file(): """Write a sources.yaml file to current working dir.""" file_content = ( "schemes: " "http...
python
# This module is derived (with modifications) from # https://github.com/GoogleCloudPlatform/tensorflow-without-a-phd/blob/master/tensorflow-rl-pong/trainer/task.py # Special thanks to: # Yu-Han Liu https://nuget.pkg.github.com/dizcology # Martin Görner https://github.com/martin-gorner # Copyright 2019 Leigh Johnson #...
python
# coding: utf-8 """ Project Euler problem #40. """ def problem(): u""" Solve the problem. An irrational decimal fraction is created by concatenating the positive integers: 0.12345678910(1)112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn repres...
python
# Author: Mathurin Massias <mathurin.massias@gmail.com> # License: BSD 3 clause import os from pathlib import Path from bz2 import BZ2Decompressor import numpy as np from scipy import sparse from download import download from sklearn import preprocessing from sklearn.datasets import load_svmlight_file NAMES = { ...
python
# Create class for weather module # Imports import requests import json import datetime import time import os import sys from dotenv import load_dotenv # Class class WeatherModule: """ Weather module class """ # Initialize def __init__(self, city): """ Initialize WeatherModule c...
python
""" AWS Lambda entrypoint and Intent router """ from __future__ import print_function import json import logging import strings from manage_data import get_player_info from utility import ( get_household_and_person_ids, determine_welcome_message ) from play_new_game import play_new_game from handle_answer_reque...
python
# Generated by Django 3.1.7 on 2021-03-12 16:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('recruiter', '0023_auto_20210312_2144'), ] operations = [ migrations.AddField( model_name='recruiter', name='overall_...
python
"""Search views init.""" from src.views.index import show_index
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Created on Mar 31, 2018 @ Author: Frederich River ''' import atexit import os import signal import sys import time from apscheduler.executors.pool import ThreadPoolExecutor from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from env import LOG_FILE, PID_FI...
python
#!/usr/bin/env python # coding: utf-8 from argparse import ArgumentParser import pandas as pd import pyprojroot LOSS_FUNC_ML_TASK_MAP = { 'CE-largest': 'single-label, largest', 'CE-random': 'single-label, random', 'BCE': 'multi-label', } def main(source_data_root, rm_corr_csv_path, tes...
python
name = 'controllers' from .constant_controller import ConstantController from .controller import Controller from .energy_controller import EnergyController from .fb_lin_controller import FBLinController from .linear_controller import LinearController from .lqr_controller import LQRController from .pd_controller import ...
python
from message_bot.database.engines.base import BaseEngine from message_bot.database.engines.gsheet import GsheetEngine from message_bot.database.engines.json import JSONEngine
python
array = input("Enter the string here: ").split() array.sort(key=len) print(array)
python
import unittest from oletools.common.clsid import KNOWN_CLSIDS class TestCommonClsid(unittest.TestCase): def test_known_clsids_uppercase(self): for k, v in KNOWN_CLSIDS.items(): k_upper = k.upper() self.assertEqual(k, k_upper)
python
import logging import os def setup_logger(log_directory='', log_filename="astronomaly.log"): """ Ensures the system logger is set up correctly. If a FileHandler logger has already been attached to the current logger, nothing new is done. Parameters ---------- log_directory : str, optional ...
python
from unittest.mock import patch import pytest from peerscout.utils.bq_data_service import ( load_file_into_bq, ) import peerscout.utils.bq_data_service \ as bq_data_service_module @pytest.fixture(name="mock_bigquery") def _bigquery(): with patch.object(bq_data_service_module, "bigquery") as mock: ...
python
import click from jinja2 import PackageLoader from dgen import jinja env = jinja.create_env(PackageLoader(package_name=__package__)) TEXT_FIELD = """ %s = models.TextField( verbose_name=_('%s') )""" INTEGER_FIELD = """ %s = models.IntegerField( verbose_name=_('%s') )""" BOOLEAN_FIE...
python
from cocos.layer import Layer, director from cocos.menu import Menu, CENTER, ToggleMenuItem, MenuItem from cocos.scene import Scene from app import gVariables import sceneGenerator class CustomPauseScene(Scene): def __init__(self, gScene): super(CustomPauseScene, self).__init__() #ADD ALL TO MAIN L...
python
#%% import numpy as np from scipy import sparse from scipy.linalg import block_diag #%% def sdp_ymat( lines, Ybus ): nbus = Ybus.shape[0] nline = len(lines) # busset = np.arange(0, nbus) # lineset = np.arange(0, nline) #%% def e(k): return np.eye(nbus)[:, k][np.newaxis] # size of e(k): (...
python
while True: try: height = input("Height: ") while 9 > int(height) > 1: i = 0 while i <= int(height): a = int(height) - i print(a * ' ' + "#" * i) i = i + 1 exit() except ValueError: print("invalid numb...
python
from typing import Dict, List, Tuple import pygame import pygame_gui from pygame.constants import TEXTINPUT from pygame.event import EventType from pygame_gui.core import UIContainer from pygame_gui.elements import UIButton from pygame_gui.elements.ui_label import UILabel from pygame_gui.ui_manager import UIManager i...
python
# coding: utf-8 from __future__ import ( absolute_import, print_function, unicode_literals, ) from pydocx.models import XmlModel, XmlCollection from pydocx.openxml.vml import Shape, Rect class Picture(XmlModel): XML_TAG = 'pict' children = XmlCollection(Shape, Rect)
python
from typing import Union from pyppeteer.browser import Browser __all__ = ("BrowserContext",) class BrowserContext: def __init__(self) -> None: self._browser: Union[Browser, None] = None def set(self, browser: Browser) -> None: self._browser = browser def get(self) -> Union[Browser, Non...
python
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ This script controls the head motors Altered by Johannes Sommerfeldt """ import os import sys import redis # ROS 2 Imports import rclpy from rclpy.node import Node from std_msgs.msg import Float32, String, Int16, Bool from head.msg import MotorPosition from syste...
python
from hapServer import * import hapBack as hb import time import sys hs = hapserver() if sys.argv[1] == "1": hb.a1(int(sys.argv[2]),hs) time.sleep(1) if sys.argv[1] == "2": hb.a2(int(sys.argv[2]),hs) time.sleep(1) if sys.argv[1] == "3": hb.r1(int(sys.argv[2]),hs) time.sleep(1) if sys.argv[1] == "4": h...
python
# Copyright 2018 Capital One Services, 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...
python
# This sample is used in conjunction with protocolModule4.py. from typing import Protocol, TypeVar Y = TypeVar("Y", contravariant=True) class Fn(Protocol[Y]): def __call__(self, y: Y) -> None: ... def x(x: Fn[int]) -> None: print(x)
python
#!/usr/bin/env python3 # Create C/C++ code for two lookup tables. import math # Size of static tables. kTableSize = 4096 # Scale factor for float arg to int index. kScaleFactor = 256.0 print("// Generated code with lookup tables") print('#include "functions.h"') print("namespace tesseract {") print("const double T...
python
class FactorProfile: types = { 'question': str, 'questionText': str, 'answer': str, 'phoneNumber': str, 'credentialId': str } def __init__(self): # unique key for question self.question = None # str # display text for question self...
python
""" Scheduler Service for starting flow :license: MIT """ import calendar import datetime import json import os from src.dependencies.dependency_typing import (PynamoDBCheckIn, PynamoDBConsultant, PynamoDBCustomers,...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 Christoph Reiter # # 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, including # without limitation the right...
python
#!/usr/bin/env python ################################################################################ # Created by Oscar Martinez # # o.rubi@esciencecenter.nl # #######################################################...
python
#! /usr/bin/env python from __future__ import print_function import logging logging.getLogger(__name__).setLevel(logging.INFO) import os,sys,time #import yaml import signal from snowboy import snowboydecoder interrupted = False def signal_handler(signal, frame): global interrupted interrupted = True def in...
python
# 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...
python
import os import unittest import numpy as np import pandas as pd from cgnal.core.data.model.ml import ( LazyDataset, IterGenerator, MultiFeatureSample, Sample, PandasDataset, PandasTimeIndexedDataset, CachedDataset, features_and_labels_to_dataset, ) from typing import Iterator, Generat...
python
"""CheckingProxy derived from jsonrpc.proxy due to subclassing problems w/getattr. Converts service errors into ServiceError exceptions, otherwise call returns the jsonrpc "result" field. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import import sys impo...
python
import sys from PyQt5.QtWidgets import QAction,QHBoxLayout,QWidget,QApplication,QMainWindow from PyQt5.QtGui import QIcon class QToolBarDemo(QMainWindow): def __init__(self): super(QToolBarDemo, self).__init__() #设置窗口大小 self.resize(400, 150) #设置窗口标题 self.setWindowTitle("QTo...
python
from django.contrib.auth.base_user import AbstractBaseUser from django.db import models from django.db.models import Manager class EqualizeMixin: equal_fields = () def __eq__(self, other): equal_fields = self._get_equal_fields() for field in equal_fields: if getattr(self, field) !...
python
""" Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan...
python
#!/usr/bin/env python3 # coding=utf8 """\ Our Standards Jill-Jênn Vie et Christoph Dürr - 2020 """ from sys import stdin def readint(): """ function to read an integer from stdin """ return int(stdin.readline()) def readstr(): """ function to read a string from stdin """ return stdin...
python
import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go from ECAgent.Core import Model # Can be used to customize CSS of Visualizer external_stylesheets = ['https://rawgit.com/BrandonGower-Winter/ABMECS/master/Assets/VisualizerCustom.css', ...
python
"""Test ``X-Forwarded-For`` middleware.""" from __future__ import annotations from ipaddress import _BaseNetwork, ip_network from typing import Dict, List, Optional import pytest from fastapi import FastAPI, Request from httpx import AsyncClient from safir.middleware.x_forwarded import XForwardedMiddleware def bu...
python
# --------------------------------------------------------------------------- # MTDA Client # --------------------------------------------------------------------------- # # This software is a part of MTDA. # Copyright (c) Mentor, a Siemens business, 2017-2020 # # -------------------------------------------------------...
python
"""Standard modules""" import sys import numpy as np import ldp import matplotlib.pyplot as plt class SimMesh(object): def __init__(self, mesh, neg, sep, pos): self.mesh = mesh self.neg = neg self.pos = pos self.sep = sep class SimData(object): def __init__(self, ce, cse, phi...
python
# -*- coding: utf-8 -*- #""" # Created on Mon Oct 28 15:12:43 2013 # #@author: laure # # BROKEN : Doesn't work ########################## #""" # import sys # # import soma_workflow.constants as constants # from soma_workflow.test.job_tests.job_tests import JobTests # from soma_workflow.configuration import LIGHT_MODE ...
python
from matplotlib import colors import matplotlib.pyplot as plt from copy import deepcopy import numpy as np import matplotlib.gridspec as gridspec from scipy.interpolate import interp1d class TrianglePlot(object): _default_contour_colors = [(colors.cnames['darkslategrey'], colors.cnames['black'], 'k'), ...
python
from django.apps import AppConfig class CoinapiConfig(AppConfig): name = 'coinapi'
python
import os import torch import numpy as np import torch.nn as nn # import torch.nn.functional as F import torch.distributed as dist import datetime import pandas as pd from asyncfeddr.utils.models import SimpleNetMNIST, SimpleNetFEMNIST from asyncfeddr.utils.serialization import ravel_model_params, unravel_model_param...
python
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # 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...
python
"""Utility functions for commissioning tests.""" # STDLIB import os import sys from collections import Iterable # THIRD-PARTY import numpy as np import pytest from numpy.testing import assert_allclose # ASTROLIB try: import pysynphot as S from pysynphot.spparser import parse_spec as old_parse_spec except Imp...
python
# -*- coding: utf-8 -*- """ Created on Thu Nov 28 19:11:30 2019 @author: wenbin """ """ 实现一个数据结构,使其具有以下方法:压栈,弹栈,取栈顶元素,判断栈是否为空以及获取栈中元素个数. 链表实现stack """ class LNode: def __init__(self , x = 0 , y = None): self.Data = x self.Next = y class MyStack: def __init__(self): ...
python
# Digitar algorithm for plucked-string synthesis # Demo with "Frere Jacques" # Abe Karplus, 2016 import wave import array sampling = 48e3 # Hz bpm = 100 notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} def notepitch(n): step = notenames[n[0]] octind = 2 if n[1] == '#': step +...
python
from django.test import SimpleTestCase from corehq.apps.app_manager.xpath import ( CaseSelectionXPath, CaseTypeXpath, LedgerdbXpath, XPath, ) class XPathTest(SimpleTestCase): def test_paren(self): xp = XPath('/data/q1') self.assertEqual('/data/q1', xp.paren()) self.assert...
python
__version__ = "1.2.0" from .utils import drawLandmark_multiple, detection_adapter, bbox_from_pts, Aligner from .fast_alignment import * from .face_detection import * from .face_reconstruction import *
python
import unittest class TestTransition(unittest.TestCase): @unittest.skip("") def test___init__(self): # transition = Transition(type_, element, nuclear_charge, charge, wavelength, temperature, density, pec) assert False # TODO: implement your test here @unittest.skip("") def test_energy...
python
from django.test import TestCase from meadow.models import Book from meadow.tests.factories.book import BookFactory from meadow.utils.book_searcher import book_preview, search_by_title class BookPreviewTestCase(TestCase): def test_book_preview_book_exists(self): some_book = BookFactory() result ...
python
def f(): pass a = f() b = f() c = f() str
python
from itertools import islice from queue import Queue from typing import Iterator import numpy as np def limited_queue_iterator(queue: Queue, max_num_elements: int) -> Iterator: """Construct an iterator from a queue. The iterator will stop after max_num_elements.""" for _ in range(max_num_elements): y...
python
""" This module illustrates code that accepts a single integer, a character, and an uppercase flag as positional arguments and print this character 'n' amount of times. If the uppercase flag is set to true, it prints uppercased. """ import argparse def main(character, number): print (character * number) if __name...
python
""" Export module """ import os import os.path import sqlite3 import sys import regex as re # pylint: disable=E0611 # Defined at runtime from .index import Index class Export: """ Exports database rows into a text file line-by-line. """ @staticmethod def stream(dbfile, output): """ ...
python
#!/usr/bin/env python import argparse import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional try: import comet_ml use_tensorboard = False except ImportError: use_tensorboard = True import datasets import numpy as np import torch import tran...
python