content
stringlengths
5
1.05M
"""Add decidotron tables Revision ID: 2a1107018fad Revises: ed6cbcd62bee Create Date: 2019-02-16 17:41:15.330449 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '2a1107018fad' down_revision = 'ed6cbcd62bee' branch_labels = None depends_on = None def upgrade():...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd from datetime import datetime, timedelta import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as tck import matplotlib.font_manager as fm import math as m import matplotlib.dates as mdates im...
# Copyright (c) 2019 Capital Fund Management # SPDX-License-Identifier: MIT import logging import os import threading class LogPipe(threading.Thread): def __init__(self, level): """Setup the object with a logger and a loglevel and start the thread """ threading.Thread.__init__(se...
config = { "play_in_spanish": "2", "play_with_symbols": "2", "play_again": "Y", "human_vs_human": "1", "human_vs_comp": "2", }
import copy import numpy as np import pandas as pd import seaborn as sns class GreedyBanditAgent(object): def __init__(self, epsilon=0.1, learning_rate=0.5, action_space=10, q0=0): self.action_space = action_space self.epsilon = epsilon self.learning_rate = learning_rate self.acti...
""" Experiments performed in Chen et al.: BDA-PCH, figure 2, with different parameter splitting. Link to the reference: https://arxiv.org/pdf/1802.06502v2.pdf """ from collections import OrderedDict from os import path import torch from bpexts.hbp.crossentropy import HBPCrossEntropyLoss from bpexts.optim.cg_new...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
# -*- coding: utf-8 -*- """ $ python copyBinary.py source copy copy source to copy name """ import sys if __name__ == "__main__": with open(sys.argv[1],'rb') as f: with open(sys.argv[2],'wb') as g: for line in f: g.write(line)
# This solution involves the multinational coefficient function, which is defined as follows. # For a multinomial such as (x1 + x2 + x3 …)^n, the coefficient of the element of the product with the exponent n1 for x1, # n2 for x2 and so on is equal n!/(n1! * n2! *n3! …). from sys import stdin import math while True: ...
#!/usr/bin/env python import requests from requests.auth import HTTPBasicAuth import pprint pp = pprint.PrettyPrinter(indent=4) def get_shareable_fingerprints(base_url, user, password): fps = [] resp = requests.get('http://localhost:8000/fingerprints?q=shareable:true', auth=HTTPBasicAuth('ddosdb', 'ddosdbddos...
import setuptools def readme(): with open('README.md') as f: README = f.read() return README setuptools.setup( name="PFX", version="1.0.1", author="Prashanth Umapathy", author_email="ujprashant@gmail.com", description="PFX or Python-Effects is a PyPI package for adding ...
from typing import List import click from click import echo from spellsync.dictionary import all_dictionary_classes from spellsync.dictionary.base import Dictionary from spellsync.dictionary.common import CommonDictionary def find_dictionaries() -> List[Dictionary]: """Return all dictionaries that can be found ...
#!/usr/bin/python import sys, marisa_trie, random, json from array import array import re, os N = 1E6 def create_trie(): """ This is a helper function to create a file containing the key_id of every Word in the trie word list. """ if len(sys.argv)<2: print "USAGE: %s dictionary_fl trie_fl [out_fl]"...
/usr/lib64/python3.4/copyreg.py
import pygame, math, gv from ast import literal_eval def drawWords(): if gv.playing: playingDisplay = gv.font.render("Playing", 1, pygame.Color("green")) else: playingDisplay = gv.font.render("Not Playing", 1, pygame.Color("red")) objectDisplay = gv.font.render(str(len(gv.objects.objects)...
#!/usr/bin/env python3 import serial import datetime import time import pymongo import Adafruit_DHT import sys import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont class sensorsIO(): def __init__(self): self.pm_device = '/dev/tty...
import csv from django.db import migrations BOOK_NAME_EN = "Tobit" BOOK_NAME_AR = "طوبيا" def populate_tobit_book(apps, schema_editor): BibleBook = apps.get_model('bible', 'BibleBook') BibleChapter = apps.get_model('bible', 'BibleChapter') BibleVerse = apps.get_model('bible', 'BibleVerse') book_r...
import pytest from githubmarkdownui.blocks import leaf from githubmarkdownui.constants import HEADING_MAX_LEVEL, HEADING_MIN_LEVEL def test_thematic_break(): assert leaf.thematic_break() == '<hr>' @pytest.mark.parametrize('language', ['python', None]) def test_code_block(language): test_code = 'x = 5\nprin...
from .delivery_stream import DeliveryStream from .buffering_hints import BufferingHints from .cloudwatch_logging_options import CloudWatchLoggingOptions from .copy_command import CopyCommand from .data_format_conversion_configuration import DataFormatConversionConfiguration from .deserializer import Deserializer from ....
from typing import List from ....utilities.byte_io_mdl import ByteIO from ....source_shared.base import Base from .model import ModelV36, ModelV49, ModelV44 class BodyPartV36(Base): model_class = ModelV36 def __init__(self): self.base = 0 self.name = "" self.models = [] # type: List...
from django.contrib import admin from . import models admin.site.register(models.Organisation) admin.site.register(models.Paper) admin.site.register(models.Scholar)
from aisikl.events import component_event from .control import Control class PopupMenu(Control): def show(self): # Some menus emit an "init" event when opened. You can do that with # this function, but you must do it manually when needed. By default, # menu items can be accessed directly ...
import json import logging import os import re import sys from collections import defaultdict from functools import wraps import chalice import connexion from chalice import Chalice from connexion import FlaskApi, ProblemException, problem from flask_cors import CORS from urllib.parse import urlparse pkg_root = os.p...
""" The SA game class and supporting functions. """ import copy import warnings from matching import MultipleMatching from matching import Player as Student from matching.algorithms import student_allocation from matching.exceptions import ( CapacityChangedWarning, MatchingError, PreferencesChangedWarning,...
#!python import click import os import math import logging from docstamp.file_utils import get_extension from docstamp.template import TextDocument from docstamp.config import LOGGING_LVL from docstamp.cli.utils import ( CONTEXT_SETTINGS, verbose_switch, get_items_from_csv, ExistingFilePath, DirP...
#!/usr/bin/env python import os import sys import time from datetime import datetime from dianaLib import * dryrun = False if 'DIANA_DIR' not in os.environ: print " 'DIANA_DIR' environmental variable not set. Exiting..." exit(1) dianaDir = os.environ['DIANA_DIR'] usage = """ mProphetMerged.py SWAT...
from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from multiselectfield import MultiSelectField from django_countries.fields import CountryField from apps.profiles.models import UserType, UserCreatedGroup, UserProfile...
from __future__ import unicode_literals from hooks.aws_glue_job_hook import AwsGlueJobHook from airflow.models import BaseOperator class AWSGlueJobOperator(BaseOperator): template_fields = () template_ext = () ui_color = '#ededed' """ https://boto3.amazonaws.com/v1/documentation/api/latest/refer...
import pytz def build_tzinfo(tzname, tzsign='+', tzhour=0, tzmin=0): """ create a tzinfo instance according to given parameters. tzname: 'Z' ... return pytz.UTC '' | None ... return None other ... return pytz.FixedOffset """ if tzname is None or tzname == '': r...
# -*- coding: utf-8 -*- """ Find an approximation to the square root of 25 using newton rapson method Newton proved that if a value: guess is an approximation to a root of a polynomial, then guess-p(guess)/p'(guess) is a better approximation for square roots: x*x - k = 0 take a guess... then: better_guess...
from tkinter import Frame, Label import json class Countdown(Frame): def __init__(self, window): super().__init__(window) self.config = json.load(open("data/config.json", "r"))["countdown"] self.event_frequency = self.config["event_frequency"] self.bgcolor = self.config["b...
#!/usr/bin/python # # Script creates GraphState object from given adjacency list # For example: # $ python from_adjlist.py "[[-1, 0], [0, 1], [0, 2], [1, 2], [1, 3], [2, 3], [3, -1]]" # Expected output: # e12|23|3|e| import sys import graph_state from graph_state import graph_state_property from graph_state impo...
import subprocess import os import sys import subprocess import numpy as np import pyroms import pyroms_toolbox from remap_bdry import remap_bdry from remap_bdry_uv import remap_bdry_uv year = int(sys.argv[1]) lst_year = [year] data_dir = '/Volumes/R1/Data/SODA_2.1.6/' dst_dir='./' lst_file = [] for year in lst_y...
from __future__ import annotations import functools from typing import Optional, Iterable, Set, Any from gelidum import freeze def freeze_params(params: Optional[Iterable[str]] = None): def inner_freeze_params(func): """Freeze all input params of a method""" @functools.wraps(func) def wra...
import mock from mock import patch import pytest import responses from drf_client import utils, settings from drf_client.resources import Resource from drf_client.exceptions import APIException from tests.fixtures import authenticate from tests.helpers import mock_response def test_converting_objs_to_ids_works_with_...
from flask import render_template, redirect ,request, url_for from app import app, vote, vote_data @app.route('/') @app.route('/index') @app.route('/index/') def index(): return render_template('index.html',vote={}) ''' For future when we have logins @app.route('/',methods=['POST']) @app.route('/index',...
import sys import cauldron as cd from cauldron.test import support from cauldron.test.support import scaffolds from cauldron.runner import redirection class TestRunnerRedirection(scaffolds.ResultsTest): """ """ def test_already_restored(self): """ should not cause an exception when already defaulted...
"""PIL based font support for p5. :author: Abhik Pal :date: 2018-07 """ import contextlib import functools import textwrap import PIL from PIL import Image from PIL import ImageDraw from PIL import ImageFont __all__ = ['create_font', 'load_font', 'text', 'text_font', 'render_font'] _rendering = False _canvas = Non...
import random import time import argparse, gc import tensorflow as tf import pandas as pd import numpy as np import scipy from ..gnn.gcn.layers import InputLayer from ..align.test import greedy_alignment, sim from ..align.sample import generate_neighbours class DecentralizedAttentionLayer(tf.keras.layers.Layer): ...
from discord.ext import commands from modules import database from datetime import datetime from bson import ObjectId from time import time import config import asyncio import discord import re db = database.Connection() async def get_member(ctx, bot, source): if source is None: return None if isins...
#!/usr/bin/python3 from configs import config from stores import mapstore from shard_protos import shard_proto class cfg_mapstore(config): def __init__(self, ipaddr, core=0): cores = range(core,112) config.__init__(self, shard_proto(ipaddr, mapstore(), cores=cores), 1) if __name__ == '__main__': ...
# Copyright (c) 2019 Horizon Robotics. 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 applicab...
# imports from pyspark.sql.functions import * from pyspark.sql.functions import monotonically_increasing_id from pyspark.sql.window import Window # Enrich Source dataframe with tracking columns def enrich_source(df,start_dt,comp): enr_df = (df.withColumn('load_dt',lit(start_dt)) .withColumn('load_sou...
class WorkerInterrupt(BaseException): pass class Shutdown(BaseException): pass class Reject(Exception): pass
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) METRIC_MAP = { 'etcd_debugging_mvcc_db_compaction_keys_total': 'debugging.mvcc.db.compaction.keys.total', 'etcd_debugging_mvcc_db_compaction_pause_duration_milliseconds': ( 'debugging.mvcc.db.compa...
import math import struct class Struct(struct.Struct): # cast-like syntax for packing def __call__(self, value): return self.pack(value) def __str__(self): return "<Struct %s>" % self.format c_bool = Struct("?") c_float = Struct("f") c_double = Struct("d") c_int = Struct("i") c_uint = Struct("I...
#!/usr/bin/env python """This module supplies functionality to convert a csv file into a LaTeX table. """ import os import csv __author__ = "Christoph Woller" __credits__ = ["Christoph Woller"] __maintainer__ = "Christoph Woller" __email__ = "wollerch@fim.uni-passau.de" PATH = '<your path>' def csv_to_tex(): ""...
import os import sys sys.path.append("C:\\BERTVision") import torch import models.args def get_args(): # retreive the general models.args and attach them here parser = models.args.get_args() # set some AdapterPooler specific args parser.add_argument('--model', type=str, ...
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Provide a convenient name for sub-packages to resolve the main C-extension # with a relative import. from .._mlir_li...
import weakref class CarModel: _models = weakref.WeakValueDictionary() def __new__(cls, model_name, *args, **kwargs): model = cls._models.get(model_name) if not model: model = super().__new__(cls) cls._models[model_name] = model return model def __init__(...
import pandas as pd from azure.storage.blob import BlobServiceClient # sample code covers in creating a append blob and appending contents blobconnection = "connectionstring" blob_service_client = BlobServiceClient.from_connection_string(blobconnection) foldername = "folder1" containername = 'mycontainer' filename = ...
"""This script creates a regression test over metarl-TRPO and baselines-TRPO. Unlike metarl, baselines doesn't set max_path_length. It keeps steps the action until it's done. So we introduced tests.wrappers.AutoStopEnv wrapper to set done=True when it reaches max_path_length. We also need to change the metarl.tf.sampl...
#!/usr/bin/python import sys import json import hashlib import os import shutil import subprocess def md5sum(filename, blocksize=65536): hash = hashlib.sha1() count = 1 with open(filename, "rb") as f: # for block in iter(lambda: f.read(blocksize), b""): # hash.update(block) whi...
from .response import ResponseMessage from .user_example import UserBase, UserInDBBase
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor import matplotlib.pyplot as plt import multiprocessing import numpy as np import pickle import time import glob import csv import re NUMBER_OF_PROCESSES = 4 # Number of Processes running together filename = '' # UNPICKLING ALL THE PI...
import unittest import sys from crosshair.behavior_diff import diff_behavior from crosshair.core import AnalysisOptions from crosshair.util import set_debug def foo1(x: int) -> int: if x >= 100: return 100 return x def foo2(x: int) -> int: return min(x, 100) def foo3(x: int) -> int: if x > 1...
#!env/bin/python # -*- coding: utf-8 -*- import argparse import requests import lxml.html as html from datetime import datetime import re import sys import bokeh.plotting as plt import tempfile import os import numpy as np title_re = re.compile(r'#(?P<key>\d+) - (?P<date_string>.+)') num_re = re.compile(r'(?P<num>\d+)...
__version__ = "0.1.3" from .managers import RandomManager
#!/usr/bin/python # ***************************************************************************** # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The A...
import cxr_dataset as CXR import eval_model as E import model as M # you will need to customize PATH_TO_IMAGES to where you have uncompressed # NIH images PATH_TO_IMAGES = "../images_resized/" WEIGHT_DECAY = 1e-4 LEARNING_RATE = 0.01 NUM_LAYERS = 58 FREEZE_LAYERS = 0 DROP_RATE = 0 chromosome = [58, 0, 2, 0] NUM_OF_EP...
import os import vk_api as vk import random import logging from dotenv import load_dotenv from vk_api.longpoll import VkLongPoll, VkEventType from logs_handler import TelegramLogsHandler from telegram import Bot from detect_intent import detect_intent_texts logger = logging.getLogger('chatbots-logger') def answer(e...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import StratifiedKFold from sklearn.linear_model import Perceptron from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.naive...
from datetime import datetime from enum import Enum from typing import List, Optional from pydantic import Field from opennem.api.schema import ApiBase class StationIDListLocation(ApiBase): state: str country: str = "au" class StationIDList(ApiBase): id: int name: str location: StationIDListLo...
from summarize.modules.generate_probability_functions.generate_probability_function import GenerateProbabilityFunction from summarize.modules.generate_probability_functions.onmt import ONMTGenerateProbabilityFunction from summarize.modules.generate_probability_functions.see2017 import See2017GenerateProbabilityFunction...
import enum import argparse class LinkState(enum.Enum): INITIALIZED = 1, RUNNING = 2, ERROR = 3 class Link: """ Link implements receiving and sending data over a physical or networked connection to the target. """ def __init__(self, flopz_config: dict, arg_parser: argparse.Namespace): ...
from os import name from typing import List from flask import Flask, render_template, request from flask.wrappers import Response HOST = "" app = Flask(__name__) '''Variables globales: ''' #Aca se va a guardar los datos recividos: data_storage = { 'edad': 30, 'pasajero': ['0','0','0'], 'viaja_solo': '...
import os import unittest class GeneratePythonTestCase(unittest.TestCase): # Generate some bad python and verify that an error is detected in the output def test_execute_item(self): from pyjsg.parser_impl.generate_python import generate, evaluate basedir = os.path.abspath(os.path.dirname(__fi...
# Written using Python 3.6 # # Check a list of boreholes for concordance between collar elevations # in A.ENTITIES and BOREHOLE.BOREHOLES databases. # # The list of boreholes is harvested from the names of folders in which raw # gamma and induction conductivity field geophysics logs are stored. import os, sys ...
# -*- coding: utf-8 -*- import distutils.text_file from pathlib import Path import pkg_resources BASE_PATH = Path(__file__).parent.parent.parent REQUIREMENTS_PATH = str(BASE_PATH.joinpath("reqs/base-requirements.txt").absolute()) class TestRequirements: def test_requirements(self): """Test that each re...
# encoding = utf-8 # Always put this line at the beginning of this file import import_declare_test import os import sys from splunktaucclib.alert_actions_base import ModularAlertBase from splunk_ta_uccexample import modalert_test_alert_helper class AlertActionWorkertest_alert(ModularAlertBase): def __init__(sel...
""" training_dataset.py ------------------- This module provides classes and methods for creating a training dataset. By: Sebastian D. Goodfellow, Ph.D., 2018 """ # Compatibility imports from __future__ import absolute_import, division, print_function # 3rd party imports import os import json import shutil import zip...
import os from setuptools import setup # utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="kisn_pylab", version="3.0.0", author="bartulem", author_email="mimica.bartul@gmail.com", description=("For runni...
''' Python Program to Read a Number n And Print the Series “1+2+…..+n= " ''' n = int(input("Enter the number: ")) lst = [] for i in range(1,n+1): print(i, sep=" ", end=" ") if i < n: print("+", sep=" ", end=" ") lst.append(i) print("=", sum(lst)) print()
""" MobileNet V3 A PyTorch impl of MobileNet-V3, compatible with TF weights from official impl. Paper: Searching for MobileNetV3 - https://arxiv.org/abs/1905.02244 Hacked together by / Copyright 2021 Ross Wightman """ from functools import partial from typing import List import torch import torch.nn as nn import t...
class CommandArgs(): def __init__(self): self.operation = None self.errorLevel = 2 self.recursive = False self.printFlag = False self.extension = '.ckstyle.txt' self.include = 'all' self.exclude = 'none' self.standard = '' self.exportJson = Fal...
import requests import re import json # Intervalo [since,until[ de pares (Ano,Semestre) para dar scrapping # Provavelmente nada robusto mas há que ter fé since = [1, 2] until = [2, 1] def scrape_degree(degree): html = requests.get( 'https://fenix.tecnico.ulisboa.pt/cursos/{}/curriculo'.format( ...
import pywer references = [ "this is a simple python package", "it calculates word error rate", "it can also calculate cer", ] hypotheses = [ "this is the simple python package", "it calculates word error", "it can also calculate see er", ] wer = pywer.wer(references, hypotheses) cer = pywer.c...
from pathlib import Path from ekorpkit import eKonf from hydra.utils import instantiate from ..datasets import ShardingDataset from ..models import train_tokenizer from ..utils.func import elapsed_timer def lmdata(**args): args = eKonf.to_config(args) with elapsed_timer(format_time=True) as elapsed: ...
""" Calculate CRC's the standard way, using a table and/or bitshifting + XOR. Also demonstrates how to calculate a patch to arrive at a desired CRC value. And how to calculate a CRC in reverse. Copyright (c) 2016 Willem Hengeveld <itsme@xs4all.nl> """ from __future__ import division, print_function import sys if sys....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 12:43:56 2020 @author: abhijith """ import dash external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__,external_stylesheets=external_stylesheets) server = app.server app.config.suppress_callback_exceptions ...
def solution(args): i = [] ################################### # First part is to add the first part of the args list to the i arragy ################################### # If the first part is not followed by a subsequent number, # then you can add it to the array if args[0]+1 != args[1]:...
"""flowchart Flowchart Library in Python Copyright 2016 AlphaServ Computing Solutions """ from flowchart.chart import FlowChart from flowchart.version import __version__, __version_info__ __all__ = ['FlowChart', '__version__', '__version_info__']
# Generated by Django 2.2.10 on 2020-03-18 14:52 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('currency', '0002_auto_20200303_1713'), ] operations = [ migrations.AlterField( model_name='rate', n...
# coding: utf-8 from decimal import Decimal import pytest from moneyed import Money from ._compat import patch @pytest.fixture def patched_convert_money(request): patched = patch( 'djmoney.models.fields.convert_money', side_effect=lambda amount, cur_from, cur_to: Money((amount * Decimal('0.88'))...
from eletronico import Eletronico from log import LogMixing class SmartPhone(Eletronico, LogMixing): def __init__(self, nome): super().__init__(nome) self._conectar = False def inicia_conexao(self): if not self._ligado: _msg = f'{self._nome} ESTÁ DESLIGADO' pri...
#from pybtmsdk import ed25519 #import pybtmsdk.edwards25519 as ed25519 import copy from binascii import hexlify from binascii import unhexlify from pybtmsdk.key import get_child_xprv, get_xpub, get_seed, get_root_xprv, xprv_sign from pybtmsdk import utils from pybtmsdk.transaction import encode_raw_tx def find_dist...
import csv # CSV https://docs.python.org/ko/3/library/csv.html?highlight=csv from pprint import pprint # PrettyPrinter https://docs.python.org/ko/3/library/pprint.html def read_csv(filename): rows = [] with open(filename) as csvfile: reader = csv.reader(csvfile) for row in reader: ...
############################################################################### # Copyright (c) 2017-2020 Koren Lev (Cisco Systems), # # Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others # # # ...
"""Performance plotter. This module defines some helper functios to create nice plots out of the performance log files. """ import os import functools import itertools import pandas import pprint import matplotlib.pyplot as plt def read_experiment_folders(rootdir): """Creates a nested dictionary that represents...
""" Module handling stages of an MD run: PreProcessing, Simulation, PostProcessing. """ import pandas as pd from IPython import get_ipython from threading import Thread if get_ipython().__class__.__name__ == "ZMQInteractiveShell": from tqdm import tqdm_notebook as tqdm else: from tqdm import tqdm import matpl...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) 2021 Yong Hoon Lee __all__ = ["__title__", "__description__", "__version__", "__author__", "__uri__"] __title__ = "surrogate" __description__ = """Surrogate: A Python-Based Surrogate Modeling Testbed""" __version__ = "0.0.1" __author__ = "Yong Hoon Lee" __uri__ = "...
import pytest from autifycli.domain.utils import url2filepath from autifycli.exceptions import UnsupportedUrlTypeException def test_url2filepath_happycase(): url = "https://example.com" r = url2filepath(url) assert "example.com.html" == str(r) def test_url2filepath_invalid_url(): url = "example.com...
#### Get libraries import requests import re from bs4 import BeautifulSoup from collections import Counter import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.pipeline import make_pipeline from skle...
numbers = input().split(" ") numbers = list(map(int, numbers)) invert_list = [] for num in numbers: if num == 0: invert_list.append(0) elif num < 0: new_num = abs(num) invert_list.append(new_num) else: new_num = -num invert_list.append(new_num) print(invert_l...
from django.db import models from django.utils import timezone # Create your models here. from django.contrib.auth.models import User class Fee(models.Model): """ Fees Table """ title = models.CharField(max_length=30, unique=True) description = models.TextField(null=True, blank=True) job = mode...
# -*- coding: utf-8 -*- """ Base class and function for making a walk through a given asttypes tree possible. """ from __future__ import unicode_literals from calmjs.parse.asttypes import Node from calmjs.parse.ruletypes import Token from calmjs.parse.ruletypes import Structure from calmjs.parse.ruletypes import Layo...
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2020) Hewlett Packard Enterprise Development LP # # 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/licen...
from django import forms from django.core.exceptions import ValidationError from django.utils.translation import pgettext_lazy from ...interface import PaymentData class BraintreePaymentForm(forms.Form): amount = forms.DecimalField() # Unique transaction identifier returned by Braintree # for testing in...
import json class Developer: DEVELOPER_FIELD = 'Developer' NAME_FIELD = 'Name' def __init__(self, jsondata): self.name = '' self.load(jsondata) def load(self, jsondata): data = json.loads(jsondata) self.name = data[Developer.DEVELOPER_FIELD][Developer.NAME_FIELD]
from pathlib import Path from typing import Any import pytest import tomlkit from tbump.cli import run as run_tbump from tbump.config import ConfigNotFound, InvalidConfig from tbump.error import Error from tbump.file_bumper import ( BadSubstitution, CurrentVersionNotFound, InvalidVersion, SourceFileNo...