content
stringlengths
5
1.05M
# -*- coding: future_fstrings -*- from fabric.context_managers import cd from fabric.operations import run from fabric.state import env def __task_clean_releases(): with cd(env.release_path): releases = env.get("keep_releases") or 5 releases_count = int(releases) if str(releases).isdigit() else 5...
import re import random import aiohttp from fuzzywuzzy import fuzz import logging from . import config from skybeard.beards import BeardChatHandler logger = logging.getLogger(__name__) async def get_key(): return BeardChatHandler.key BOT_JSON = None async def get_me(): global BOT_JSON if not BOT_JS...
# coding: utf-8 """A tornado based Jupyter lab server.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. # TODO: import base server app import os from jupyter_core.paths import jupyter_config_path, jupyter_path from notebook.notebookapp import NotebookApp from tra...
# Copyright 2021 The Cirq Developers # # 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 ...
# project/server/models.py import datetime from project.server import app, db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(255), unique=True, nullable=False) password = db.Column(db.String(255), ...
from django.contrib import admin from .models import Patient from .forms import PatientAdminForm # Register your models here. class PatientAdmin(admin.ModelAdmin): form = PatientAdminForm list_display = ['user','created', 'last_updated', 'cart_code'] readonly_fields = ['created', 'last_updated'] admin.sit...
import numpy as np # make any plots not use display from matplotlib import use use('Agg') import matplotlib.pyplot as plt # used for ECDF import statsmodels.api as sm from selection.algorithms.lasso import instance from selection.algorithms.forward_step import forward_step, info_crit_stop, data_carving_IC from sel...
import csv import os import tempfile import pytest from topo_processor.metadata.csv_loader.csv_loader import read_csv def test_read_csv() -> None: metadata_path = os.path.join(os.getcwd(), "test_data", "historical_aerial_photos_metadata.csv") metadata = read_csv(metadata_path, "raw_filename", "sufi") a...
import pytest from flask import g, session from app.db import get_db @pytest.mark.parametrize(('username', 'password', 'message'), ( ('', '', b'Incorrect username.'), ('test', '', b'Incorrect password.'), ('test', 'test', b'Ok.'), )) def test_login(client, username, password, message): response = clie...
from PyQt5.QtSql import QSqlDatabase, QSqlQuery import pymysql from datetime import date import time class LinkDatabaseInMysql: def __init__(self, username, pass_word): self.connection = pymysql.connect( host='localhost', port=3306, user=username, password=p...
import json from time import sleep import blessed import requests from blessed.keyboard import Keystroke from modules.game import Game from modules.game_data import GameData Bounds = tuple[int, int, int, int] RenderableCoordinate = tuple[int, int, str] def _lies_within_bounds(bounds: Bounds, point: tuple[int, int]...
from .base import * DEBUG = True TEMPLATE_DEBUG = True ADMINS = () MANAGERS = ADMINS SECRET_KEY = 'TEST' COINS_BASE_URL = 'https://coins.ph' COINS_API_KEY = "09Wvsxce4IVBYfW1yIn4OnvlstObgTXNEeV0i7jY" COINS_SECRET = "8PLwxbZpB3nW2N7kqRaIfkgja5kLTMO6VYUaJMLQ3Aea2yfv4K" # For testing in sandbox # COINS_BASE_URL = '...
''' This file provides a basic framework for a live demo. In this case the demo is for face and eye detection. Copyright David S. Bolme Created on Jul 9, 2011 @author: bolme ''' import pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import Filt...
# This class is used to implement a stack which in turn is used to implement LRU class Stack: # Default constructor def __init__(self): self.items = [] # Function used to push an item on to the stack def push(self, item): self.items.append(item) # Function used to remov...
from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from notifications.models import Notification from .serializers import NotificationSerializer class NotificationListAPIView(ListAPIView): """ View that returns notification list of a single user. """ ...
from maya import cmds from PySide2 import QtWidgets, QtGui, QtCore from ncachefactory.optionvars import ( RANGETYPE_OPTIONVAR, CACHE_BEHAVIOR_OPTIONVAR, VERBOSE_OPTIONVAR, VERBOSE_OPTIONVAR, SAMPLES_EVALUATED_OPTIONVAR, SAMPLES_SAVED_OPTIONVAR, ensure_optionvars_exists) BLENDMODE_LABELS = ( "Clear all...
#import skimage.io as io #import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score def read_img(img_path): img = io.imread(img_path) return img def save_img(img_path, np_array): io.imsave(img_path, np_array) def extract_patches(outpu...
from transformers import RobertaTokenizer, RobertaModel, RobertaConfig import torch import os class EmbeddingGenerator: ''' A class which generates embeddings for text and saves them to data/tensors/ ''' def __init__(self): self.config = RobertaConfig.from_pretrained("roberta-base") self.confi...
import asyncio import datetime import json import logging from pathlib import Path import discord from discord.ext import commands # https://discordapp.com/oauth2/authorize?client_id=500165490753404938&scope=bot&permissions=8 # APPROVED SERVERS: # Fooeyy Official - 476519720380792834 def config_load(): with op...
def number_generator(): yield 0 yield 1 yield 2 # for i in number_generator(): # print(i) g = number_generator() # print(dir(g)) print(next(g)) print(next(g)) print(next(g)) def one_generator(): yield 1 return 'return에 지정한 값' try: g = one_generator() next(g) next(g) except ...
# coding: utf-8 """Набор конструкция для работы с уровнем моделей.""" import os import simplejson as json import sqlalchemy from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.automap import automap_base from sqlalchemy.inspection import inspect from sqlalchemy.orm.properties import ColumnProperty from sqlal...
from process import wordlist import itertools import time import os import re ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz' def main(): blacklist_all = wordlist.dict_by_length() blacklist = blacklist_all[3].union(blacklist_all[4]).union(blacklist_all[5]) combinations = get_combinations(3) tick = time.t...
''' Created on 13.06.2016 @author: Fabian Reiber @version: 1.0 ''' class NoFingerprintException(Exception): def __str__(self, *args, **kwargs): return Exception.__str__(self, *args, **kwargs) # # a = NoFingerprintException('Blaa') # print('test:', a.args[0]) # raise a
#!/usr/bin/python import sys, os, platform import configparser from executely.constants import Java class AppConfiguration(object): def __init__(self, app_path): if (not os.path.exists(app_path)): raise Exception('The app folder "%s" does not exist!' % app_path) config = conf...
# Copyright (c) 2021, NVIDIA 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 by appli...
#!/usr/bin/env python3 from pathlib import Path from typing import Any, Dict import jinja2 from aiohttp import web from aiohttp_jinja2 import setup as jinja2_setup, template from aiohttp_session import SimpleCookieStorage, get_session, setup as session_setup from aiohttp_oauth2.client.app import oauth2_app from func...
#!/usr/bin/python # -*- coding: utf-8 -*- # VideoColorSpace for Dreambox-Enigma2 # # Coded by cmikula (c)2012 # Support: www.i-have-a-dreambox.com # # This plugin is licensed under the Creative Commons # Attribution-NonCommercial-ShareAlike 3.0 Unported # License. To view a copy of this license, visit # http://c...
from nextcord.ext.commands.errors import CheckFailure class NotConnectedToVoice(CheckFailure): """User not connected to any voice channel""" pass class PlayerNotConnected(CheckFailure): """Player not connected""" pass class MustBeSameChannel(CheckFailure): """Player and user not in same chan...
import numpy as np from collections import defaultdict from formulagen.formula import as_str from formulagen.formula import as_tree from formulagen.formula import gen_formula_tree from formulagen.formula import Unit from formulagen.formula import Node def count(): return defaultdict(int) class TreeGram: ...
from data_detective_airflow.operators.extractors.db_dump import DBDump from data_detective_airflow.operators.extractors.python_dump import PythonDump from data_detective_airflow.operators.extractors.request_dump import RequestDump from data_detective_airflow.operators.extractors.s3_dump import S3Dump from data_detectiv...
import os from pydub.utils import make_chunks from pydub import AudioSegment chunk_size = 60000 #millisecs ragas = ['Kapi', 'Mayamalavagowla', 'Harikambhoji', 'Kharaharapriya', 'Nattai', 'Bilahari', 'Charukesi', 'Abheri', 'Kamas', 'B...
# =============================================================================== # Program : iterative_vasp_run.py # Author : Hyeongseon Park # must be run in the main_dataset directory!! # This code iteratively runs "vasp_run.sh" using "qsub" command in super-computing # server in NURION (by KISTI) # =========...
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright (c) 2015-2022 Vector 35 Inc # # 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, publish, ...
from django.shortcuts import redirect from .models import HouseMembership def house_required(function=None): def wrapper(request, *args, **kwargs): user = request.user try: currentHouse = HouseMembership.objects.get(user=user, currentHouse=True) except HouseMembership.DoesNotExist: currentHouse = None ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os.path sys.path.append(os.path.join(os.getcwd(), '.')) sys.path.append(os.path.join(os.getcwd(), '..'))
import json import os import argparse from shutil import copy, SameFileError import logging from tqdm import tqdm from PIL import Image from pathlib import Path from odm_report_shot_coverage.models.reconstruction import parse_reconstruction from odm_report_shot_coverage.models.shot import Boundaries Image.MAX_IMAGE_...
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: dic = {} for i, x in enumerate(nums): if x in dic: if abs(dic[x] - i) <= k: return True dic[x] = i return False
def main(parameters): ''' Gets al ist of users at a certain location NOTE: not implemented yet ''' answer = { 'text': 'This feature is not yet implemented.', 'markdown': 'This feature is not yet implemented.', 'file': None } return answer
from jinja2 import Environment, FileSystemLoader, select_autoescape, meta, Template from sql_gen.template_source import TemplateSource from sql_gen.prompter import Prompter from sql_gen.filter_loader import load_filters from sql_gen_app import run_app ##main def main(): run_app() if __name__ == '__main__': m...
from pymongo import MongoClient if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument( "-u", "--mongo_url", default="localhost", dest = "u" ) parser.add_argument( "-d", "--mongo_db", default="pmc", dest = "d" ) parser.add_argument(...
from .python_package_template import PythonPackageTemplate
# -*- coding: utf-8 -*- from hcloud.core.domain import BaseDomain, DomainIdentityMixin class Location(BaseDomain, DomainIdentityMixin): """Location Domain :param id: int ID of location :param name: str Name of location :param description: str Description of location ...
# import inspect # import os # # # def test_rules_imported(): # """ # Проверяем что все правила импортированны в __init__ # :return: # """ # import policy # # members = inspect.getmembers(policy, inspect.ismodule) # modules_imported = set(name for name, _ in members) # # # Берем все файл...
class Piece: def __init__(self, name, *, is_white: bool = True): self.name = name self.is_white = is_white self.color = 'white' if is_white else 'black' self.has_moved = False def find_piece(self, board): position = None for row in board: for cell in ...
import re import os import json from ts import Simbolo from storageManager import jsonMode as jsonMode from tabla_errores import * from columna import * import math import numpy as np from random import random class TypeChecker(): 'Esta clase representa el type checker para la comprobación de tipos' def __i...
from django import forms from django.forms import formset_factory from .models import Category,Measure,IngPrice class RecipeForm(forms.Form): name = forms.CharField( label="Recipe name", required=True, widget=forms.TextInput( attrs={ 'placeholder':"Enter Recipe...
import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('hidden3', 64, 'Number of units in hidden layer 3.') flags.DEFINE_integer('discriminator_out', 0, 'discriminator_out.') flags.DEFINE_float('discriminator_learning_rate', 0.001, 'Initial learning rate.') flags.DEFINE_float('learning_...
from django.db.models.signals import pre_save,post_save from .mysingal import action def pre_save_func(sender,**kwargs): print(sender) print(kwargs) print(kwargs.get("instance")) # pre_save.connect(pre_save_func) post_save.connect(pre_save_func) def my_action_func(sender,**kwargs): pr...
import os import shutil import hdbscan from math import isclose import numpy as np from sklearn.metrics import adjusted_rand_score from oolearning import * from tests.TestHelper import TestHelper from tests.TimerTestCase import TimerTestCase # noinspection PyMethodMayBeStatic, PyUnresolvedReferences class Unsuperv...
# 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...
from .module import Module from .pipeline import Pipeline from .pipeline import PipelineNode from .module import Module2 from .pipeline import Pipeline2 from .pipeline import Node
# CloudKit Helper # # # Based off the following # - CloudKitCatalog (c) 2016, Apple # - PyCloudKit. Created on 09.02.2016 (c) 2015 Andreas Schulz # - requests-cloudkit Copyright 2016 Lionheart Software LLC from __future__ import print_function import ecdsa import base64 import hashlib import datetime import sys im...
#!/usr/bin/env python import sys from PyQt5 import QtGui, QtWidgets, QtCore #create class for QPix map that just changes picture based on button pressest class WindowScreen(QtWidgets.QWidget): def __init__(self): super().__init__() self.string_of_commands = '' self.setWindowTitle("Traject...
# automatically generated by the FlatBuffers compiler, do not modify # namespace: graph class ExecutionMode(object): SEQUENTIAL = 0 STRICT = 1 AUTO = 2
import sys from setuptools import setup VERSION = '0.0.1' DESCRIPTION = 'WRITE SOMETHING INTELLIGENT HERE!' CLASSIFIERS = ['Development status :: 3 - Alpha', 'Intended Audience :: Ay250 grader', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OS...
from dataclasses import dataclass from enum import Enum from typing import Optional, List, Sequence, Any import numpy as np from tabulate import tabulate from pyqumo.matrix import str_array from pyqumo.random import CountableDistribution, Distribution from pyqumo.sim.helpers import build_statistics, FiniteFifoQueue, \...
import logging from .traderbot import TraderBot import json import config class MockMarket(object): def __init__(self, name, fee=0, cny_balance=3000., btc_balance=10., persistent=True): self.name = name self.filename = "traderbot-sim-" + name + ".json" self.cny_balance = c...
import numpy as np import cv2 camera = cv2.VideoCapture(0) # determine upper and lower HSV limits for (my) skin tones lower = np.array([0, 100, 0], dtype="uint8") upper = np.array([50,255,255], dtype="uint8") while (True): ret, frame = camera.read() if not ret: continue # switch to HSV hsv = ...
"""3. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Ex...
import os import pickle import operator from . import config from . import lib from .profanity_rater import profanity_severity_rating from .spam_rater import spam_severity_rating from .short_content_rater import short_content_severity_rating from .keyword_stuffing_rater import keyword_stuffing_severity_rating, find_stu...
from solutions.CHK import checkout_solution from unittest import TestCase class TestSum(TestCase): def test_chkE(self): self.assertEqual(checkout_solution.checkout('BBE'), 85) def test_chkEE(self): self.assertEqual(checkout_solution.checkout('BBEE'), 110) def test_chkABCDE(self): ...
# -*- coding: utf-8 -*- """Synteny (genome order) operations.""" # standard library imports import sys from itertools import combinations # from os.path import commonprefix as prefix from pathlib import Path # third-party imports import dask.bag as db import networkx as nx import numpy as np import pandas as pd from ...
import unittest from jina.executors.encoders.nlp.transformer import TransformerTFEncoder, TransformerTorchEncoder from tests.unit.executors.encoders.nlp import NlpTestCase class PytorchTestCase(NlpTestCase): def _get_encoder(self, metas): return TransformerTorchEncoder( pretrained_model_name_...
from os.path import join from celery import Celery from flask import Flask from flask_assets import Environment as FlaskAssets, Bundle from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config.Config') app.secret_key = app.config['SECRET_KEY'] ce...
""" Code to make an exploratory plot of the output of a box extraction. """ from lo_tools import Lfun, zfun from lo_tools import plotting_functions as pfun import xarray as xr import matplotlib.pyplot as plt import numpy as np import sys from cmocean import cm import pandas as pd Ldir = Lfun.Lstart() # choose the fi...
import numpy as np # most basic functions def sigmoid(x): """sigmoid function""" return 1/(1+np.exp(-x)) def sigmoid_gradient(x): """gradient of sigmoid function""" return x * (1-x) def tanh(x): """tanh function""" return np.tanh(x) def tanh_gradient(x): """gradient of tanh function"...
#!/usr/bin/env python import sys if sys.version_info.major == 3: import exodus3 as exo else: import exodus2 as exo import os.path import numpy as np f = sys.argv[-1] if not os.path.isfile(f) or not (len(sys.argv) == 2): print "usage: {0} <filename>".format(sys.argv[0]) exit e = exo.exodus(f,"r") dim ...
# The MIT License (MIT) # # Copyright (c) 2020 Huimao Chen # # 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, modif...
import torch import torch.nn as nn import torch.nn.functional as F class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() self.linear_z = nn.Linear(100, 200) self.linear_y = nn.Linear(10, 1000) self.linear = nn.Linear(1200, 784) # "In our generat...
import os,sys,time from Tkinter import * from PIL import Image, ImageTk import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(8, GPIO.IN, pull_up_down=GPIO.PUD_UP) def RunPlaylist(): hdmi.destroy() path = '/home/pi/Desktop/majestic-pi/current.txt' file = open(path...
from csvhandler import * import logging class DataFeed(object): def __init__(self, instrument): self.feed = None self.subscribe_to_price_feed_for_instrument(instrument) def n_day_moving_avg(self, instrument, date, price, n): ''' trading, not calendar, day average ''' j = -1 for i ...
from Crypto import Random from Crypto.Cipher import AES from Crypto.Hash import SHA256 def get_key( password: str ) -> bytes: """Generates an encryption key based on the password provided.""" key = SHA256.new(password.encode()).digest() return key def encrypt( key: bytes, source: bytes ) ->...
from .dataset import split, deploy, deploy_and_split from .generic import * class DatasetCreator: ''' Create a dataset from a string. dataset_cmd (str): Command to execute. ex: "ImageList('path/to/list.txt')" Returns: instanciated dataset. ''' def __init__(self, globs): ...
class Logger: enable_logging = True def __init__(self, owning_class): self.owning_class_name = type(owning_class).__name__ def warning(self, message): self.log("Warning: " + message) def log(self, message): if (Logger.enable_logging): print(self.owning_class_name +...
def bezout(a, b): """returns u, v such as au+bv = pgcd(a,b)""" if b == 0: return (1, 0) else: (u, v) = bezout(b, a % b) return (v, u - (a // b) * v) def chinese_theorem_inv(modulo_list): """ Returns (x, n1*...*nk) such as x mod mk = ak for all k, with modulo_list =...
import unittest from mock import patch from bbpyp.ll_combinator.defer import Defer @patch('test.TestContext', create=True) class TestDefer(unittest.TestCase): def test_defer_initialized_as_expected(self, test_context): expected_parser_factory = test_context.parser_factory parser = Defer(test_co...
from dataclasses import dataclass, field from typing import Optional from bindings.csw.angle_type import AngleType from bindings.csw.vector import Vector __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class DirectionVectorType: """ Direction expressed as a vector, either using components, or using a...
class TestPolicy: def test_view_policy(self, lenses_conn): result = lenses_conn.ViewPolicy() assert type(result) is list def test_set_policy(self, lenses_conn): result = lenses_conn.SetPolicy("test_policy","All","HIGH","test_category",["test_field"]) policies = lenses_conn.View...
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Abstract class for utilities that upload to and download from object stores.""" import abc import pathlib from typing import Callable, Optional, Union __all__ = ['ObjectStore', 'ObjectStoreTransientError'] class ObjectStoreTransien...
import os import os.path as osp import click from prettytable import PrettyTable import pandas as pd from he import colors from he.config import * from he.experiment import Experiment from he.util import ExclusivePersistentObject class Workspace: """HE Workspace""" def __init__(self): experiments_fi...
""" Initialization module. """
import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib import rc from matplotlib import rcParams from matplotlib import style # https://stackoverflow.com/questions/15814635/prettier-default-plot-colors-in-matplotlib # http://seaborn.pydata.org/tutorial/color_palettes.html #import seaborn a...
from nacl.utils import random from nacl.secret import SecretBox from nacl.pwhash.argon2i import kdf class TestRule4c: def __init__(self): self.g_salt1 = b"1234567812345678" self.g_salt2 = bytes("1234567812345678", "utf8") self.nonce = b"123456781234567812345678" # 24 byte def p_examp...
### This is a script to get fragments using Murcko method ### import os import pandas as pd import rdkit from rdkit import Chem from rdkit.Chem.Scaffolds import MurckoScaffold as Murcko from rdkit.Chem import AllChem import numpy as np import ast def get_fragments(insmiles): """Get core and sidechains using Murcko...
"""This module contains utilities for docstrings parsers.""" from __future__ import annotations from ast import PyCF_ONLY_AST from contextlib import suppress from typing import TYPE_CHECKING, Callable from griffe.agents.nodes import get_annotation from griffe.expressions import Expression, Name from griffe.logger im...
from decimal import Decimal import numpy as np import matplotlib.pyplot as plt from scipy import io from scipy.optimize import minimize def cofi_costfunc(params, Y, R, num_users, num_movies, num_features, lambda_): # 还原参数 X = params[:num_movies * num_features].reshape(num_mov...
import glob import subprocess import sys from multiprocessing import Pool FILES_DIR = '/tmp/credo/parts' CORES = 4 def run_file(fn): print('Start compressing: %s' % fn) sp = subprocess.Popen(["xz", "-9e", fn]) sp.wait() print('... finish compressing: %s' % fn) def main(): # list all files in IN...
# MenuTitle: Copy Paths To All Layers for layer in Glyphs.font.selectedLayers: g = layer.parent paths = [p.copy() for p in layer.paths] for l in g.layers: if layer == l: continue l.shapes = [] for p in paths: l.paths.append(p.copy()) l.width = layer.width
from toolz.functoolz import curry from sympy.core.function import Function NAN = Function('NAN') Missing = Function('Missing') NaNProtect = Function('NaNProtect') Expit = Function('Expit') # def call_method_or_dispatch(method_name, dispatcher): # def _call_method_or_dispatch(estimator, *args, **kwargs): # ...
from datetime import datetime from abc import ABCMeta, abstractmethod from typing import List from domain.entry import Entry class EntryRepository(metaclass=ABCMeta): @abstractmethod def get_all_entries(self, url: str) -> List[Entry]: raise NotImplementedError @abstractmethod def get_until_l...
from scrabbler.scrabbler import Game # from dqn.dqn_scrabble_helpers import DQNScrabbleHelpers import random import copy class Simulation: # LETTERS = ("AAAAAAAAAB" # "BCCDDDDEEE" # "EEEEEEEEEF" # "FGGGHHIIII" # "IIIIIJKLLL" # "LMMNNNNNNO" ...
print([123, 'das'] * 2 )
# -*- coding: utf-8 -*- import unittest import psycopg2 import mock from pgclient.exceptions import ErrorsRegistry as registry, PgClientError class ErrorsRegistryTest(unittest.TestCase): def test_registry(self): from psycopg2 import errorcodes codes = {k: v for k, v in errorcodes.__dict__.items() ...
import torchdiffeq import torch import torch.utils.data import torch.nn as nn import numpy as np import transformer.Constants as Constants from transformer.Layers import EncoderLayer, DecoderLayer from transformer.Modules import ScaledDotProductAttention from transformer.Models import ( Decoder, get_attn_key_pad_ma...
import data_preparation def main(file): data_preparation.save_data(file) file = '../data/viirs-snpp_2016_Australia.csv' main(file)
import requests class ImportApi: """ import french products from api openfoodfact""" def __init__(self): self._page = None self._page_size = None self._actual_request = None self._status_code = None self._imported_file = None @property def page(self): ...
import cv2 import random import itertools import numpy as np from skimage.measure import compare_mse def random_drop(img, ws, ratio): h, w = img.shape[:2] drop_map = np.zeros((h, w)) img_drop = img.copy() for i, j in itertools.product(range(h // ws), range(w // ws)): drop_index = random.sample...
import numpy as np import matplotlib.pyplot as plt import os import itertools import bayesiantests as bt import matplotlib.pyplot as plt import seaborn as snb import scipy.io as sio # Define set that stores names of results files. res_list = [] # Define path to folder containing results. RESULTS_FOLDER = '../resul...
# -*- coding: utf-8 -*- import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.callbacks import ModelCheckpoint import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn....