content
stringlengths
5
1.05M
from typing import Optional, Sequence import numpy def pad_sequences( sequences: Sequence[Sequence[float]], max_length: Optional[int] = None, value: float = 0.0, ) -> numpy.array: count = len(sequences) if max_length is None: max_length = max(map(len, sequences)) result = numpy.full(...
# -*- coding: utf-8 -*- """ Testing basic functionalities of DL.utils.data_splitting.py """ import unittest import numpy as np from DL.utils.data_loading import loadRobotData from DL.utils.data_splitting import CompleteRolloutsDataSplitter from tests.fake_data_test_case import FakeDataTestCase class TestDataSplit...
#! /usr/bin/env python # coding: utf-8 # # Copyright (c) 2019 JR Oakes # # 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,...
from __future__ import unicode_literals from PIL import Image, ImageSequence import sys import os # Python 2 and 3 support # TODO: Proper images2gif version that supports both Py 2 and Py 3 (mostly handling binary data) if sys.version_info < (3,): import legofy.images2gif_py2 as images2gif else: import legofy...
from json import dumps from re import sub from docutils.parsers.rst import Parser as RstParser from docutils.statemachine import StringList from docutils.utils import new_document from jinja2 import Environment, PackageLoader from six import string_types from sphinx.errors import SphinxError from sphinx.util import rs...
from datetime import datetime from app import app from app import db from flask import Blueprint from flask import render_template from flask import redirect from flask import url_for from flask import request from flask_login import login_required from flask_login import current_user from app.models.comment import ...
import multiprocessing # bind - The server socket to bind bind = "0.0.0.0:8081" # backlog - The maximum number of pending connections # Generally in range 64-2048 backlog = 2048 # workers - The number of worker processes for handling requests. # A positive integer generally in the 2-4 x $(NUM_CORES) range workers = ...
from mock import ANY from raptiformica.actions.package import package_machine from tests.testcase import TestCase class TestPackageMachine(TestCase): def setUp(self): self.get_first_server_type = self.set_up_patch( 'raptiformica.actions.package.get_first_server_type' ) self.ge...
import tornado.web import tornado.escape import json from {{appname}}.config import myapp from {{appname}}.handlers.base import BaseHandler class PowHandler(BaseHandler): """ The Base PowHandler Place to put common stuff which will remain unaffected by any PoW Changes. Purely and only Use...
import datetime import math import itertools import pytest import calendar from homeplotter.timeseries import TimeSeries sample_data = { "both-broken":[[datetime.date(2017, 10, 12), 200.0],[datetime.date(2017, 11, 24), 50.0],[datetime.date(2018, 12, 5), 200.0], [datetime.date(2020, 12, 30), 400.0], [datetime.date...
t = ["SET", "nameVariable", "value"] a = ["ADD_COMMAND", ]
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 7 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and pyth...
import pytest from semantic_version import Version from vvm.utils.convert import to_vyper_version @pytest.mark.parametrize( "version_str", ["0.1.0b17", "0.1.0beta17", "0.1.0-beta17", "0.1.0.beta17", "0.1.0B17", "0.1.0.Beta.17"], ) def test_to_vyper_version(version_str): assert to_vyper_version(version_st...
from __future__ import absolute_import from __future__ import unicode_literals from django.conf.urls import url from custom.icds.views.hosted_ccz import ( ManageHostedCCZ, ManageHostedCCZLink, EditHostedCCZLink, HostedCCZView, remove_hosted_ccz, download_ccz, download_ccz_supporting_files, ...
from typing import Union import abjad class Score(abjad.Score): r"Score." def add_final_bar_line(self, bar_line: Union[str, abjad.BarLine] = "|.", *, to_each_voice: bool = False, ) -> None: r"...
import tarfile import re import requests import json import os import shutil import pickle import sys import pandas as pd import numpy as np from fuzzywuzzy import fuzz import pickle import unidecode import unicodedata as ud # ran code on multiple clusters because the folder was very big inputid = int(sys.argv[2]) s...
from .core import draw_plot from .generic_plot import PlotLosses try: from .keras_plot import PlotLossesKeras except ImportError: # import keras plot only if there is keras pass try: from .pytoune_plot import PlotLossesPytoune except ImportError: # import pytoune plot only if there is pytoune ...
#!/usr/bin/env python3 ###################################################################### ## Author: Carl Schaefer, Smithsonian Institution Archives ###################################################################### import sys if "." not in sys.path: sys.path.append(".") import os import re import argparse ...
def int32_to_ip(int32):
from packassembler.schema import connect def setup(env): connect('', host=env['registry'].settings.get('mongodb', 'packassembler'))
from copyrightDetection.preprocessing import PreprocessData import pandas as pd import json from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from copyrightDetection.extractData import * pathToFile = "C:/Users/dilGoe/Desktop/CopyrightDetection/dataClean/dataCLEANsmall.json" class Vectorize...
"""NonHuman Schema.""" # Third-Party Libraries from marshmallow import fields # cisagov Libraries from api.schemas.base_schema import BaseSchema class NonHumanSchema(BaseSchema): """NonHumanSchema.""" asn_org = fields.Str(required=True)
import pyvista pyvista.global_theme.silhouette.feature_angle = 20.0
""" Add heuristics here """ from chess import * from typing import Dict, List import collections import random from utils.state_identifier import eval_boardstate from utils.trans_table_utils import * def piece_value_heuristic(board: Board, color: bool, max_turn) -> int: """ Values each piece and calculates th...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 17 14:08:28 2020 @author: Tobias Andermann (tobias.andermann@bioenv.gu.se) """ import sys,os,glob import numpy as np import pandas as pd import matplotlib.pyplot as plt np.set_printoptions(suppress=True) np.random.seed(1234) from Bio import SeqIO...
from matplotlib import cycler bg_mpl_style = {'lines.linewidth': 2.5, 'lines.markeredgewidth': 0.25, 'lines.markersize': 6.0, 'lines.solid_capstyle': 'round', 'font.family': ['sans-serif'], 'font.sans-serif': ['DejaVu Sans', 'Bitstream Vera Sans', 'Computer Modern Sans Serif', 'Lucida Grande', 'Verdana', 'Geneva', '...
from numpy.testing.utils import assert_allclose from kameleon_rks.tools.covariance_updates import update_mean_lmbda, \ weights_to_lmbdas, log_weights_to_lmbdas, update_mean_cov_L_lmbda import numpy as np def test_update_mean_lmbda(): N = 100 D = 2 X = np.random.randn(N, D) X2 = np.random.randn(N,...
import tempfile import typing import asyncio from renus.core.concurrency import run_in_threadpool class Background: def __init__( self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any ) -> None: self.func = func self.args = args self.kwargs = kwargs self....
import discord from copy import deepcopy from discord.ext import commands from dislash import slash_command, Option, OptionType, OptionChoice, SelectMenu, SelectOption template_embed = None template_help_embed = None # A class for static methods and fields related to help embeds for global usage class HelpEmbeds: @s...
from streamalert.shared.config import load_config class LookupTablesConfiguration: """ An abstraction around lookup tables configuration. LookupTables can be configured in two places. """ def __init__(self, config=None): self._configuration = {} if config is None: config ...
import os import yaml from datetime import datetime, timedelta import pytz from pprint import pprint from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from airflow.operators.python_operator import BranchPythonOperator from airfl...
#! /usr/bin/python3 def generate(file_name, target=None, sources=None, compiler_flags=None, ldflags=None, ldadd=None, first_strings=None): with open(file_name, "w") as f: f.write("# Automatically generated, see generate_am_files.py\n") if first_strings is not None: f.write(first_string...
import time from typing import ( Iterable, ) from eth_keys import keys from eth_keys.datatypes import PrivateKey from eth_typing import ( Address, Hash32, ) from eth_utils import ( encode_hex, to_tuple, ValidationError, ) from eth.abc import ( BlockHeaderAPI, ) from eth.constants import ( ...
from functools import partial from typing import Callable, Union import numpy as np import jax from jax import numpy as jnp from flax import linen as nn from netket import jax as nkjax from netket.stats import Stats from netket.utils.types import PyTree from netket.utils.dispatch import dispatch from netket.operat...
# -------------------------------------------------------------------------------------------------- # Copyright (c) 2021 Microsoft Corporation # # 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 Softw...
from .celery_app import *
#!/usr/bin/python from k5test import * from filecmp import cmp # Make sure we can dump and load an ordinary database, and that # principals and policies survive a dump/load cycle. realm = K5Realm(start_kdc=False) realm.run([kadminl, 'addpol', 'fred']) # Create a dump file. dumpfile = os.path.join(realm.testdir, 'dum...
import sys import subprocess i = 0 filenames = { 'generator': 'test_generator.py', 'brute_force': 'firstMissing_bf.py', 'solution' : 'first_missing_positive.py' } while True: print('Test Case: {}'.format(i)) test_case = subprocess.check_output("python {} {} > inp".format(filenames['generator...
from setuptools import setup, find_packages VERSION = '0.0.6' DESCRIPTION = '' LONG_DESCRIPTION = '' # Setting up setup( name="bapi-fw", version=VERSION, author="Christophe Kafrouni", author_email="<chris.kafrouni@gmail.com>", description=DESCRIPTION, long_description_content_type="text/markd...
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: sorted_arr = sorted(arr) min_diff = float(inf) pairs = [] n = len(arr) for i in range(n-1): min_diff = min(min_diff, sorted_arr[i+1] - sorted_arr[i]) ...
from urllib import request req = request.Request('http://www.douban.com/') req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') with request.urlopen(req) as f: print('Status:', f.status, f.reason) ...
import pandas as pd def main(): train_or_crossVal = input("FOR CCSVTS: 0 for training data 1 for crossval data: ") train_or_crossVal = int(train_or_crossVal) if train_or_crossVal == 0: importData = pd.read_csv("trainableData.csv") importDataWeekly = pd.read_csv("past_two_weekstrainDa...
from xml.etree.ElementTree import parse import os db_dir = './data/VMS/' #更改为自己的目录地址 anno_path = db_dir fileList = os.listdir(anno_path) if not os.path.exists(anno_path): os.makedirs(anno_path) for file_name in fileList: if file_name[len(file_name)-3:] != 'xml': continue filePath = db_dir + file...
# Made according to this (many thanks): # http://www.eecs.umich.edu/courses/eecs373.w05/lecture/hamming.html # Each byte is separated into two 4-bit parts, each part is encoded to 8-bit code (i.e. 1 encoded byte = 16 bits) import os from random import randint # [8,4] Hamming code table suitable for single error cor...
# Generated by Django 3.1.4 on 2021-02-05 21:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('autotasks', '0015_auto_20210205_1728'), ] operations = [ migrations.AddField( model_name='automatedtask', name='stat...
# System libraries from __future__ import absolute_import, division, print_function import argparse import logging import os import random import sys import time import json from datetime import datetime from jupyterdiskcheck import jupyterdiskcheck_plugin # Enable logging logging.basicConfig( format='%(asctime)...
# Programa Principal def teste(): x = 8 print(f'Na função teste, n vale {n}') print(f'Na função teste x vale {x}') n = 2 print(f'No programa principal, n vale {n}') teste() print(f'No programa principal, x vale {x}')
# Undergraduate Student: Arturo Burgos # Professor: João Rodrigo Andrade # Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil # Third exercise: Fibonacci sequence - by a common loop import numpy as np import time n = int(input("Enter the n indices: ")) Fbn=0...
""" Helper functions. """ import os import json import sys ### IO def check_dir(d): if not os.path.exists(d): print("Directory {} does not exist. Exit.".format(d)) exit(1) def check_files(files): for f in files: if f is not None and not os.path.exists(f): print("File {} ...
#!/usr/bin/env python import numpy as np from sklearn import preprocessing def estimate_parameters(X,Y, nc, nf, ns): ''' X: a mxn array of m TD-IDF features for n samples Y: a 1xn array of encoded labels corresponding to the above samples nc: number of classes nf: size of the feature vector Returns: complementar...
from app import db from app.models import Book, Log, Permission, Temperature, Residents, Visitors from flask import render_template, url_for, flash, redirect, request, abort from flask_login import login_required, current_user from . import log from ..decorators import permission_required @log.route('/borrow/') @logi...
import discord from discord.ext import commands from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import ...
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import sys if sys.platform.startswith('linux'): from .linux import LinuxLiveWallpaper as LiveWallpaper if sys.platform.startswith('win32'): from .win32 import W...
""" 2019-10-08 Master script to run a parallel jobs; input - number of threads to run Check nx and ny! args: number of threads Implicit: nx,ny """ import logging import subprocess import sys import numpy as np import carpet.various.parallel_with_threads as pwt import carpet from sim_geometry import nx, ny ## Sc...
import os from data_integration.pipelines import Pipeline, Task from data_integration.ui.cli import run_pipeline import mara_db.auto_migration import mara_db.config import mara_db.dbs import data_integration import data_integration.config from mara_app.monkey_patch import patch from bcreg.bcreg_pipelines import bc_reg_...
from trustlab_host.models import Scenario from django.db import models import re import importlib import importlib.util import inspect from os import listdir, mkdir from os.path import isfile, exists, isdir import pprint from trustlab.lab.config import SCENARIO_PATH, SCENARIO_PACKAGE, RESULT_PATH import traceback cla...
"""Tests for baseline_models.py""" import math import pytest from milkqa_utils import baseline_models def test_wwm_get_matches(): assert baseline_models.wwm_get_matches( ["o", "gato", "o", "gato", "é", "fofo"], ["o", "gato", "sim"] ) == ["gato", "gato"] assert ( baseline_models.wwm_get_mat...
from checkov.common.models.enums import CheckCategories from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck from checkov.common.models.consts import ANY_VALUE class SQLServerAuditingEnabled(BaseResourceValueCheck): def __init__(self): name = "Ensure that 'Auditin...
from jinjamator.tools.rest_clients.jinjamator import ( JinjamatorClient, JinjamatorResource, ) from jinjamator.external.rest_client.exceptions import AuthError try: admjmc = JinjamatorClient( f"http://localhost:{_container['port']}/api", ssl_verify=ssl_verify, username=_container["...
#!/usr/bin/env python3 ############################################################################### # Module Imports ############################################################################### import arrow import collections import functools import logbook import pathlib import pyscp import re import yaml fro...
import argparse from google.cloud import language from google.cloud.language import enums from google.cloud.language import types def main(text): client = language.LanguageServiceClient() document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) response = client.cla...
from tkinter import ttk, Canvas, BOTH, CENTER, RAISED class Configspace: def off(self,x): return x+self.theOffset def __init__(self,root): self.initConfig = -1, -1 self.goalConfig = -1, -1 self.solutionPath = [] self.isInitialize = False self.root = root ...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import invoice_pb2 as invoice__pb2 class InvoiceBuilderStub(object): """The invoice builder service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Gene...
# # Pyserini: Reproducible IR research with sparse and dense representations # # 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 python from distutils.core import setup setup(name='Faker.py', version='1.0', description='Fake data generator for python', author='Hrishikesh Huilgolkar', author_email='hrishikesh911@gmail.com', url='https://github.com/hrishikeshio/Faker.py', packages=['faker'], ...
import numpy as np def mult_test(dg, steps, repeat, callbacks, workers, use_multiprocessing, metric_names, model, fully_conv): scores = model.evaluate_generator(dg, steps=repeat * steps, callbacks=callbacks, workers=workers, ...
""" Python 3.x Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given n scores. Store them in a list and find the score of the runner-up. Input Format The first line contains n. The second line contains an array [] of n integers each separ...
import os.path import subprocess import sys import time from datetime import datetime def check_connection(): '''Returns True if a wireless network is connected, otherwise False.''' try: # Try to get the ESSID of the connected network on wlan0 # To check link status on eth0: cat /sys/class/net...
import os from gcloud import storage __all__ = ['get_connection', 'CLIENT_EMAIL', 'PRIVATE_KEY_PATH', 'PROJECT'] CLIENT_EMAIL = '606734090113-6ink7iugcv89da9sru7lii8bs3i0obqg@developer.gserviceaccount.com' PRIVATE_KEY_PATH = os.path.join(os.path.dirname(__file__), 'demo.key') PROJECT = 'gcloud-storage-demo' def g...
#!/usr/bin/env python3 #=============================================================================== # pileups_count.py #=============================================================================== """Convert mpileup format to allele counts""" # Imports =======================================================...
try: from tinyBT.core import main except: from core import main main()
# coding: utf-8 import requests class UsersHandler(): base_url = "https://api.github.com/users/" def __init__(self, token): self.auth = { "Authorization":"token {}".format(token)} def get_user_profile(self, user): user_url = self.base_url + user res = requests.get(use...
from collections import Counter from typing import List, Optional, Dict import numpy as np from tqdm import tqdm from presidio_evaluator import InputSample from presidio_evaluator.evaluation import EvaluationResult, ModelError from presidio_evaluator.models import BaseModel, PresidioAnalyzerWrapper class Evaluator:...
import matplotlib, os matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np from flarestack.analyses.ccsn.necker_2019.ccsn_helpers import ( updated_sn_catalogue_name, sn_cats, sn_times, pdf_names, raw_output_dir, ) import logging from flarestack.shared import plot_output_dir pl...
import os from flask import Flask import database import auth import blog # Create flask app app = Flask(__name__, instance_relative_config=True) # App config app.config.from_mapping( SECRET_KEY='DEV', DATABASE=os.path.join(app.instance_path, 'data.sqlite'), ) # Create instance path try: os.makedirs(app...
# coding=utf-8 import npyscreen npyscreen.npysGlobalOptions.ASCII_ONLY = False class TestApp(npyscreen.NPSAppManaged): #__TEXT_WIDGET = npyscreen.TitleText __TEXT_WIDGET = npyscreen.TextfieldUnicode def main(self): # These lines create the form and populate it with widgets. # A fa...
import logging from datetime import datetime import click from loqusdb.utils.migrate import migrate_database from loqusdb.commands.cli import cli as base_command LOG = logging.getLogger(__name__) @base_command.command("migrate", short_help="Migrate an old loqusdb instance") @click.pass_context def migrate( ctx...
import os from ConfigData import ConfigData class ConfigurationManager: ''' ConfigurationManager class - extracts configuration data from the config file provided. Config file is expected to be an XML file following the required schema. ''' def __init__(self, filePath): ''' Initialise a new ConfigurationMa...
import doctest import unittest import azul import azul.azulclient import azul.bigquery import azul.caching import azul.collections import azul.doctests import azul.dss import azul.exceptions import azul.files import azul.indexer import azul.indexer.aggregate import azul.iterators import azul.json import azul.json_free...
# -*- coding: utf-8 -*- """ An experimental DeltaChat simplebot plugin for accessing some HERE.com services. Implemented using the following example as a template: https://github.com/SimpleBot-Inc/simplebot_plugins/blob/master/plugins/simplebot_xkcd/simplebot_xkcd/__init__.py Run locally from the repo root with:: ...
# -*- coding: utf-8 -*- from moon.logging import FuncLogger, setlogging setlogging(None) from logging import getLogger logger = getLogger("test.funclogger") funclogger = FuncLogger(logger) class ObjectA(object): @funclogger(printkey="b", withcaller=True) def funcinclass(self, a, b): pass @funclo...
import csv, pymssql, os, snowballstemmer, sys, string, traceback, re # used to remove non alphanumeric characters in tokens nascii_regex = re.compile('[\W_]+', re.UNICODE) # the translation for remove punctuation remv_punc = str.maketrans('', '', string.punctuation) # create the stemming engine stemmer = snowballstemm...
from django.db import models from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from modelcluster.fields import ParentalKey from wagtail.core import blocks from wagtail.core.models import Page, Orderable from wagtail.core.fields import StreamField from wagtail.admin.edit...
def binarySearch(alist, item): 2 if len(alist) == 0: 3 return False 4 else: 5 midpoint = len(alist)//2 6 if alist[midpoint]==item: 7 return True 8 else: 9 if item<alist[midpoint]: 10 return binarySearch(alist[:midpoint],item) 11 else: 12 ...
from .serializer import KnightSerialize from .serializer import PieceSerializer from .models import Pieces from .models import KnightAudits from board.moves import knight_moves from board.utilits import colors from django.contrib.auth.hashers import check_password from django.contrib.auth.models import User from rest_...
import networkx as nx import json import math import random import time from collections import deque import numpy as np class GraphManager: """ This is a class used to create, manage, draw and process some properties of graphs and, in particular, of its nodes like: shortest path and betweenness of each node """ ...
from Othello.Controller import Controller def main(): othelloController = Controller() othelloController.main() main()
#!/usr/bin/env python '''Testing the map model. This test should just run without failing. ''' from __future__ import division, print_function, unicode_literals __docformat__ = 'restructuredtext' __version__ = '$Id: MAP_MODEL.py 1078 2007-08-01 03:43:38Z r1chardj0n3s $' # that simplifies the pyglet mockup needed #...
import pandas as pd import numpy as np from typing import Union, List, Tuple from sklearn.preprocessing import StandardScaler from features.transformer import Transformer, TransformableList class StandardNormalizer(Transformer): """A transformer for normalizing values within a feature pipeline by removing the...
# SPDX-License-Identifier: BSD-3-Clause # Depthcharge: <https://github.com/nccgroup/depthcharge> """ This module provides data abort-baed register reads atop of memory read and write U-Boot commands specifically intended for memory display or modification. See: <https://www.denx.de/wiki/publish/DULG/to-delete/UBootCm...
# coding=utf-8 import logging import os import signal import time import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from apihandler.StudentMgr import StudentMgrHandler class Application(tornado.web.Application): def __init__(self): app_setting...
# coding=utf-8 import math import tensorflow as tf from functools import partial from src.utils.registry import register from . import dense registry = {} register = partial(register, registry=registry) @register('none') def null_connection(x, _, __): return x @register('residual') def residual(x, res, _): ...
class DTO_Patient(): def __init__(self): self.IDPatient = "" self.FullName = "" self.Old = "" self.Gender = "" self.Ethnic = "" self.Job = "" self.Address = "" self.NumberPhone = "" self.CitizenID = "" self.IDHealthInsurance = "" ...
import abc import json import random import time from collections import OrderedDict from enum import Enum from typing import Dict, Optional from urllib import parse import logging import requests from plenigo import util from plenigo.error import PlenigoError from plenigo.util import LogLevel logger = logging.getL...
import cv2 import numpy as np from glob import glob from sklearn.model_selection import train_test_split from feature_extraction import compute_first_digits_counts def calculate_train_test_data(): reference_real = sorted(glob("data/cyclegan/*/*A/*.jpg")) reference_fake = sorted(glob("data/cyclegan/*/*B/*.jpg")) ...
from itertools import zip_longest from tesufr.corpora import CorpusPurpose, SetType from tesufr.corpora.providers import BbcNewsProvider def test_bbc_news_provider_initialization(): bbc_news_provider = BbcNewsProvider() assert bbc_news_provider is not None def test_bbc_news_provider_metainfo(): bbc_new...
"""Test for the NSW Transport Service Incidents GeoJSON feed.""" import datetime import pytz import aiohttp import pytest from aio_geojson_client.consts import UPDATE_OK from aio_geojson_nsw_transport_incidents.consts import ATTRIBUTION from aio_geojson_nsw_transport_incidents.feed import NswTransportServiceIncident...
# -*- coding: utf-8 -*- from pyramid import i18n from pyramid.view import view_config from webob.multidict import MultiDict from h import search from h.feeds import render_atom, render_rss from h.storage import fetch_ordered_annotations _ = i18n.TranslationStringFactory(__package__) def _annotations(request): ...
"""Constants for blueprint.""" # Base component constants NAME = "Blueprint" DOMAIN = "blueprint" DOMAIN_DATA = f"{DOMAIN}_data" VERSION = "0.0.1" ISSUE_URL = "https://github.com/custom-components/blueprint/issues" # Icons ICON = "mdi:format-quote-close" # Device classes BINARY_SENSOR_DEVICE_CLASS = "connectivity" ...
import csv import codecs import cStringIO import json import requests api_url = "http://organicdatacuration.org/enigma/api.php" facts_url = api_url + "?action=wtfacts&operation=show&format=json&title=" query_url = api_url + "?action=query&" categories_url = query_url + "list=allcategories&aclimit=500&format=json" ins...