content
stringlengths
5
1.05M
from prediction_flow.pytorch.nn import Interest import torch def test_gru_interest_evolution(): interests = Interest( input_size=3, gru_type='GRU', gru_dropout=0, att_hidden_layers=[8], att_dropout=0, att_batchnorm=False, att_activation=None) query = ...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class ScaledDotProductAttention(nn.Module): """Scaled dot-product attention mechanism.""" def __init__(self, attention_dropout=0.0): super(ScaledDotProductAttention, self).__init__() self.dropout = nn.Dropout...
import logging import sys logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='[%(asctime)s] %(name)s|%(levelname)-8s|%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# Generated by Django 4.0.1 on 2022-02-10 11:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Organizations', '0005_alter_mprovider_service_and_more'), ('Market', '0004_initial'), ] operations = [ ...
from django.urls import path from django.urls import include, path from . import views urlpatterns = [ path('', views.node_labels, name='node-labels-list'), path('<str:app>/<str:model>/', views.neomodel_list_view, name='neomodel-list'), path('<str:app>/<str:model>/<str:node_id>/change/', views.neomodel_cha...
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the...
import unittest from numpy.random import seed from Statistics.Statistics import Statistics import random import statistics class MyTestCase(unittest.TestCase): def setUp(self) -> None: seed(5) self.testData = [] for i in range(0, 10): num = random.randint(0, 15) sel...
import sys import subprocess import json #print('Running parseCoreMembers.py') deployment=sys.argv[1] #print('Deployment is ' + deployment) blob=subprocess.check_output('gcloud compute instances list --format=json', shell=True) instances=json.loads(blob) #print(json.dumps(j, indent=4, sort_keys=True)) output='' fo...
#!/usr/bin/env python # -*- coding: utf-8 -*- from requests.compat import urlparse try: from .helpers import url_join except: from crawlib.helpers import url_join class BaseUrlEncoder(object): """Base Url Encoder. Provide functional interface to create url. """ domain = None def __init__(se...
# Copyright 2019 The iqt Authors. # # 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 writ...
import tensorflow as tf from models.conv_resblock_denoising_unet import ConvResblockDenoisingUnet from training.train_loop import TrainLoop separator = ConvResblockDenoisingUnet(1025, 100) lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=0.0002, decay_steps=4000, decay_rate=0.5)...
import mysql.connector mydb=mysql.connector.connect( host="35.200.219.211", user="upendar", password="Upendar@123", database="mydb_upendar" ) print(mydb) mycursor=mydb.cursor() mycursor.execute("drop table emp") sql="create table emp (name varchar(200), address varchar(300))" mycursor.execute(sql) ...
import time from fractions import gcd from random import randrange def factor2(num): # Algoritmo Las Vegas que factoriza un numero N = p*q, p y q primos start = time.process_time() a = randrange(1, num) # Inicializo a con un valor en Gnum print ("choosen a = ", a) p = gcd(a, num) # Compruebo si son cop...
#!/usr/bin/env python3 import click import tempfile from click import Choice from typing import Optional import mlflow import torch import cleartext.utils as utils from cleartext import PROJ_ROOT from cleartext.data import WikiSmall, WikiLarge from cleartext.pipeline import Pipeline # arbitrary choices EOS_TOKEN = '...
# Link: https://leetcode.com/contest/weekly-contest-278/problems/all-divisions-with-the-highest-score-of-a-binary-array/ # Time: O(N) # Space: O(N) # Score: 4 / 4 from typing import List def max_score_indices(nums: List[int]): zero_total = one_total = 0 for num in nums: if num == 0: zero...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Liz M. Huancapaza Hilasaca # Copyright (c) 2020 # E-mail: lizhh@usp.br import numpy as np from sklearn.manifold import Isomap from vx.com.py.projection.Projection import * class ISOMAPP(Projection): def __init__(self, X=None, p=2): super().__init_...
# This file is intentionally in a directory that is not located in sys.path. # That causes the python runtime to return an absolute path for __file__. import os def get_root_dir(): absDir = os.path.dirname(__file__) rootDir = os.path.normpath(absDir + "../../../..") return rootDir
# Copyright (c) 2012 John Reese # Licensed under the MIT License from __future__ import absolute_import, division import Queue import sys import select import threading import time from pyranha import async_ui_message from pyranha.dotfiles import Dotfile from pyranha.irc.client import IRC from pyranha.engine.network...
import asyncio import json import logging from asyncio.queues import Queue import colorlog from chia.util.config import load_config from chia.util.default_root import DEFAULT_ROOT_PATH from monitor.collectors.rpc_collector import RpcCollector from monitor.collectors.ws_collector import WsCollector from monitor.db imp...
from django.contrib.contenttypes.models import ContentType from django.db import models from glitter.exceptions import GlitterUnpublishedException from glitter.models import Version from glitter.page import Glitter from .managers import GlitterManager class GlitterMixin(models.Model): published = models.Boolean...
import jittor as jt from jittor import nn, models if jt.has_cuda: jt.flags.use_cuda = 1 # jt.flags.use_cuda class QueryEncoder(nn.Module): def __init__(self, out_dim=128): super(QueryEncoder, self).__init__() self.dim = out_dim self.resnet = models.resnet50(pretrained=False) sel...
__author__ = 'fausto' from models.algorithm.minimax import Heuristic import random class HeuristicTestMe(Heuristic): def heuristic(self, board): return random.randrange(-20, 20) def eval(self, old_value, new_value): #Lembre-se, uma heuristica tem que ser min, e o outro deve ser max return old_value >...
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from ..utils import extract_CN_from_content from ..items import ScrapySpiderItem import re class A406Spider(CrawlSpider): name = '406' allowed_domains = ['ynfq.gov.cn'] start_...
from ann import * def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) def eval_numerical_gradient(f, x, verbose=True, h=0.00001): """ a naive implementation of numerical gradient of f at x - f should be a function that take...
from enum import Enum class RiscvRegister(Enum): """This class is obsolete because we are no longer using Renode. It may be possible to support RISC-V in the future, but that would require some work to make it work with Qemu. """ # Can't write to register 0 because it is not writable # ZERO ...
# Copyright (c) 2019, Nordic Semiconductor ASA # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of condi...
import pytest import hail as hl from ..helpers import resource, startTestHailContext, stopTestHailContext, fails_local_backend, fails_service_backend setUpModule = startTestHailContext tearDownModule = stopTestHailContext def assert_c_king_same_as_hail_king(c_king_path, hail_king_mt): actual = hail_king_mt.entr...
lista = ['lucas', 'kessia'] #list tupla = ('lucas', 'kessia') #tuple dicionario = {'nome': 'Késsia', 'idade': 18} #dict conjunto = {'Késsia', 'lucas'} #conjunto (set) não salva dados repetidos, tem busca rápida -------------------------------------------------------------------------...
#!/usr/bin/env python import random class BullsAndCows(): def __init__(self, size): digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] self.__secret = '' for _ in range(size): rnd = random.choice(digits) self.__secret += rnd digits.remove(rnd) ...
""" Copyright 2019 Samsung SDS 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...
import os from random import shuffle from elasticsearch_dsl.connections import connections from django.core.management import call_command from django.test import TestCase from faker import Faker from series_tiempo_ar_api.apps.dump.generator.xlsx.generator import generate, sort_key from series_tiempo_ar_api.apps.dump...
from .synergies import * class Champion: @classmethod def list(champion): return champion.__subclasses__() @Demon @Blademaster class Aatrox(Champion): tier = 3 weight = 0.1 @Wild @Sorcerer class Ahri(Champion): tier = 2 weight = 0.7 @Ninja @Assassin class Akali(Champion): tier = ...
#!/usr/bin/env python import O365 as o365 import json # O365 logging #import logging #logging.basicConfig(level=logging.DEBUG) # Running this triggers a manual copy-paste into browser, login, copy-paste # back. It should only need to be done once. See README for more. with open("conf.json", "r") as f: data = js...
# # Copyright (c) 2019 Intel Corporation # # 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 ...
def fib(N): if N == 0: return 0 if N == 1: return 1 return fib(N - 1) + fib(N - 2) cache = {0: 0, 1: 1} def fib_mem(N, cache): if N == 0: return 0 if N == 1: return 1 if cache[N] != 0: return cache[N] res = fib_mem(N - 1, cache) + fib_mem(N - 2, ...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured class Config(object): def __init__(self, **kwargs): self.CLIENT_ID = kwargs.get("CLIENT_ID", "") self.CLIENT_SECRET = kwargs.get("CLIENT_SECRET", "") self.REDIRECT_URI = kwargs.get("REDIRECT_URI", "")...
#!/usr/bin/env python3 # pylint: skip-file # type: ignore import numpy as np import math from tqdm import tqdm from typing import cast import seaborn as sns import matplotlib.pyplot as plt from selfdrive.car.honda.interface import CarInterface from selfdrive.car.honda.values import CAR from selfdrive.controls.lib.v...
import logging import random from argparse import ArgumentParser, Namespace import json from typing import Union, List, Tuple, Dict, Optional import math import re import torch from torch import Tensor, nn from torch.utils.data import DataLoader, Sampler, Dataset from torch.utils.data.distributed import T_co import to...
""" This module tests the objective function by comparing it to the line example from http://dan.iel.fm/emcee/current/user/line/ """ import pickle from multiprocessing.reduction import ForkingPickler import os import pytest import numpy as np from numpy.linalg import LinAlgError from scipy.optimize import minimize, l...
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; multiset <long long> s; long long result = 0; cin >> n; for (int i = 0; i < n; i++){ long long x; cin >> x; s.insert(x); } while (s.size() > 1){ long long value_1 = *s.begin();...
import flask from flask import request, render_template, flash, redirect, url_for from flask_login import login_user from ..models import User from ..utils.auth import is_safe_url from ..auth_provider import KnowledgeAuthProvider class DebugAuthProvider(KnowledgeAuthProvider): _registry_keys = ['debug'] de...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import contextlib import logging import os from collections import defaultdict from queue import LifoQueue import pytest import torch from pyro.infer.enum import iter_discrete_escape, iter_discrete_extend from pyro.ops.indexing impor...
#!/usr/bin/env python import roadrunner retval = 0 ## event handling functions def onEventTrigger(model, eventIndex, eventId): print("event {} was triggered at time {}".format(eventId, model.getTime())) def onEventAssignment(model, eventIndex, eventId): print("event {} was assignend at time {}".format(eve...
import os.path # import jena import ssdc
""" This module contains a class that bundles several approaches to visualize the results of the variations of the 'SeqClu' algorithm that are contained in the package. NOTE: This class has actually never been used during the research project and therefore needs major modifications to make it compatibl...
#!/usr/bin/env python # encoding: utf-8 ''' DNASampleSplitter -- shortdesc DNASampleSplitter is a description It defines classes_and_methods @author: John Carlos Ignacio, Milcah Kigoni, Yaw Nti-Addae @copyright: 2017 Cornell University. All rights reserved. @license: MIT License @contact: ...
## Python script to download a weekly snapshot of the Scottish Fundraising Charity Register # Diarmuid McDonnell # Created: 25 October 2018 # Last edited: captured in Github file history import itertools import json import csv import re import requests import os import os.path import errno import urllib from time imp...
import os import tempfile import zipfile import uuid import shutil from misc import Pause class Kit: def __init__(self, name, dir ): self.name = name self.files = {} self.hasError = False self.error = None self.dir = dir self.outputDir = os.path.join(dir, name) ...
import os # to hide pygame welcome message os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1" # # game global constants # TITLE = "Kings and Pigs" # map grid size GRID_SIZE = 32 # size of a virtual screen WIDTH = 14 * GRID_SIZE # 448 px HEIGHT = 7 * GRID_SIZE # 224 px # real window size (double size of virtual sc...
# -*- coding: utf-8 -*- """Module containing tools useful for tokenizing text for pre-processing.""" import string from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer def tokenize_string(orig_string): """ Create a list of string tokens from the in...
from __future__ import absolute_import from .nesteddict import NestedDict, ndict from .structurednesteddict import StructuredNestedDict, sndict from . import app __version__ = '0.1.2' __all__ = ( 'ndict', 'NestedDict', 'sn_dict', 'StructuredNestedDict', 'app', )
import torch import torch.nn as nn import pytorch_lightning as pl from typing import List, Tuple class MaxPoolProttrans(pl.LightningModule): """ Model from Steven Combs that uses MaxPool1d instead of Convolutions that seems to work well for sequence-based models with point-mutational data """ de...
# app/auth/forms.py from flask_wtf import FlaskForm from wtforms import PasswordField, StringField, SubmitField, ValidationError from wtforms.validators import DataRequired, Email, EqualTo, Length, AnyOf from ..models import Employee class LoginForm(FlaskForm): """ Form for users to login """ id = S...
# 343. Integer Break # Runtime: 36 ms, faster than 55.89% of Python3 online submissions for Integer Break. # Memory Usage: 14.3 MB, less than 47.74% of Python3 online submissions for Integer Break. class Solution: # Dynamic Programming def integerBreak(self, n: int) -> int: prdct = [0] * (n + 1) ...
from datetime import date dados = {} dados['nome'] = str(input('Nome: ')) ano = int(input('Ano de Nascimetno: ')) dados['idade'] = date.today().year - ano dados['ctps'] = int(input('Carteira de trabalho [0 não tem]: ')) if dados['ctps'] == 0: print('-=' * 30) for c, v in dados.items(): print(f'{c} tem o...
"""Simple module to control the UI interface elements""" # TOOLBAR ICONS _run = r'assets\UI\Icons\toolbar_icons\act_compile.PNG' _runSelected = r'assets\UI\Icons\toolbar_icons\act_compileSel.PNG' _import = r'assets\UI\Icons\toolbar_icons\act_import.PNG' _export = r'assets\UI\Icons\toolbar...
import sys from argparse import ArgumentParser from os import stat, mkdir from os.path import isfile, expanduser, isdir from re import compile, match as rmatch, VERBOSE from colorama import Fore, init from requests import get as r_get def download_oui_defs(fpath: str, force_dl=False) -> bool: # file exists and is...
import time, pytest, inspect from utils import * def test_outputs(run_brave): run_brave() check_brave_is_running() assert_outputs([]) # Create output, including allowing the ID to be set add_output({'type': 'local', 'id': 99}) assert_outputs([{'type': 'local', 'id': 99, 'uid': 'output99'}]) ...
# Copyright © 2020 Hoani Bryson # License: MIT (https://mit-license.org/) # # Packet # # L3aP packet for describing data fields # class Packet(): def __init__(self, category, path=None, payload=None): self.category = category self.paths = [] self.payloads = [] if path != None: self.add(path, pa...
import traceback import logging import attr from .. import entities, exceptions logger = logging.getLogger(name=__name__) @attr.s class User(entities.BaseEntity): """ User entity """ created_at = attr.ib() updated_at = attr.ib(repr=False) name = attr.ib() last_name = attr.ib() userna...
#!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # 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...
"""Utility functions """ def num_terms(docs): terms = set() for doc in docs: terms.update(set(doc)) return len(terms) def docs_from_document_term_matrix(dtm, vocab=None): """Read dataset from document term document-term matrix Parameters ---------- dtm : array of shape N,V v...
import os import numpy as np import random import torch.nn.functional as F from torch.autograd import Variable import torch import torch.utils.data as dataf import torch.nn as nn import matplotlib.pyplot as plt from scipy import io from sklearn.decomposition import PCA # setting parameters DataPath = '/home/hrl/Pychar...
# Copyright (c) 2020 PaddlePaddle Authors. 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 app...
from django.urls import path from django.views.generic import View urlpatterns = [ path("simple/action/", View.as_view(), name="simpleAction"), ]
""" Data structures for Rockstar frontend. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, yt Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #---...
a=[7,7,4,8,9] print(sum(a))
# Copyright 2014 Open Source Robotics Foundation, Inc. # # 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...
#!/usr/bin/python # Copyright 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/licenses/LICENSE-2.0 # # Unless required ...
# Copyright 2022 The TensorFlow Authors. 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 applica...
import asyncio from asyncio.subprocess import PIPE, create_subprocess_exec from asyncio.tasks import wait_for import os from decouple import config if user := config("PYTHON_USER", cast=str, default=""): from pwd import getpwnam pw = getpwnam(user) gid, uid = pw.pw_gid, pw.pw_uid def change_gid_uid(...
#YAPI Rewrite - Yet Another Package Manager #Imports import modules.config_import as config_import import modules.installer as installer import gui.interface as interface import modules.search as search import json import sys import os try: os.chdir(os.path.dirname(__file__)) #Change file location if outside of YA...
# -*- coding: utf-8 -*- from aiida.work.workchain import while_, if_ from base import SiestaBaseWorkChain class SiestaWorkChain(SiestaBaseWorkChain): @classmethod def create_outline(cls): outline = ( cls._initial_setup, cls._validate_pseudo_potentials, cls.should_...
# store information about a pizza being ordered pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra vegan cheese'] } # summarize the order print("You ordered a " + pizza['crust'] + "-crust pizza" + "with the following toppings:") for topping in pizza['toppings']: print("\t" + topping)
import glob from os import path # This file will look in src/cedar/bindings/*.cpp for all binding files # and generate a single file in src/cedar/binding_init.cpp with all the correct # funciton calls to create the builtin modules header = """ // generated by tools/scripts/generate_binding_init.py. DO NOT MODIFY na...
import numpy as np import os import pickle import random import argparse import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as trn import torchvision.transforms.functional as trnF import torchvision.datasets as dset from torchvision.utils import save_image ...
# License: Apache-2.0 from binning import bin_rare_events from ..util import util from ..transformers.transformer import Transformer from typing import List, Union, Dict import numpy as np import pandas as pd import databricks.koalas as ks import warnings class BinRareEvents(Transformer): """Replace low occurence...
from fluent_pages.extensions import page_type_pool from icekit.content_collections.page_type_plugins import ListingPagePlugin from icekit.plugins.location.models import Location from icekit_events.models import EventType import models @page_type_pool.register class AdvancedEventListingPagePlugin(ListingPagePlugin)...
import ppc_commands ppc_model = 'ppc405gp' funcs = {} ppc_commands.setup_local_functions(ppc_model, funcs) class_funcs = { ppc_model: funcs } ppc_commands.enable_generic_ppc_commands(ppc_model) ppc_commands.enable_4xx_tlb_commands(ppc_model)
def fighter() i01.moveHead(160,87) i01.moveArm("left",31,75,152,10) i01.moveArm("right",3,94,33,16) i01.moveHand("left",161,151,133,127,107,83) i01.moveHand("right",99,130,152,154,145,180) i01.moveTorso(90,90,90)
import logging class SimpleStateMachine(): def __init__(self, starting_state): self.state = [] self.state.append(starting_state) def change(self, new_state): self.state.append(new_state) def back(self): self.state.pop() def get_state(self): if se...
# Generated by Django 3.0 on 2020-06-01 16:24 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('user', '0007_medicines'), ] operations = [ migrations.RenameModel( old_name='Medicines', new_name='Medicine', ), ]...
# coding:utf-8 # --author-- lanhua.zhou from __future__ import print_function import sys import os from PySide2 import QtWidgets, QtGui, QtCore __all__ = ["TextEdit"] class TextEdit(QtWidgets.QTextEdit): def __init__(self, parent=None): super(TextEdit, self).__init__(parent) self.setStyleSheet(...
from contextlib import contextmanager import os import shutil import sys import tempfile import unittest from six import StringIO from e_out_of_date.command import main PY2 = sys.version_info[0] == 2 # https://stackoverflow.com/questions/4219717/how-to-assert-output-with-nosetest-unittest-in-python @contextmanager...
#!/usr/bin/env python import os import sys from {{ cookiecutter.project_slug }}.config import get_project_root_path, import_env_vars if __name__ == "__main__": import_env_vars(os.path.join(get_project_root_path(), 'envdir')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ cookiecutter.project_slug }}.con...
# ----------------------------------------------------------------------------- # QP/Python Library # # Port of Miro Samek's Quantum Framework to Python. The implementation takes # the liberty to depart from Miro Samek's code where the specifics of desktop # systems (compared to embedded systems) seem to warrant a diff...
import os import shutil import textwrap import pytest import salt.utils.files import salt.utils.platform import salt.utils.stringutils from tests.support.case import ModuleCase from tests.support.helpers import destructiveTest, slowTest @pytest.mark.windows_whitelisted class PyDSLRendererIncludeTestCase(ModuleCase):...
import uuid from aiohttp import web from aiohttp_session.cookie_storage import EncryptedCookieStorage import aiohttp_session from alignment.discordclient import DiscordClient class DiscordUserHandler: STATE_KEY = 'state' ACCESS_TOKEN_KEY = 'discord-access-token' def __init__(self, cook...
import unittest from ncaabb import team class TestTeam(unittest.TestCase): @classmethod def setUpClass(cls): cls.team_one = team.Team(["Team One", "Region", 1, True, 30, 30]) def test_calculate_rating(self): self.assertNotEqual(self.team_one, self.team_one.calculate_rating()...
print ("Oi, esse é o meu primeiro programa!") print (2+2) print(2-2) print(2*3)
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 09:53:57 2020 @author: Gualandi """ import numpy as np from math import sqrt from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList # Residenza Collegiali...
from __future__ import absolute_import, division, print_function import argparse import os import torch import torch.distributed as dist import torch.utils.data import _init_paths from config import cfg, update_config from datasets.dataset_factory import get_dataset from logger import Logger from models.model import...
""" Example: Shows how to create, train and use a text classifier. """ import urllib3 import feersum_nlu from feersum_nlu.rest import ApiException from examples import feersumnlu_host, feersum_nlu_auth_token # Configure API key authorization: APIKeyHeader configuration = feersum_nlu.Configuration() # con...
import re import os from paths import APP_DIR import os, shutil def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: ...
from django.conf import settings from django.contrib.sites.models import Site from oscar.apps.checkout.views import PaymentDetailsView as OscarPaymentDetailsView from oscar.apps.payment.exceptions import RedirectRequired from oscar_gocardless import facade class PaymentDetailsView(OscarPaymentDetailsView): def ...
# -*- coding: utf-8 -*- import tensorflow as tf import os.path class PrefixSaver: def __init__(self, prefix, dir_to_model, name='model', write_meta_graph=False): self.prefix = prefix if not dir_to_model: raise RuntimeError('no folder given where variables should be saved.') if ...
"""Test related functionality Adds a Pylons plugin to `nose <http://www.somethingaboutorange.com/mrl/projects/nose/>`_ that loads the Pylons app *before* scanning for doc tests. This can be configured in the projects :file:`setup.cfg` under a ``[nosetests]`` block: .. code-block:: ini [nosetests] with-pylon...
from api import create_app from config import Config application = create_app(Config)
import pytest from scripts.custom import clean_dateTime @pytest.mark.parametrize( "test_input,expected", [ ("2015", "2015"), ("2015-02", "2015-02"), ("201502", "2015-02"), ("2015-02-07", "2015-02-07"), ("20150207", "2015-02-07"), ("2015-02-07T13:28:17", "2015-0...