content
stringlengths
5
1.05M
from pynput.keyboard import Key import numpy as np import threading import time from utils.player import Player from utils.keyboard import Keyboard from utils.reader import Reader # env vars orbDist = None # screen reader reader = Reader() reader.showWindow = False reader.printDebug = False reader.selectMonitor(2...
'''Simple text input dialog''' from PyQt4 import QtGui, QtCore def text_input(question="Enter your response", default=""): app = QtGui.QApplication([]) text, ok = QtGui.QInputDialog.getText(None, '', question, QtGui.QLineEdit.Normal, default) app.quit() if ok and text: return text if ...
import robot_inspector.robot_inspector as ri # create the inspector inspector = ri.SQLInspector("config.yml") # print everything in all the tables print(inspector.get_query("log", "1=1")) print(inspector.get_query("local_log", "1=1")) print(inspector.get_query("topics", "1=1")) print(inspector.get_query("robots", "1=...
import argparse import glob import logging import os import random import shutil import json from typing import Dict, List, Tuple from argparse import Namespace import numpy as np import sklearn import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from torch.utils.data.distributed i...
#------------Librerias------------------ from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import generics ...
from __future__ import absolute_import, division, print_function import multiprocessing import traceback import pickle import sys from warnings import warn import cloudpickle from . import config from .compatibility import copyreg from .local import get_async # TODO: get better get from .optimization import fuse, c...
import asyncio import json import time from dataclasses import dataclass from typing import Dict import websockets from httpx import AsyncClient from nonebot import get_bots from nonebot.message import handle_event from src.utils.config import config from src.utils.log import logger from websockets.exceptions import C...
#!/usr/bin/python # Format of each line is: # date\ttime\tstore name\titem description\tcost\tmethod of payment # # We want elements 2 (store name) and 4 (cost) # We need to write them out to standard output, separated by a tab import sys for line in sys.stdin: end=line.find(" - - ") ipHit=line[:end] print "{0}\...
import time import btclib.ecc.dsa import btclib.ecc.ssa import coincurve from btclib.hashes import reduce_to_hlen from btclib.to_pub_key import pub_keyinfo_from_prv_key import btclib_libsecp256k1.dsa import btclib_libsecp256k1.ssa prvkey = 1 pubkey_bytes = pub_keyinfo_from_prv_key(prvkey)[0] msg_bytes = reduce_to_h...
import pickle from revscoring.datasources import revision_oriented from revscoring.dependencies import solve from revscoring.languages import portuguese from .util import compare_extraction BAD = [ "babaca", "babacas", "babacão", "babacões", "babaquice", "bixa", "bixas", "bicha", "bichas", "boiola", "boi...
import os import socket import struct import select from multiprocessing import Process, Lock from msgpack import packb, unpackb from datetime import datetime THINKNODE_HOST = os.getenv("THINKNODE_HOST") THINKNODE_PORT = int(os.getenv("THINKNODE_PORT")) THINKNODE_PID = os.getenv("THINKNODE_PID") BUFFER_SIZE = 4096 d...
""" String utility methods to be used in templates. """ from django import template register = template.Library() def to_field_name(value): """ This template tag is used to convert a list of words into a single word that does not contain spaces. The words are capitalized as they are joined. It...
# -*- coding: utf-8 -*- from pathlib import Path import os print('Warning this will permanently delete the zip file(s)\n') pixivDirectory = input('Enter Pixiv directory: ') print() for path in Path(pixivDirectory).rglob('*.ugoira'): ugo_name = str(path) zipfile_name = f'{ugo_name[:-7]}.zip' t...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 3rd party imports import numpy as np import xarray as xr __author__ = "Louis Richard" __email__ = "louisr@irfu.se" __copyright__ = "Copyright 2020-2021" __license__ = "MIT" __version__ = "2.3.7" __status__ = "Prototype" def mva(inp, flag: str = "mvar"): r"""Comput...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F class Discriminator(nn.Module): """ This class implements the discriminator network """ def __init__(self, channels: Tuple[int] = (64, 256, 256, 128, 1), in_channels: int = 3, frames: int = 6) -> None: ...
import collections from typing import Callable, Union import torch.nn as nn from ..modules import BlurPool2d, DropBlock, SEModule def ResNetOperation( *args, block_type='basic', layer_type='basic', **kwargs, ) -> nn.Module: if block_type == 'basic' and layer_type == 'basic': return Basic...
#!/usr/bin/env python import sys import adns import ADNS from hashlib import md5 sys.path.append('.') from dns.utils import status_name def callback(answer, name, rr, flags, data): print name, data, status_name(answer[0]) for entry in answer[3]: if data == 'SOA': print ' ', entry[0] ...
import flask import re from ..authenticated_blueprint_preparator import AuthenticatedBlueprintPreparator name = 'api-description' app = AuthenticatedBlueprintPreparator(name, __name__, template_folder='templates') def strip_leading_space(s): if s is None: return '<no docstring>' leading_spaces = re.co...
import os import sys import importlib # Loop over every directory beneath us that has a __init__.py inside of it root_dir = os.path.dirname(__file__) for module_name in os.listdir(root_dir): if not os.path.isdir(os.path.join(root_dir, module_name)) or not os.path.isfile(os.path.join(root_dir, module_name, '__init_...
""" You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?). The valid times are those inclusively between 00:00 and 23:59. Return the latest valid time you can get from time by replacing the hidden digits. """ class Solution1736: ...
import os import glob import hashlib import logging import argparse import tensorflow as tf import numpy as np from collections import defaultdict from lxml import etree from pprint import pprint from tensorflow.core.example import example_pb2 from tensorflow.core.example import feature_pb2 """ bjenei: This script is ...
from utils import misc_utils from datetime import datetime from psycopg2.extras import Json, DictCursor import psycopg2 import importlib.util import pandas as pd import yaml from functools import reduce num2words = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', \ 6: 'six', 7: 'seven', 8: 'eight', ...
import click from jira import JIRA from contextManagerRequests import no_ssl_verification @click.command() @click.option('--source', prompt='Source Project', help='Origin of the data, jira project XXX') @click.option('--prefix', prompt='Prefix', help='Prefix for the release names') def rename(source, prefix): wit...
import subprocess import re import helper class MULSolve: def __init__(self,opnd1,opnd2,filename="mul_tb.v"): self.opnd1 = opnd1 self.opnd2 = opnd2 self.filename = filename def solve(self): flag = 0 if self.opnd1 < 0 and self.opnd2 < 0: self.opnd1 = self.opnd1 * -1 self.opnd2 = self.opnd2 * -1 f...
""" Missing residues in protein structures of DNA-PKcs ================================================== This script creates two bars, each indicating gaps in the structure of DNA-PKcs. The top bar indicates the missing residues in a recent crystal structure (PDB: 5LUQ), the bottom bar indicates missing residues in a...
import copy import logging as _logger _logger.basicConfig(level='INFO') class Prototype: def __init__(self) -> None: self._objects = {} def register_object(self, name: str, obj: object) -> None: """ Register an object """ self._objects[name] = obj def unregister_object(self, na...
from __future__ import print_function from __future__ import absolute_import import rdflib as R from .DataTestTemplate import _DataTest from owmeta_core.statement import Statement from owmeta_core.property_value import PropertyValue from owmeta_core.dataobject import DataObject from owmeta_core.dataobject_property im...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 13 14:20:15 2022 @author: bobrokerson """ # Task: # Two words “interlock” if taking alternating letters from each forms a new # word. For example, “shoe” and “cold” interlock to form “schooled.” # 1. Write a program that finds all pairs of words th...
from vumi.persist.fields import Field from go.vumitools.routing_table import RoutingTable class RoutingTableField(Field): """Field that represents a routing table. This is just a JSON object wrapped in a RoutingTable helper class. """ def custom_to_riak(self, value): return value._routing_t...
import numpy as np import matplotlib.pyplot as plt import itertools ### def sigmoid(z): return 1 / (1 + np.exp(-z)) def gradient(dataset, w): g = np.zeros(len(w)) for x,y in dataset: x = np.array(x) error = sigmoid(w.T.dot(x)) g += (error - y) * x return g / len(dataset) def ...
import propresenter from propresenter.files.pro6Template import File as p6t p6t("Default.pro6Template", propresenter.appDataLocation+"\\Templates") #import propresenter.registry ''' %PROGRAMDATA%\Renewed Vision\Bibles %PROGRAMFILESX86%\Renewed Vision\ProPresenter 6 HKCU\Software\Renewed Vision\ProPresenter 6 REG_SZ I...
# The conftest.py file serves as a means of providing # fixtures for an entire directory. # Fixtures defined in a conftest.py can be used by any # test in that package without needing to import them # (pytest will automatically discover them). # https://docs.pytest.org/en/latest/reference/fixtures.html # #conftes...
#!/usr/bin/env python3 from utils.nginx_page_helper import NginxPage import time from retry.api import retry_call from utils.tools import get_request_text from utils.log_helper import logger from utils.init_helper import BaseInit from utils.config import get_config from utils.nginx_module_helper import NginxModule ...
import random import string import time from fastapi import HTTPException from pydantic import BaseModel, Field from typing import List, Dict import pymongo.database def create_random_string(length: int = 32) -> str: return "".join( random.choice(string.ascii_letters + string.digits) for _ in range(length...
import logging import unittest import textwrap from typing import Any, Dict, List from test import mixins from unittest import mock from bigflow.build import spec class ReadSpecTestCase( mixins.TempCwdMixin, unittest.TestCase, ): def test_should_raise_error_when_cant_find_deployment_config(self): ...
from os.path import abspath, join, dirname import sys import bax_insertion.data from bax_insertion.data import parse_data data_path = dirname(sys.modules['bax_insertion.data'].__file__) data_file = abspath(join(data_path, 'KD2_dataset.xlsx')) # This list must match the order in the spreadsheet exactly nbd_residues = ...
from prettytable import PrettyTable def main(): nama_minuman = ['Sprite', 'Coca-cola', 'Mizone', 'Pocari Sweat', 'Teh Botol Sosro'] harga_minuman = [7000, 12000, 7500, ...
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT...
from matplotlib import pyplot import numpy x_max = 20 x = numpy.linspace(-x_max, x_max, 1024) def f(z, theta=0.0): return numpy.exp(numpy.e*z) + numpy.exp(numpy.pi*z) + numpy.exp(theta*1.0j) def f_prime(z, theta=0.0): return numpy.e*numpy.exp(numpy.e*z) + numpy.pi*numpy.exp(numpy.pi*z) def G(u, v): retu...
import pygame from Player import Player from weapon import Pistol, ShotGun, MachineGun, Sword from typing import List, Tuple import random BOX_IMAGE = "box.png" HEAL = [10, 25, 40, 75] WEAPONS = [Pistol, ShotGun, MachineGun, Sword] class Box(pygame.sprite.Sprite): """Item box""" position: Tuple def __in...
from nose import with_setup from webdnn.graph.attribute import Attribute from webdnn.graph.graph import Graph from webdnn.graph.node import Node from webdnn.graph.operator import Operator from webdnn.graph.order import OrderNC from webdnn.graph.traverse import check_attribute_match, check_node_type_match, search_sub_s...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import build_norm_layer from mmcv.runner import BaseModule from ..builder import HEADS from ..utils import MultiPooling, accuracy @HEADS.register_module() class MultiClsHead(BaseModule): """Multiple classifier heads. This he...
import urllib.request urllib.request.urlretrieve("https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2016-01.csv", "yellow_tripdata_2016-01.csv") import duckdb conn = duckdb.connect('ytd.duckdb') cursor = conn.cursor() cursor.execute(""" CREATE TABLE yellow_tripdata_2016_01 ( VendorID bigint, tpep...
""" Copyright (c) 2020 Alex Forencich 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, distribute...
from django.db import models from cars.models import PersonalCar from users.models import User # Create your models here. class JobList(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class JobOnCar(models.Model): user = models.ForeignKey...
from django.db import models from django.conf import settings from utils.models.abstract import DatetimeCreatedModel class Todo(DatetimeCreatedModel): """Our todo model.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="todos" ) tit...
def filter_numbers(string): return ''.join(a for a in string if not a.isdigit())
from weakref import WeakValueDictionary, WeakKeyDictionary, _IterationGuard def copy_wvd(self): if self._pending_removals: self._commit_removals() new = WeakValueDictionary() with _IterationGuard(self): for key, wr in self.data.items(): o = wr() if o is not None: ...
"""Tests for aiohttp/worker.py""" import asyncio import unittest import unittest.mock try: from aiohttp import worker except ImportError as error: # pragma: no cover raise unittest.SkipTest('gunicorn required') from error class TestWorker(worker.GunicornWebWorker): def __init__(self): self.serv...
import logging import sys from django.conf import settings from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.template.defaultfilters import slugify from apps.devicetemplate.models import DeviceTemplate from apps.org.models import Org from apps.physicaldevic...
from mesh_to_sdf import mesh_to_voxels import trimesh import numpy as np import skimage.measure import pyrender mesh = trimesh.load('/home/exx/georgey/dataset/hippocampus/obj/AD_pos/100_S_5106_I369381/LHippo_60k.obj') # voxels = mesh_to_voxels(mesh, 64, pad=True) # print(voxels.shape) # # vertices, faces, normals, _...
from flask import Blueprint, jsonify from .services import hello main_view = Blueprint('main_view', __name__) @main_view.route('/api/hello/<path:name>') def helloRoute(name : str): return hello(name)
Integers - Check Triplets The program must accept N integers as the input. The program must print Yes if there is at least one triplet (a, b, c) in the given N integers where a2 + b2 = c2. Else the program must print No as the output. Example Input/Output 1: Input: 7 5 1 3 6 7 2 4 Output: Yes Explanation: Here the tri...
#================================= # the main code for emr # author: Lily # created: 2022.2.2 #================================= from emr.db import load_db, update_db import emr from emr import AVAILABLE_INNITIAL, INITIAL_DATA, GROUP_DISCOUNT, DISCOUNT_MAX_ACOUNT, PURCHASING_TIME, UNIT_PRICE, GROUP_DISCOUNT emr.data ...
import os from subprocess import SubprocessError from tempfile import TemporaryDirectory from typing import List import zkay.jsnark_interface.jsnark_interface as jsnark import zkay.jsnark_interface.libsnark_interface as libsnark from zkay.transaction.interface import ZkayProverInterface, ProofGenerationError from zkay...
"""Collections of functions that helps to build the lane finder package.""" import cv2 import numpy as np def get_perspective_transform(image, src_in=None, dst_in=None): if src_in is None: src = np.array([[585. , 455], [705. , 455], [1130., 720], ...
load("@rules_pkg//pkg:pkg.bzl", "pkg_tar") load("@rules_pkg//pkg:deb.bzl", "pkg_deb") GLIBC_MIN_VERSION = "2.27" def envoy_pkg_deb( name, data, homepage = "https://www.envoyproxy.io/", description = "Envoy built for Debian/Ubuntu", preinst = "//distribution/debian:preinst", ...
#!/usr/bin/env python ############################################################ # # Python client to query the GOCDB programmatic interface, # retrieve info about downtimes for a top entity region # using curl, parse xml output with the xml.dom.minidom mudule # and store data into a MySQl db. # # Giuseppe Misur...
from extend_euserv import __version__ from logzero import logger # pytest --log-cli-level=10 tests\test_extend_euserv.py def test_version(): logger.debug("debug version: %s", __version__) # pytest -s logger.info("info version: %s", __version__) print("print version: %s" % __version__) assert __versi...
# coding: utf-8 import pylab import scipy.integrate import fenics as fe import numpy as np import matplotlib.pyplot as plt def setup_vectorspace(mesh): """setup""" V = fe.VectorFunctionSpace(mesh, "CG", 1, dim=3) v = fe.TestFunction(V) u = fe.TrialFunction(V) m = fe.Function(V) Heff = fe.Funct...
import json from flask import g, request, render_template from flask.views import View from godmode import logging from godmode.acl import ACL from godmode.audit_log import audit_log from godmode.exceptions import AccessDenied log = logging.getLogger(__name__) class BaseAction(View): name = None title = No...
"""adding notes column Revision ID: 4de8f69a75d1 Revises: 2ab7af991b87 Create Date: 2013-10-29 15:43:13.132113 """ # revision identifiers, used by Alembic. revision = '4de8f69a75d1' down_revision = '2ab7af991b87' from alembic import op import sqlalchemy as sa def upgrade(): conn = op.get_bind() columns = ...
# Question 10 # Level 2 # # Question: # Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. # Suppose the following input is supplied to the program: # hello world and practice makes perfect and hello w...
from django.contrib.auth.models import BaseUserManager from django.db import models class BaseEmailUserManager(BaseUserManager): use_in_migrations = True def get_by_natural_key(self, email): return self.get(email=email) def _create_user(self, email, password, **extra_fields): email = sel...
#!/usr/bin/env python3 import sys def vadd(v1, v2): return tuple(x + y for x, y in zip(v1, v2)) ADIRS = [(x,y) for x in [-1,0,1] for y in [-1,0,1] if not x == y == 0] def step(m): for k in list(m): m[k] += 1 togo = [k for k, v in m.items() if v > 9] flashes = 0 while togo: flash...
# # Middle-aged Cinderella software to run forever # import machine import time TEST_MODE = False # Declare devices button = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP) pin = machine.Pin(15, machine.Pin.OUT) # Variables global mode, loops_to_run, silent_steps, vibration_steps, step, silent, current_iterati...
import numpy as np import matplotlib.pyplot as plt import time import pickle from run_episode import find_reachable_frontier_indices2 # from util import get_traversable_colors # def get_fov_aware_goal_array(raw_goal_array): # # global ENVIRONMENT # # If the raw goal_array contains an axis that defines what th...
from pony.orm import count from .model import Document MAX_LIMIT = 20 class DocumentCollection(object): def __init__(self, offset, limit): self.offset = offset self.limit = min(limit, MAX_LIMIT) def query(self): return Document.select().limit(self.limit, offset=self.offset) def ...
import os import sys import unittest from libs.lib import struct, newAction, newIcon, addActions, fmtShortcut, generateColorByText class TestLib(unittest.TestCase): def test_generateColorByGivingUniceText_noError(self): res = generateColorByText(u'\u958B\u555F\u76EE\u9304') self.assertTrue(res.gre...
from itertools import groupby def count_unique_questions_in_group(group): return len(set("".join(group))) with open('input.txt') as f: lines = [x.strip() for x in f.readlines()] grouping = groupby(lines, lambda x: x == "") groups = [list(group) for k, group in grouping if not k] sum_of_counts =...
{ "targets": [ { "target_name": "hello", "sources": [ "hello.cc" ], "include_dirs": [ "include" ], "libraries": [ "<(module_root_dir)/libgoaddon.a" ] } ] }
import numpy as np import torch from torch.utils.data import Dataset import scipy.misc as m import random class gtsrbLoader(Dataset): def __init__(self, root, exp, split='train', is_transform=False, img_size=None, augmentations=None, prototype_sampling_rate=0.005): super().__init__() if split == 'train': ...
# flake8: noqa from sourced.ml.models.bow import BOW from sourced.ml.models.coocc import Cooccurrences from sourced.ml.models.df import DocumentFrequencies from sourced.ml.models.ordered_df import OrderedDocumentFrequencies from sourced.ml.models.id2vec import Id2Vec from sourced.ml.models.tensorflow import TensorFlowM...
from unittest import mock import os from django import forms from django.conf import settings from django.test import LiveServerTestCase, Client from urllib.request import urlopen from media_example.forms import UploadForm from media_example.views import media_example class Exercise6Test(LiveServerTestCase): de...
from typing import List class Mention(object): def __init__(self, doc_id: str, sent_id: int, tokens_number: List[int], tokens_str: str, coref_chain: str, context: str = None): ''' :param doc_id: the document ID :param sent_id: the mention sentence ID :param tokens...
import json from ibm_watson import SpeechToTextV1 # Create a connection to the speech to text service speech_to_text = SpeechToTextV1( iam_apikey='f6nEkrdAJdvluiBI74xhnlQ134HcHFxxrL21Krii_0Gg', url='https://stream.watsonplatform.net/speech-to-text/api') # Identify the source audio file file = 'Transfe...
# coding: utf8 """ 题目链接: https://leetcode.com/problems/single-number/description. 题目描述: Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ...
# pylint: disable=fixme """ Library files for adding, moving, verifying files ,etc """ import grp import os import os.path as os_path import pwd import shutil from texttable import Texttable from logical_backup.objects.device import Device from logical_backup.objects.file import File from logical_backup.objects.folder...
import unittest import pytest import sysaudit def hook(event, args): pass @pytest.mark.benchmark(group="audit") def test_csysaudit_audit(benchmark): sysaudit.csysaudit_addaudithook(hook) benchmark(sysaudit.csysaudit_audit, "event", 1, 2, 3) @pytest.mark.benchmark(group="audit") def test_std_audit(b...
from networkx import NetworkXError from sortedcontainers import SortedDict from dynetworkx.classes.intervalgraph import IntervalGraph from dynetworkx.classes.intervaltree import IntervalTree from networkx.classes.digraph import DiGraph from networkx.classes.multidigraph import MultiDiGraph class IntervalDiGraph(Inte...
""" Copyright (c) College of Mechatronics and Control Engineering, Shenzhen University. All rights reserved. Description : Author:Team Li """ """ 1. Two Sum Easy Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exact...
import random from collections import Counter import torch from torch.nn.functional import cosine_similarity from src.const import IMBD_ROOT from src.dataset import ( ImdbReviewsDataset, get_test_dataset, collate_docs, SimilarRandSampler, TXT_CLIP, SNT_CLIP ) from src.model import HAN, get_pretrained_embe...
import re from setuptools import setup # type: ignore with open("voltage/__init__.py") as f: match = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE) if match is not None: version = match.group(1) else: raise RuntimeError("version is not set") with open("requi...
#!/usr/bin/env python3 import os import sys import subprocess from wasabi import msg tests = [ "mypy --config-file setup.cfg scrubadub_address/", "flake8 --config setup.cfg scrubadub_address/", # If py3.5 then examples with spacy don't work so disable doctests 'if python3 --version | grep -Evq "Pyth...
""" Hello world """ print('Hello word')
#!/usr/bin/env python3 """ Unit tester for genome_iterator.py Python version: Python 3.6.8 :: Anaconda, Inc. Date: 02/28/2019 Dependencies: - unittest - pandas>=0.22.0 """ import unittest import pandas as pd from primer_tk import genome_iterator as gi class TestGenomeIterator(unittest.TestCase): """ Subcla...
# encoding: utf-8 from .lr_scheduler import WarmupMultiStepLR
''' This is a re-implmentation of the Python code that implements the HaarPSI metric introduced in the following paper: R. Reisenhofer, S. Bosse, G. Kutyniok and T. Wiegand. A Haar Wavelet-Based Perceptual Similarity Index for Image Quality Assessment. (PDF) Signal Processing: Image Communication, vol. 61, 33-43, 201...
"""A test that is run only by Github Actions This test makes real network requests, so environment variables should be specified in Github Actions. """ import os import pytest from asyncpraw import Reddit from asyncpraw.models import Submission @pytest.mark.skipif( not os.getenv("NETWORK_TEST_CLIENT_ID"), ...
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lic...
import unittest import math def norm(*args): return math.sqrt(sum(v ** 2 for v in args)) class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(norm(4, 3), 5) if __name__ == '__main__': unittest.main()
"""Main subapp.""" from flask import Blueprint main = Blueprint("main", __name__) from . import views, forms, errors # noqa: E402 __all__ = ["main", "views", "forms", "errors"]
import json from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.shortcuts import get_object_or_404, get_list_or_404 from django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse from .models ...
from FotMoby import FotMoby as fm r_league = fm.getLeague() print(r_league.json())
# Generated by Django 2.1.7 on 2019-03-28 22:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('steambird', '0003_auto_20190328_2300'), ] operations = [ migrations.AddField( model_name='course', name='course_code...
def cellTowers(houses, radius): if(len(houses) == 0): return 0; towers = 0; # first tower placement distance = houses[0] + radius; towers += 1; # find all other towers for house in houses: if(abs(house - distance)) > radius: towers += 1; distance =...
# Copyright 2018 Abraham cabrera. import os from abc import ABC, abstractmethod from enum import Enum class ConnectionFactoryType(Enum): UNSUPPORTED = 0 MONGODB = 1 class ConnectionFactory(ABC): @abstractmethod def get_connection(self): pass def get_mongodb_properties(): port = int(o...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^name/(?P<name>[a-z]+)$', views.name), url(r'^books/', views.allbooks) ]
from typing import List class Traceback: @staticmethod def format_exception(exception, file : str, trash_exception): return Traceback.format_traceback_list(Traceback.exception_to_traceback_list(exception, file, trash_exception)) @staticmethod def exception_to_traceback_list(exception, ...
import math def abs_diff(x, y): return abs(min(x, y) - max(x,y)) midpoint = lambda x: (x[0] + x[-1])/2.0 def balanceSteps(steps): m = midpoint(steps) shift = abs_diff(m, 0) if abs(min(steps)) < abs(max(steps)): shifted = [step - shift for step in steps] else: shifted = [step + sh...