content
stringlengths
5
1.05M
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) def get_count(check, metric_name, modifiers): count_method = check.count def count(value, *, tags=None): count_method(metric_name, value, tags=tags) del check del modifiers ...
from django.contrib import admin from .models import Coupon @admin.register(Coupon) class CouponAdmin(admin.ModelAdmin): list_display = ['code', 'valid_from', 'valid_to', 'discount', 'active'] list_filter = ['active', 'valid_from', 'valid_to'] search_fields = ['code']
from django.urls import path from . import views app_name = "charts" urlpatterns = [ path( route="", view=views.ChartsListView.as_view(), name="list", ), path( route="form/", view=views.ChartsFormView.as_view(), name="form", ), path( route="<...
#!/usr/bin/env python3 """ ATTOM API https://api.developer.attomdata.com """ LA_GRANGE = "LA GRANGE, IL" MADISON_LA_GRANGE = {"address": "645 S MADISON AVE", "mktttlvalue": 495470, "avm": 523100, "building": {"size": 0, "baths": 2.0, "beds": 3, "bsmt": 0}, "lot": 8500, "sale": "FUTURE"} SPRING_LA_GRANGE = {"address":...
# -*- coding: utf-8 -*- """Public forms.""" from flask_wtf import Form from flask_wtf.file import FileField, FileAllowed, FileRequired from fitnotes_visualization.extensions import uploads class UploadForm(Form): """Upload Form.""" workout_data = FileField('Workout Data', validators=[FileRequired(), FileAllowe...
import requests from functions.config import * def symbol_value(symbol,type_fuction): url = "https://alpha-vantage.p.rapidapi.com/query" querystring = {"from_currency": symbol, "function": type_fuction, "to_currency": "USD"} headers = { 'x-rapidapi-key':RAPIDAPI_KEY, 'x-rapidapi-host': "a...
import pika import threading class rabbitThread(threading.Thread): def __init__(self): self._running_flag = False self.stop = threading.Event() self.connection = None self.channel = None threading.Thread.__init__(self, target=self.consume_message) def callback(self, ch, method, properties, bod...
from .abc_interpreter import Interpreter from .abc_interpreter import InputGradientInterpreter, InputOutputInterpreter, IntermediateLayerInterpreter from .lime import LIMECVInterpreter, LIMENLPInterpreter from .gradient_cam import GradCAMInterpreter from .integrated_gradients import IntGradCVInterpreter, IntGradNLPInt...
import numpy as np from sklearn.manifold import TSNE import plotly.offline as plt import plotly.graph_objs as go def example(): X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) X_embedded = TSNE(n_components=2).fit_transform(X) print(X_embedded.shape) print(X_embedded) import matplotlib.pyplot as plt ...
# -*- coding: utf-8 -*- # Author: Haoran Chen # Date: 2019-3-12 import os import subprocess import multiprocessing as mp import time Path_Train = '/home/chenhaoran/kinetics-400-video/train' Path_Val = '/home/chenhaoran/kinetics-400-video/val' Path_Test = '/home/chenhaoran/kinetics-400-video/test' Path_Train_Out =...
from struct import Struct from ocoen.filesecrets import cipher, kdf VERSION_2 = b'\xf4\x5f\xff\x73' # Fixed Block Size # Enc Info Size # Ciphertext Start # Tag Size FILE_INDEX_STRUCT = Struct('>BBHB') # Fixed Block Size # KDF Header Size # ENC Header Size ENC_INFO_STRUCT = Struct('>BBB') # Algorithm Id # Salt Leng...
from django.shortcuts import render, HttpResponse from django.utils.safestring import mark_safe import json # Create your views here. def index(request): return render(request, 'echo/index.html') def echo_image(request): return render(request, 'echo/echo_image.html') def join_chat(request, username): ret...
import os import pickle from collections import namedtuple import numpy as np TFLM_Tensor = namedtuple('TFLM_Tensor', ['tensor', 'quantization']) def import_test_data(dir_path): test = {} with open(dir_path + '/inputs.pkl','rb') as pickle_in: test["inputs"] = pickle.load(pickle_in) with open(dir_...
import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv("question-2-features.csv") df2 = pd.read_csv("question-2-labels.csv") x_train = df.to_numpy() y_train = df2.to_numpy() def add_bias(x): if (len(x.shape)==1): x=x[:,np.newaxis] b=np.ones((x.shape[0],1)) x=np.c...
import ROOT import os, time, sys, math import datetime as dt import PlotUtils import UnfoldUtils from multiprocessing import Process from tools.PlotLibrary import PLOT_SETTINGS,HistHolder from config.AnalysisConfig import AnalysisConfig from config.BackgroundFitConfig import CATEGORY_FACTORS from config.SignalDef impo...
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def set_width(self, width): self.width = width def set_height(self, height): self.height = height class Square(Rectangle): def __init__(self, size): super().__init__(si...
import os # define fixed rate for running plantbot.py INTERVAL = 10 # define slack channel + emojis CHANNEL = "general" EMOJI_LIST = ["herb", "seedling", "leaves", "fallen_leaf"] # plant definition file PLANT_DEF = './data/plant_def.json' DB_PATH = './data/plantbot.sqlite' # general images ASSET_PATH = './assets' P...
import settings import handlers.base_handler import csv class CartogramHandler(handlers.base_handler.BaseCartogramHandler): def get_name(self): return "United States (Conterminous)" def get_gen_file(self): return "{}/usa_processedmap.json".format(settings.CARTOGRAM_DATA_DIR) def vali...
from os import listdir from os.path import exists from random import choice, randrange import pygame from Errors import SpriteError from Utils import Sounds class Sprite(pygame.sprite.Sprite): '''Base sprite class Initilization arguments: *position - Start position of sprite : list ...
import random import numpy as np import random_walk_step import utilities as util class RandomWalkAny: """ Simulate a random walk in any direction represented as a weighting list of the 4 cardinal directions """ def __init__(self, speed, timestep, grid_x, grid_y): # Cardinal directions and t...
#!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu Nguyen" at 18:14, 10/04/2020 % # ...
''' test_module_taken_prior_backend.py Contains test cases related to the backend functions of modules taken prior to other modules ''' from nose.tools import assert_equal, assert_true, assert_false from components import model from components.handlers.module_taken_prior_to_others import TakePriorTo class...
"""Add User flags Revision ID: 6d9c67a35dad Revises: 7783c1dc58f7 Create Date: 2019-11-07 01:15:14.106054 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "6d9c67a35dad" down_revision = "7783c1dc58f7" branch_labels = None depends_on = None def upgrade(): #...
from app import app from bokeh.embed import components from bokeh.models import ColumnDataSource, HoverTool, NumeralTickFormatter, Legend from bokeh.plotting import figure, show from bokeh.palettes import brewer def formatter(val, type='number'): if 10**3 < val < 10**6: val = str(round(val / 10**3, 3)) + '...
class MoeVAE(): r""" Multimodal Mixture-of-Experts VAE Reference: Shi, Y., Siddharth, N., Paige, B., H.S. Torr, P., 2019. "Variational Mixture-of-Experts Autoencoders for Multi-Modal Deep Generative Models". NeurIPS. Pytorch implementation: https://github.com/iffsid/mmvae """ pass
#!/usr/bin/env python # license removed for brevity import os import sys current_folder = os.path.dirname(os.path.realpath(__file__)) sys.path.append(current_folder) main_folder = os.path.join(current_folder, "..") sys.path.append(main_folder) import numpy as np full_path = os.path.dirname(__file__) sys.p...
# -*- coding: utf-8 -*- # Copyright (C) 2014 Denys Duchier, IUT d'Orléans #============================================================================== from .action import Action2, Action3 from mud.events import DropEvent, DropInEvent class DropAction(Action2): EVENT = DropEvent RESOLVE_OBJECT = "resolve_fo...
""" Spoof requests as HTTP/1.1 You can make Scrapy send HTTP/1.1 requests by overriding the Scrapy HTTP Client Factory, with the following (undocumented) setting: DOWNLOADER_HTTPCLIENTFACTORY = 'myproject.downloader.HTTPClientFactory' imported from http://snipplr.com/view/66994/spoof-requests-as-http11/ # Snipp...
import spotipy import spotipy.util as util from sklearn.neighbors import NearestNeighbors from sklearn.preprocessing import StandardScaler, MinMaxScaler from flask import request import pandas as pd from pandas.io.json import json_normalize from flask import jsonify from joblib import load import pickle def instantia...
import uuid class TimeTravelWrapper: """ AppDaemon Test Framework Utility to simulate going forward in time """ def __init__(self, hass_mocks): # Access the `_hass_functions` through private member for now to avoid genearting deprecation # warnings while keeping compatibility. ...
""" This module is strongly inspired by / copied from xarray/plot/plot.py. """ import functools import numpy as np import xarray as xr from xarray.plot.facetgrid import _easy_facetgrid from xarray.plot.utils import ( _add_colorbar, _ensure_plottable, _process_cmap_cbar_kwargs, _update_axes, get_axi...
import discord import asyncio import os import json from fuzzywuzzy import fuzz from fuzzywuzzy import process soul = json.load(open("cfg/soul.json")) clientid = json.load(open('cfg/clientid.json')) client = discord.Client() def create_reply(m): if not m.strip() == "": output = "My database does not contain a rep...
# This Python file uses the following encoding: utf-8 """ Global Power Plant Database build_database_yemen.py Converts plant-level data from Arab Union of Electricity to the Global Power Plant Database format. Note: The AUE data is in .xls format. We need to use xlrd to read this. Note: xlrd decodes values to unicode a...
from ..utils import Object class UpdateMessageSendAcknowledged(Object): """ A request to send a message has reached the Telegram server. This doesn't mean that the message will be sent successfully or even that the send message request will be processed. This update will be sent only if the option "use_quic...
import pandas as pd import numpy as np from fbprophet import Prophet import pickle import math import scipy.optimize as optim import matplotlib.pyplot as plt from datetime import datetime, timedelta import covid19_prepare_data as prepare_data import logging logging.getLogger('fbprophet').setLevel(logging.WARNING) ...
"""This file contains rules to preprocess files before bundling""" def _update_links_impl(ctx): """Wrapper for the links-update command-line tool""" dir_name = ctx.label.name output_files = [] input_js_files = [] output_js_files = [] js_files_args = ctx.actions.args() js_files_args.set_par...
from django.db import models from django.contrib.auth import get_user_model from django.contrib.postgres.fields import ArrayField from utils.model_utils import default_1d_array_of_strings class SeoModel(models.Model): seo_title = models.CharField("SEO title", max_length=100, blank=True, null=True) seo_descri...
# Задача 4. Вариант 7. # Напишите программу, которая выводит имя, под которым скрывается Ричард Дженкинс. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех необходим...
import argparse import os import pickle import numpy as np import scipy.stats as spst from hmc import mmd from load_samples import load_samples from unit_vectors import load_unit_vectors parser = argparse.ArgumentParser(description='Compute ergodicity metrics for the Neal funnel distribution') parser.add_argument(...
"""The basic setup of the platform.""" from unittest.mock import MagicMock, patch from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.ruuvi.sensor import ( SENSOR_TYPES ) fr...
import sys sys.setrecursionlimit(500005) stdin = sys.stdin ni = lambda: int(ns()) nm = lambda: map(int, stdin.readline().split()) nl = lambda: list(nm()) ns = lambda: stdin.readline().strip() class LCADoubling: """ I used these sites as reference - https://ikatakos.com/pot/programming_algorithm/graph_th...
''' Configuration file for MS SQL Server data source @author: kong ''' # # The following parameters are used to configure the connection to # Microsoft SQL Server # server = '.\SQLEXPRESS' database = 'diet_sample_db' driver = 'SQL+Server+Native+Client+11.0' sa_string = 'mssql+pyodbc://{server}/{database}?driver={drive...
from math import ceil class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass class Paginator(object): def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True): self.object_list = object_list self.per_pa...
from __future__ import annotations import typing from ..base import Dependency if typing.TYPE_CHECKING: from ...base import Environment class Installer: def run(self, env: Environment, dependency: Dependency): raise NotImplementedError() __all__ = ["Installer"]
from threading import Thread def thread_function_runner(self, func, message): Thread(target=func, args=(self, message)).start()
from pathlib import Path import pytest from ruamel.yaml import ( YAML, ) from eth_utils import ( to_tuple, ) from py_ecc import bls # noqa: F401 from ssz.tools import ( from_formatted_dict, to_formatted_dict, ) from eth2.configs import ( Eth2Config, Eth2GenesisConfig, ) from eth2.beacon.db.c...
from __future__ import print_function import json def handler(event, context): print("received event: "+ json.dumps(event)) xgboostresult=float(event[0]['prediction']['xgboostresult']['Payload']['prediction_result']) llresult=float(event[1]['prediction']['llresult']['Payload']['prediction_result']) if xgboostr...
""" A baseline run using random actions in the mock gym. """ from utils import mock_gym import numpy as np env = mock_gym.make() observation = env.reset() steps = 10 total_reward = 0 for _ in range(steps): action = observation.target observation, reward, done, info = env.step(action) print reward total_reward +=...
from django.urls import path from . import views app_name = "profileApp" urlpatterns = [ path('profile/', views.profile, name='profile'), path('unfollow/<to_unfollow>', views.unfollow, name='unfollow'), path('follow/<to_follow>', views.follow, name='follow'), path('search/', views.se...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages console_scripts = ['counterfactualms-train=counterfactualms.experiments.calabresi.trainer:main', 'counterfactualms-test=counterfactualms.experiments.calabresi.tester:main', 'classifier-train...
import requests from django.conf import settings import re POSTMAN_URL = re.sub(r'/$', '', settings.POSTMAN_URL) def send_registration_email(email, first_name): header_obj = { "Content-Type": "application/json", "Authorization": f"Token {settings.POSTMAN_TOKEN}", } data_obj = { "r...
import logging import time from django.conf import settings from django.contrib import messages from django.contrib.auth import logout from django.core.cache import cache from django.shortcuts import redirect from biostar.accounts.models import Profile, Message from biostar.accounts.tasks import detect_location from ...
# Copyright (c) 2020 KTH Royal Institute of Technology # # 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...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from pathlib import Path from importanize.config import Config from importanize.importanize import RuntimeConfig, run_importanize_on_text from importanize.plugins import activate_plugin, deactivate_all_plugins from importa...
#!/usr/bin/python # Copyright 2013 Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of version 2 of the GNU General Public License as # published by the Free Software Foundation. """ ./id3_frames_gen.py > api/id3_frames.rst """ import sys import os sys.pa...
from store.models import Product from django.db import models from accounts.models import Account # Create your models here. class LikeProduct(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_added = models.Date...
import binascii import os import struct import types from . import libicebox # magic to attach dynamic properties to a single class instance def _attach_dynamic_properties(instance, properties): class_name = instance.__class__.__name__ + "_" child_class = type(class_name, (instance.__class__,), properties) ...
# make sure the 'allow less secure apps' is turned on for your gmail account MY_ADDRESS = 'your email adress here' MY_NAME='name that should appear in the email' PASSWORD = 'your email password'
#-*-coding:utf-8-*- ''' PENSADO E DESENVOLVIDO TOTALMENTE PARA REALIZAÇÃO E ESTUDO ACADÊMICO. Projeto desenvolvido por Joandeson Andrade com a licença MIT (Open Source). O Lancap é uma ferramenta que tem como objetivo legendar vídeos usando Deep Learning. O Objetivo principal é a propagação de conhecimento, onde até o...
import asyncio class Behaviour(asyncio.Task): def __init__(self): super(Behaviour, self).__init__() async def run(self): raise NotImplementedError
import torch from grace_dl.torch import Compressor class EFSignSGDCompressor(Compressor): def __init__(self, lr): super().__init__(average=False) self.learning_rate = lr def compress(self, tensor, name=""): """Encoding and compressing the signs """ shape = tenso...
from django import forms from .models import Whiteboard from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Field class WhiteboardForm(forms.ModelForm): class Meta: model = Whiteboard fields = ['account', 'date', 'text', 'image'] def __init__(self, *ar...
import os import shutil from os.path import abspath from unittest import mock from . import SourceTest from ... import call_pkg_config, test_stage_dir from mopack.iterutils import iterate from mopack.path import Path from mopack.sources import Package from mopack.sources.apt import AptPackage from mopack.sources.syst...
class Item(): def __init__(self, id, name, cost, image_name): self.__id = str(id) self.__name = name self.__cost = cost self.__description = ' ' self.__image_file = image_name self.__quantity = 1 self.__stock = 0 def add_quantity(self): self.__qua...
#!/usr/bin/env python # =============================================================================== import os from olympus import __scratch__ from olympus import Logger from olympus.objects import Object from olympus.utils import generate_id # ====================================================================...
import os def load_file(file):# function to load images main_dir = os.path.split(os.path.abspath(__file__))[0] file1 = os.path.join(main_dir) return file1 def write_registry(): import os.path import _winreg as winreg k='' file2=load_file('changepathspeech.py') file2...
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@googlegroups.com import os from tempfile import NamedTemporaryFile class BaseOptim...
# # This file is part of Brazil Data Cube Collection Builder. # Copyright (C) 2019-2020 INPE. # # Brazil Data Cube Collection Builder is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Define flask views for collections.""" # 3rdpar...
from django.contrib import admin from .models import Blog admin.site.register(Blog)
import unittest from tests.tests_tibiapy import TestCommons from tibiapy import BoostedCreature, InvalidContent class TestCreature(TestCommons, unittest.TestCase): # region Tibia.com Tests def test_creature_from_content(self): """Testing parsing a boosted creature""" content = self.load_resou...
# Highlights target instructions using custom colors for easy identification #@author https://AGDCServices.com #@category AGDCservices #@keybinding #@menupath #@toolbar ''' Script will search all instructions in current program looking for target instructions of interest. When found, a defined highlighting color will...
# 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 # d...
from clientes import Cliente class Banco: def __init__(self): self.cliente = None self.AGENCIA = 1111 def cadastrar_cliente(self, nome: str = " ", idade: int = 0, RG: str = ' ', CPF: int = 0): self.cliente = Cliente(nome, idade, RG, CPF) return self.cliente def cadast...
import os from functools import partial, wraps from flask import Blueprint, current_app, redirect, render_template, request, url_for from oauthlib.oauth2 import TokenExpiredError from optigurator.onshape import onshape from optigurator.optimization import run_optimization from optigurator.pareto import generate_paret...
from machine import Pin, reset, PWM class DCMotor: def __init__(self, pwm_pin, direction_pin1, direction_pin2): """ pwm_pin: PWM capable pin id. This pin should be connected to ENA/B. direction_pin1 and direction_pin1: Direction pins to be connected to ...
"""Test cases for SuperFences.""" from .. import util import unittest import markdown import pymdownx.arithmatex as arithmatex from pymdownx.util import PymdownxDeprecationWarning import warnings def custom_format_old(source, language, class_name, options, md): """Custom format.""" return '<div lang="%s" cla...
from unittest import mock import pytest from hgtools import managers def test_existing_only(): """ Test the static method RepoManager.existing_only. """ # presumably, '/' is never an hg repo - at least for our purposes, that's # a reasonable assumption. mgrs = managers.RepoManager.get_valid_...
__version__ = '4.1.2.dev0' if __name__ == '__main__': print(__version__)
""" URL to filename parsers. They can be generic or entirely site-specific, based on what type of file names the RSS contains. """ import os import re import sys from lxml import etree from slugify import slugify def _slug(string): # There are podcasts (e.g. Podcast.__init__) which mix and match underscores and ...
import tensorflow as tf import pandas as pd import h5py import numpy as np class XtomicsData: def __init__(self, array_fname='array.h5', array_ds='data', labels_ds='sample_name', metadata_fname='metadata.csv'): self.array_fname = array_fname self.arr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # módulos externos from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.toolbar import MDToolbar, MDBottomAppBar from view.widgets.genericos.dropdown import DropDownMenu from kivy.metrics import dp # módulos da aplicação from controllers.excpetions.RootException im...
from enum import Enum class Direction(Enum): forward = 0, left = 1, right = 2
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 """A tool to manage deployments in a modular fashion Usage: yorktown [-v | -h] <command> [<args>...] Options: -h, --help show this screen. -v, --version show version. Available yorktown commands: demo Demo e...
import webapp2, datetime from models.dailymail import DailyMail class SendMailHandler(webapp2.RequestHandler): def get(self): force = self.request.get('force', '0') == '1' date = self.request.get('date', None) if date: try: y,m,d = date.split('-') date = datetime.datetime(int(y), int(m), int(d)).dat...
def func1(): d = {'foo': 'bar'} print(d['foo']) try: print(d['bar']) except KeyError as e: print("bar is not in dict") def func2(): d1 = dict(foo='bar') d2 = {'foo': 'bar'} d3 = {"foo": "bar"} print(d1) print(d2) print(d3) # func1() func2()
import discord # noqa from utility import sendMessagePackets, saveData from constants import Constants from discord.ext import commands class DevTools(commands.Cog): def __init__(self, client): self.client = client """ # Events @commands.Cog.listener() async def on_message(self, message)...
import json import pytest from sqlalchemy.orm.session import Session from opencdms.models.climsoft import v4_1_1_core as climsoft_models from climsoft_api.api.qcstatusdefinition import schema as qcstatusdefinition_schema from tests.datagen import qcstatusdefinition as climsoft_qcstatusdefinition from fastapi.testclient...
from __future__ import absolute_import import six from datetime import timedelta from enum import Enum SNUBA_MAX_RESULTS = 10000 DEFAULT_EXPIRATION = timedelta(weeks=4) class ExportError(Exception): pass class ExportStatus(six.text_type, Enum): Early = "EARLY" # The download is being prepared Valid =...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'tracksscalewidget.ui' # # Created: Sun Jun 28 11:27:31 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 exc...
"""The names :py:class:`.render.Color`, :py:class:`.render.Material`, :py:class:`.render.Channel`, :py:class:`.render.ImageFormat`, :py:class:`.render.CallbackRenderer`, :py:class:`.render.BlockingRenderer`, :py:class:`.wrapper.NTracer`, :py:data:`.wrapper.CUBE` and :py:data:`.wrapper.SPHERE` are imported here for conv...
import numpy as np def normalize_probabilities(probabilities: np.ndarray) -> np.ndarray: assert len(probabilities) > 0 probabilities_sum = probabilities.sum() # if there are only zeros, we return an uniform distribution if probabilities_sum == 0: return np.array([1 / len(probabilities)] * len(...
import csv import operator from itertools import combinations from itertools import permutations ''' Reads csv file Each row is it's own list Row lists are extended onto one main list 'data' ''' def csvReader(file_directory): with open(file_directory) as f: reader = csv.reader(f) n...
#!/usr/bin/env python # # Copyright 2016 Mozilla # # 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 ag...
from django import forms from .models import Todolist, Share from django.forms import ModelForm from django.forms import formset_factory class TodolistForm(ModelForm): class Meta: model = Todolist fields = ['name', 'description', 'end_date'] widgets = { 'end_date': forms.TextIn...
from anthill.framework.handlers.base import ( RequestHandler, StaticFileHandler, WebSocketHandler, JsonWebSocketHandler, RedirectHandler, JSONHandler, JSONHandlerMixin, TemplateHandler, TemplateMixin, Handler404 ) from anthill.framework.handlers.jsonrpc import WebSocketJSONRPCHandler, JSONRPCMixin from ...
import pytest @pytest.mark.xfail() def test_should_fail(): assert 3 > 5
import sys import numpy as np import skimage import argparse import os import skimage.io as io import skimage.color as color def main(ref_dir, gen_dir): """ Compute the mean and standard deviation of the AuC metric from an image directory Args: ref_dir: reference images directory g...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Per Unneberg" __copyright__ = "Copyright 2020, Per Unneberg" __email__ = "per.unneberg@scilifelab.se" __license__ = "MIT" import os import re import tempfile from snakemake.shell import shell from snakemake.utils import logger log = snakemake.log_fmt_shell(...
from decimal import Decimal from tests.utils import _mock_gql get_prices_response = dict( getPrices=[ dict( id="1", cryptocurrency="bitcoin", buyPricePerCoin="5332823", minBuy=0.0001, maxBuy=0.04, expiresAt=2382084323, ), ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ----------------------------------------...