content
stringlengths
5
1.05M
import os import sys import time import signal from ave.network.pipe import Pipe from ave.network.process import Process from ave.network.control import Control, RemoteControl from ave.network.connection import find_free_port import setup # make some controls that defy SIGTERM so that an ordinary join() ...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('info/', views.info, name='info'), path('history/', views.getHistory, name='history'), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- '''The main class that is used to create and store Context instances. This setup is what makes ways.api.Context objects into flyweight objects. TODO: Remove this class. It could just be a list with functions. ''' # IMPORT STANDARD LIBRARIES # scspell-id: 3c62e4aa-...
import argparse import configparser import os from functools import partial from multiprocessing import Pool import psutil from crawler.crawl_authors import (crawl_author_with_publications, crawl_author_info_by_name, crawl_author_info_by_id, ...
# coding: utf8 # Author: Rodrigo Bistolfi # Date: 03/2013 """ Base class for Nikola test cases """ __all__ = ["BaseTestCase"] import sys import unittest if sys.version_info < (2, 7): try: import unittest2 _unittest2 = True except ImportError: _unittest2 = False if _unittest...
import sys, random, time, pygame from pygame.locals import * def print_text(font, x, y, text, color=(255, 255, 255)): imgText = font.render(text, True, color) screen.blit(imgText, (x, y)) pygame.init() screen = pygame.display.set_mode()
from abc import ABCMeta, abstractmethod from threading import RLock import traceback from .downstream_prune import DownstreamState from .assert_state import AssertState, AssertStateABC from pimdm.packet.PacketPimGraft import PacketPimGraft from pimdm.packet.PacketPimGraftAck import PacketPimGraftAck from pimdm.packet...
import os import bson import copy import datetime import dateutil import json import uuid import zipfile from ..web import base from .. import config from .. import upload from .. import util from .. import validators from ..auth import listauth, always_ok from ..dao import noop from ..dao import liststorage from ..da...
from django.contrib.auth import user_logged_in from scientist.models import Profile def check_userprofile(sender, request, user, **kwargs): try: profile = user.profile except: Profile(user=user).save() user_logged_in.connect(check_userprofile)
# Copyright 2020 Nick Guletskii # # 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 ...
from django.contrib import admin # Register your models here. from .models import (homepage,login,logout,post,teaching,non-teaching,teaching apply,non-teaching apply,create,register) class RegisterAdmin(admin.ModelAdmin): model = Register search_fields = ('email_address',) admin.site.register(homepage) admin....
from .base import Scheduler
from os import path from tests.cli import util from tests import testcase SYMSTORE_PATH = "dummy" class TestInvalidPEFile(testcase.TestCase): def assertUnknownFileTypeMsg(self, retcode, msg, filename): self.assertEqual(retcode, 1) self.assertRegex(msg.decode(), ".*%s: can...
import copy ################################################# # Elements # ################################################# class Element: def __init__(self, name, **kwargs): self.name = name self.dx = float(abs(kwargs.get('dx', 1))) self.k = float(kw...
from __future__ import print_function import sys import numpy as np import numba.unittest_support as unittest from numba.compiler import compile_isolated from numba.numpy_support import from_dtype from numba import types, njit, typeof from .support import TestCase, CompilationCache, MemoryLeakMixin def array_dtype...
persona1 = {'first_name':'Luis','last_name':'Romero','age':21,'city':'Saltillo'} print(persona1['first_name']) print(persona1['last_name']) print(persona1['age']) print(persona1['city']) print() persona2 = {'first_name':'Maria','last_name':'Vazquez','age':23,'city':'Saltillo'} print(persona2['first_name']) print(person...
class Solution: # @param {integer} s # @param {integer[]} nums # @return {integer} def minSubArrayLen(self, s, nums): val = start = 0 minLength = len(nums) + 1 for i in xrange(len(nums)): if nums[i] >= s: return 1 val += num...
import pytest from dvc.cli import parse_args from dvc.command.stage import CmdStageAdd @pytest.mark.parametrize( "command, parsed_command", [ (["echo", "foo", "bar"], "echo foo bar"), (["echo", '"foo bar"'], 'echo "foo bar"'), (["echo", "foo bar"], 'echo "foo bar"'), ], ) def test...
class Multimodal(Module): __parameters__ = ["positional_embedding", "text_projection", "logit_scale", ] __buffers__ = ["input_resolution", "context_length", "vocab_size", ] positional_embedding : Tensor text_projection : Tensor logit_scale : Tensor input_resolution : Tensor context_length : Tensor vocab...
# Copyright 2017 The Chromium Authors. # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd. import json import sys import os from .compat import IsString, ToStringSafe class CodeSearchProtoJsonEncoder(j...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import os.path as op import sys import time import argparse import paramiko import luigi def run_cmds_ssh(cmds): username = 'zhoup' hostname = 'mesabi.msi.umn.edu' port = 22 pubkey = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa') key ...
import sys """ Calculates differences between yourResults and realResults files. Prints them to stdout. testCommands contains commands for which these outputs were generated """ if len(sys.argv) != 4: print "Invalid number of arguments. Example usage: python diff.py yourResults realResults testCommands" pr...
import kydb import kydb_config import pytest @pytest.fixture def db(): db = kydb.connect('memory://local') db.mkdir('/portfolio_management/test') db.upload_objdb_config(kydb_config.OBJDB_CONFIG) return db
from helpers import show_dotted_image import cv2 import numpy as np class BirdsEye: def __init__(self, source_points, dest_points, cam_matrix, distortion_coef): self.spoints = source_points self.dpoints = dest_points self.src_points = np.array(source_points, np.float32) self.dest_points = np.a...
import pytest import requests_mock from logsearch.logsearch import LogSearch def test_load_logsearch_with_api_key_makes_request_to_rest(): with requests_mock.Mocker() as m: m.get( "https://eu.rest.logs.insight.rapid7.com/management/organizations/apikeys", request_headers={'x-api-k...
import copy import csv import logging import os import pickle import random from collections import defaultdict from functools import lru_cache import numpy as np from keras.preprocessing import sequence, image from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing.text import text_to_word_...
# -*- encoding: utf-8 -*- from . import version, uuid_models default_app_navbar = [ ### MAIN NAVBAR ### - - - - - - - - - - - - - - - ### ### CONFIG SONUM { "field" : "app_navbar", "content" : u"apiviz default navbar", "app_version" : version, "help" : u"The ...
from unittest.mock import MagicMock import asynctest import jwt import pytest from fastapi import FastAPI from starlette import status from starlette.requests import Request from starlette.testclient import TestClient from fastapi_users.authentication import Authenticator from fastapi_users.router import ErrorCode, E...
from models.controller import Controller from models.nas_rnn import NAS_RNN from models.rte_classifier import RTEClassifier
# Import Libraries import requests import time import csv import pandas as pd from bs4 import BeautifulSoup from pandas import DataFrame # webscrape ticker symbol of companies from given year & month from NASDAQ IPO website def getTicker(year, month): url = 'https://www.nasdaq.com/markets/ipos/activity.aspx?tab=pric...
# -*- coding: utf-8 -*- { 'name': "Duplicate Change", 'version': '0.2', 'category': 'Operations/Purchase', 'summary': """ This module change duplicate behaivor for setting elaboraton to current logged user.""", 'description': """ This module change duplicate behaivor for setting ela...
# -*- coding: utf-8 -*- # from __future__ import absolute_import, print_function, division from future.utils import with_metaclass import numpy as np import xmeos from xmeos import models from xmeos.models import core from xmeos.models import CompositeEos import pytest import matplotlib.pyplot as plt import matplotli...
#!/usr/bin/env python3 import argparse import os import sys import re import pandas as pd from itertools import takewhile def merge( aaastrIn, ostm ): """ Outputs the table join of the given pre-split string collection. :param aaastrIn: One or more split lines from which data are read. :type aaa...
""" Unit tests of the gps.py module """ import numpy as np from pygam import LinearGAM import pytest from causal_curve import GPS from tests.conftest import full_continuous_example_dataset @pytest.mark.parametrize( ("df_fixture", "family"), [ (full_continuous_example_dataset, "normal"), (ful...
import matplotlib as mpl mpl.use('agg') import os import sys import numpy as np import drama as drm #import matplotlib.pylab as plt #from matplotlib import gridspec n_ftrs = 100 noise = 0.8 scl = 0.00 sft = 0.00 i_sig = int(sys.argv[1]) n_train = int(sys.argv[2]) nn = int(sys.argv[3]) dir_add = './'+sys.argv[0][:-3...
import numpy as np import argparse import cv2 import mahotas ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(image, (5,...
import sys from urllib.parse import urlsplit from sanic.response import HTTPResponse try: from sanic.websocket import WebSocketProtocol except ImportError: # the installed version of sanic does not have websocket support WebSocketProtocol = None import six def create_route(app, engineio_server, engineio_...
import xml.dom.minidom as dom import os, re def cut_nomeaning_text(mml): target = [] # removing in for loop cause the problem that the node next to the removed node is skipped. for child in mml.childNodes: if child.nodeType == child.TEXT_NODE: if re.match(r'\A\s*\Z', child.data): ...
"""General purpose factorization routines. """ from sympy.polys.integerpolys import zzX_from_poly, zzX_to_poly, zzX_factor from sympy.polys.polynomial import Poly, PolynomialError, SymbolsError, CoefficientError from sympy.polys.monomial import monomial_div from sympy.core import Integer, Rational, Symbol, sympify d...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os, logging, torch, json import os.path as osp from collections import OrderedDict from network.base_network import * from utils import utils from utils import config as cfg class...
from controller.invoker.invoker_cmd_base import BaseMirControllerInvoker from controller.utils import checker, invoker_call, utils from id_definition.error_codes import CTLResponseCode from controller.invoker.invoker_cmd_branch_commit import BranchCommitInvoker from controller.invoker.invoker_cmd_repo_check import Repo...
# Generated by Django 3.2.4 on 2021-06-15 18:40 import accounts.models from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import simple_history.models class Mig...
from common import * from textwrap import indent from math import prod filename = "AOC_2021\Day-16-Packet-Decoder\input.txt" with open(filename, 'r') as f: data = "".join(f"{int(x,16):04b}" for x in f.read().strip()) class Packet: def __str__(self): if self.typeid == 4: s = f'Packet({se...
import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor class InvariantMaxLayer(nn.Module): def forward(self, x: Tensor): """ x: (batch_size, n_nodes, n_nodes, channels)""" bs, n, channels = x.shape[0], x.shape[1], x.shape[3] diag = torch.diagonal(x, dim...
# This program has been developed by students from the bachelor Computer Science at Utrecht University within the # Software and Game project course # ©Copyright Utrecht University Department of Information and Computing Sciences. from unittest.mock import MagicMock, patch from django.test import TestCase from assist...
# -*- coding:utf-8 -*- """ Create on 2017/01/18 @author: vinson zheng @group: inpluslab @contact: 1530820222@qq.com """ import time import json import lxml.html from lxml import etree import datetime import pandas as pd import numpy as np import cons as ct import re import dateu as du from pandas.compat import String...
import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://blog.scrapinghub.com','https://www.vox.com/', 'https://fivethirtyeight.com/','https://slate.com/','https://www1.nyc.gov/', 'https://www.post-gazette.com/','https://www.nytimes.com/'] def parse(self, response)...
x ="maravillso"
""" Copyright (c) [2019] [sixlab.cn] [https://github.com/PatrickRoot/six-site] is licensed under the Mulan PSL v1. You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN "AS I...
""" module: radmin.client Radmin client logic that is used to interface with the Radmin clients Created by Ian Starnes 2007-11-27 """ from threading import Thread import thread, time, commands, os import timeout_xmlrpclib as xmlrpclib import socket, select # radmin modules import config, log class Triggers(object):...
# # Parameter classes # import numbers import numpy as np import pybamm class InputParameter(pybamm.Symbol): """ A node in the expression tree representing an input parameter. This node's value can be set at the point of solving, allowing parameter estimation and control Parameters -------...
import pytest from datetime import datetime, timezone from dateutil import parser from dkrls import calculate_age def test_calculate_age_seconds(): created = parser.parse('2020-10-20T17:49:45.000000000Z') now = datetime.fromtimestamp(1603216190.0, tz=timezone.utc) age = {'number': 5, 'unit': 'seconds'} ...
import os import pandas as pd import logging from gensim.models import KeyedVectors from sqlalchemy import create_engine PSQL_USER = "158_user" PSQL_PASSWORD = "158" PSQL_DB = "fasttext_vectors" PSQL_IP = "localhost" PSQL_PORT = "10153" LIMIT = 100000 FASTTEXT_PATH = "./fasttext_models/{lang}/cc.{lang}.300.vec.gz" o...
from sklearn.metrics import mean_squared_error import math import numpy as np def scorer_rmse(y_true, y_pred): mse = mean_squared_error(y_true=y_true, y_pred=y_pred) rsme = math.sqrt(mse) return rsme def scorer_quantile(y_true, y_pred, quantile=0.5): e = y_true - y_pred return np.mean(np.maximum(q...
import datetime import json import logging import socket import struct import threading from typing import Callable, Any from .state import State ## ======================================================================== def _log(): return logging.getLogger( __name__ ) ## ======================================...
""" Ways to transform interfaces to produce new interfaces """ import gradio class Parallel(gradio.Interface): """ Creates a new Interface consisting of multiple models in parallel Parameters: interfaces: any number of Interface objects that are to be compared in parallel options: additional kwarg...
import argparse import os import sys from contextlib import redirect_stdout import pytest from . import BASE_PATH from .timing import process_results parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("-o", "--outfile", dest="outfile", default='') pa...
from pipeline import load_initial_data_wrap, proc_config from fileop import loadfile from bowsvm import generate_vocabulary, generate_bow_feature from bowsvm import get_not_none_data, recover_image_from_vector from bowsvm import predict_none_as_zero import numpy as np import sklearn.svm from sklearn.metrics import acc...
# Copyright 2020 Google 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 writing, ...
import pytest import math @pytest.mark.a def test_a(): assert (2 * 3) == 6 @pytest.mark.b def test_b(): assert (2 + 5) == 7
from .base_case import BaseCase from actions import Remake class RemakeCase(BaseCase): def test_remake_result(self): return NotImplemented
import pandas as pd import pickle as pickle import sys import os from mpl_toolkits.mplot3d import Axes3D import matplotlib import matplotlib.pyplot as plt import numpy as np from skimage import io import utils.list_inputFiles as list_inputFiles import utils.general_utils as general_utils import utils.list_behavior as ...
from apps.api.utils import SharedAPIRootRouter from .views import CommitteeApplicationViewSet urlpatterns = [] # API v1 router = SharedAPIRootRouter() router.register( "committeeapplications", CommitteeApplicationViewSet, basename="committeeapplications", )
#!/usr/bin/env python3 """Utilities for determining invalid filenames. """ import errno import json import logging import os def create_directories(directory_list): """ Create the directories defined in the directory_list """ reasons = [] for directory in directory_list: try: os...
from ..survey.sfm_helpers import SparseModel if __name__ == "__main__": # post_condition project_path = r"" project = SparseModel(project_path, model_path=project_path + r"/sparse/aligned") images = project.images if True: query_point = "rechts/R1022.jpg" img = next((i for i in imag...
import csv import random from pathlib import Path import datetime wafers = ['iLGAD_3374-15', 'iLGAD_3374-16', 'iLGAD_3374-16', 'iLGAD_3374-17', 'iLGAD_3374-18'] die_row = 4 die_col = 4 def create_iv_file(wafer, die, filepath): author = random.choice(['Dima Maneuski', 'Danial Tariq', 'James McClure', 'Ciara Lose...
import pytest from controller.k8s_resources import get_children_specs import logging @pytest.mark.parametrize("pvc_enabled", [True, False]) @pytest.mark.parametrize("size", ["1G", "10G"]) @pytest.mark.parametrize("storage_class", ["standard"]) def test_storage(storage_class, size, pvc_enabled, valid_spec): storag...
import inspect import os import sys from typing import List import template_txs # Used to import from parent directory # TODO # Consider turning it into a package current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent...
def get_requires_for_build_sdist(config_settings): return ["intree_backend_called"]
"""Looper implementation.""" from typing import Optional, List import torch import numpy as np import matplotlib from matplotlib import pyplot class Looper(): """Looper handles epoch loops, logging, and plotting.""" def __init__(self, network: torch.nn.Module, device: torch...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 25 10:14:39 2019 @author: Kyle """ # Keras is used for loading the model import keras from keras.models import Model from keras.models import load_model from keras.applications.inception_v3 import InceptionV3, preprocess_input, decode_predictions ...
from paymentrails.configuration import Configuration from paymentrails.gateway import Gateway class Recipient: """ A class that facilitates Client requests to the PaymentRails API in regards to Recipients. """ _attributes = { "id": "", "routeType": "", "estimatedFees": "", ...
import json import numpy import os import pathlib import pickle import tempfile def write_delimited(path, data, delimiter='\t'): """Write a list of lists (or iterable of iterables) to a delimited file.""" path = pathlib.Path(path) try: with path.open('w') as f: f.write('\n'.join(delimit...
import os import sys import subprocess ''' Outpost API ''' class OutpostApi(object): def __init__(self, settingData, additionalEnv): ''' "AHOY": ["PUPU", "set"] ''' self.__executablePath = settingData['executablePath'] self.__beforeLaunchHook = settingData['beforeLaunchHo...
import abc from typing import Dict from django.conf import settings from django.core.paginator import Paginator, Page as PaginatorPage from django.http import HttpRequest, QueryDict from django.utils.functional import lazy from wagtail.core.models import Page __all__ = ['AbstractPaginationData', 'PaginatorPaginati...
import taichi as ti @ti.all_archs def test_running_loss(): return steps = 16 total_loss = ti.var(ti.f32) running_loss = ti.var(ti.f32) additional_loss = ti.var(ti.f32) @ti.layout def place(): ti.root.place(total_loss) ti.root.dense(ti.i, steps).place(running_loss) ti.root.place(additional_l...
import argparse from endless_sky.datafile import DataFile from re import sub parser = argparse.ArgumentParser() parser.add_argument("locations") parser.add_argument("links") args = parser.parse_args() links = {} for i in DataFile(args.links).root.filter_first("system"): links[i.tokens[1]] = [] for j in i.filter_...
from collections import namedtuple Tweet = namedtuple("Tweet", "text polarity") # polarity < 0 = negative, > 0 = positive # long strings and pep8: you can wrap strings in () to reduce line length tweets = [ Tweet( text=( "It's shocking that the vast majority of online banking " "sy...
from datetime import date, datetime from typing import Optional from pydantic import AnyUrl, BaseModel, Field, validator from app.airtable.attachment import AirtableAttachment from app.airtable.response import AirtableResponse from app.airtable.validators import get_first_or_default_none, get_first_or_default_dict ...
import random import string class token_generator: def __init__(self, length): self.letters = string.ascii_letters self.length = length def get_random_string(self): result = ''.join(random.choice(self.letters) for i in range(self.length)) return result
from abc import ABC from dataclasses import dataclass from django.db import models from rest_framework import serializers class BaseModel(models.Model): created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Seril...
# -*- coding: utf-8 -*- """Utils package for pyentrez."""
# -*- coding: utf-8 -*- from qcloudsdkcore.request import Request class DescribeApiKeysStatusRequest(Request): def __init__(self): super(DescribeApiKeysStatusRequest, self).__init__( 'apigateway', 'qcloudcliV1', 'DescribeApiKeysStatus', 'apigateway.api.qcloud.com') def get_filter(self): ...
from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): ...
import dataclasses import sys from unittest import mock from unittest.mock import patch import pytest from rich.style import Style if sys.platform == "win32": from rich import _win32_console from rich._win32_console import COORD, LegacyWindowsTerm, WindowsCoordinates CURSOR_X = 1 CURSOR_Y = 2 CU...
import json import os import tempfile import traceback from runpy import run_path from unittest.mock import MagicMock from urllib.parse import parse_qs import param import pkg_resources from tornado import web from tornado.wsgi import WSGIContainer from .state import state class HTTPError(web.HTTPError): """ ...
from discord.ext import commands from discord import Embed, TextChannel, VoiceChannel from typing import Union, Optional from src.utils.loader import load items = load("./data/resources.yml") res = items["resources"] aliases = items["aliases"] class Random(commands.Cog): """A set of random commands for Soren"""...
import sys sys.path.append("../") from api.questions.rideshare_ohare import OHareRideshareQuestion from api.utils.testing import create_test_db def test_total_trips_pooled_by_pickup_specific_area_and_year(): con, cur = create_test_db( scripts=[ "./pipeline/load/rideshare.sql", ], ...
import contextlib import os from ase.neighborlist import NeighborList import numpy as np import spglib as spg def s2hms(time): m = time // 60 s = int(time % 60) h = int(m // 60) m = int(m % 60) return '{:02d}:{:02d}:{:02d} (h:m:s)'.format(h,m,s) def qp2ase(qpatoms): from ase import Atoms as ...
#!/usr/bin/env python import sys from confspy import ConfSpyPy from dataspy import DataSpyPy from procspy import ProcSpyPy def main(urls): configs = ConfSpyPy.load('spypy.cfg') dataspypy = DataSpyPy(configs['host'], configs['port']) procspypy = ProcSpyPy(dataspypy, configs['google_analytics'], configs[...
import os import unittest from buildnumber import objects TEST_FILENAME = "test-data/Buildfile" class BuildNumberTest(unittest.TestCase): @classmethod def tearDownClass(self): pass @classmethod def setUpClass(self): pass def setUp(self): pass def tearDown(self): ...
import serial import sys import time #import credentials READ_TIMEOUT = 8 def main(): print "\nInitializing serial connection" console = serial.Serial( port='COM3', baudrate=9600, parity="N", stopbits=1, bytesize=8, timeout=READ_TIMEOUT ...
from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) print("Key "+str(cipher_suite)) message = "Secret message".encode("utf8") cipher_text = cipher_suite.encrypt(message) plain_text = cipher_suite.decrypt(cipher_text) print("Cipher text: "+str(cipher_text.decode())) print("Pl...
from config import config import torch import torch.utils.data as data import torchvision.transforms as transforms import time, string import re, random, itertools from PIL import Image, ImageDraw import scipy.io as scio import Polygon as plg from glob import glob import matplotlib.pyplot as plt from detection.gaus...
""" Helper functions to deal with files """ import glob from pathlib import Path from os import walk def read_template(file_name: str) -> str: """Reads a template file and returns its content Params: :file_name: str, Required Template file name Returns: Template file conten...
# main.py 控制一组步骤的执行 # 目前的执行流程是 # 1. checkStepWaitReady 先检查 当前步骤 是否可以触发, 利用步骤中封装的 waitReady 函数 # 2. __start 如果检查通过, 则开始执行 当前步骤, 利用步骤中封装的 run 函数 # 3. __start 等待执行完成, 并检查当前的执行是否生效, 利用步骤中封装的 checkRun 函数 # 4. __start 如果执行成功, 则进入下一个步骤, 重复 流程 1 - 5 # 5. __start 如果执行失败, 终止当前流程组, 直接纪录失败 # TODO: 任务组 Steps 继承自 Event, ...
import nep29 import pytest def test_project_import(): pass
# _*_ coding: utf-8 _*_ # authFilters are use to filter requests by permission or authentication __author__ = "{{.Author}}" from flask import request def authFilter(): # login apis don't need auth-filter if request.path.startswith("/login"): return None # Other auth-filter logic... ret...
from torch import nn loss_functions = { "MSE": nn.MSELoss, "MSEPenalty": nn.MSELoss, "L1": nn.L1Loss, "CrossEntropy": nn.CrossEntropyLoss, "CTC": nn.CTCLoss, "NLL": nn.NLLLoss, "PoissonNLL": nn.PoissonNLLLoss, "KLDiv": nn.KLDivLoss, "BCE": nn.BCELoss, "BCEWithLogits": nn.BCEWith...
import warnings from .naive import NaiveAlgorithm class GhettoAlgorithm(NaiveAlgorithm): def __init__(self, *args, **kwargs): warnings.warn( "`GhettoAlgorithm` is pending deprecation and it will be removed in " "future versions. Use `recommends.algorithms.naive.NaiveAlgorithm ins...