text
stringlengths
3.07k
12.6k
import gzip import json import shutil from dataclasses import dataclass from pathlib import Path from typing import Awaitable, Callable, Dict, List, Optional, Tuple import aiofiles from virtool_core.utils import compress_file, decompress_file from virtool_workflow import data_model from virtool_workflow.api.indexes im...
''' Script for collecting and processing the ZAP github stats ''' import csv import utils import glob import json import os import sys tags = [ "v2.11.0", "v2.10.0", "v2.9.0", "v2.8.0", ] mappings = { "core": "core", "crossplatform": "cross", "linux": "linux", "unix": "unix", "deb": "deb...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import inspect import logging import six import warnings from concurrency.exceptions import RecordModifiedError logger = logging.getLogger(__name__) def deprecated(replacement=None, version=None): """A decorator which can be used ...
# type: ignore import argparse import dataclasses import json import logging from dataclasses import dataclass from typing import Dict, List, Optional, Union import pytorch_lightning as pl from overrides import overrides from torch.utils.data import DataLoader, Dataset from transformers import PreTrainedTokenizer lo...
import requests import json class Smogon(): BASE_URL = "http://www.smogon.com/dex/api/query" def __init__(self): self.url = self.BASE_URL @staticmethod def convert_to_dict(poke_list): poke_dict = {} for poke in poke_list: poke_dict[poke['name']] = SmogonPokemon.from...
from typing import Any, List import matplotlib.pyplot as plt # type:ignore import numpy as np import pandas as pd # type:ignore import constants import trajectory # sanity check trajectories group at a time MUZZLE_VELOCITY_MIN_M_S: float = 5 MUZZLE_VELOCITY_MAX_M_S: float = 14 GUN_ELEVATION_MIN_DEGREES: float = 35 GU...
# Copyright 2015 Tesora Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
import os from flask import Flask, render_template, request, url_for, send_from_directory from PIL import Image import numpy as np import time import platform from Model import Model import random import cv2 from io import StringIO, BytesIO import base64 from datetime import datetime import json def readb64(base64_str...
def to_superscript(number): supers = '⁰¹²³⁴⁵⁶⁷⁸⁹' return ''.join((supers[int(d)] for d in str(number))) def format_coefficient(coeff, allow_one = False): if coeff == 1 and not allow_one: return '' if coeff % 1 == 0: return str(int(coeff)) return str(coeff) class Polynomial: ...
import os import re import time import webbrowser import steam.webauth as wa from bs4 import BeautifulSoup as bs def log(text: str, printdate: bool = True, printmessage: bool = True, writetofile: bool = True) -> str: """Prints the text in the console and saves it in log file :param text: text you ...
import mistune import bs4, os from emoji import emojize from build_static import add_css, add_script, include_resource from grammar import markdown_parser import logging import CDN_assets as assets logger = logging.getLogger("miniprez") _video_extensions = set(["mp4", "webm", "flac"]) def slide_parser(html): """ ...
""" Simplest aggregation algorythms tests on different datasets Testing all boundary conditions and asserts """ import pytest import pandas as pd from crowdkit.aggregation import MajorityVote, MMSR, Wawa, GoldMajorityVote, ZeroBasedSkill from .data_mv import * # noqa: F401, F403 from .data_mmsr import * # noqa: F4...
#import math from scipy import constants class Position(): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def to_string(self): return "({0}, {1}, {2})".format(self.x, self.y, self.z) class Velocity(): def __init__(self, x, y, z): self.x...
import prodigy from prodigy.components.loaders import Audio, Video, JSONL, ImageServer from plumcot_prodigy.forced_alignment import ForcedAlignment from plumcot_prodigy.video import mkv_to_base64 from plumcot_prodigy.custom_loaders import * from prodigy.components.preprocess import add_tokens, fetch_media from prodigy....
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
import pygame from pygame.locals import * import math from algorithms import bfs, dfs, A_Star from maze import generateMaze from random import randint WIDTH = 900 HEIGHT = 900 FPS = 240 clock = pygame.time.Clock() WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Path Finding Algorithm Visual...
import pytest import astropy.units as u from astropy.time import TimeDelta from astropy.time import Time from sunpy.time.timerange import TimeRange from sunpy.net.dataretriever.client import QueryResponse import sunpy.net.dataretriever.sources.norh as norh from sunpy.net.fido_factory import UnifiedResponse from sunpy...
import tkinter.ttk as ttk import tkinter as gui import button as btn import player from filehandler import is_file_there import misc def higher_volume(): vol = volume.get() vol = vol + 3 if vol <= 100: volume.set(vol) elif vol > 100: volume.set(100) def lower_volume(...
"""Data Files Convertor This script allows the user to convert different data types. This tool accepts comma separated value files (.csv) as well as apache parquet (.parquet) files. It is assumed that the first row of the spreadsheet is the location of the columns. This script requires that `pandas`, `pyarrow`, `ar...
"""Assignment - Blocky === === <NAME> and <NAME> Department of Computer Science, University of Toronto === Module Description === This file contains the player class hierarchy. """ import random from typing import Optional import pygame from renderer import Renderer from block import Block from goal import Goal ...
# # Copyright (c) 2017 Electronic Arts Inc. All Rights Reserved # from __future__ import print_function from __future__ import absolute_import from builtins import object import json import shutil import os import re import time import logging import threading from sys import platform from .base import BaseJob cla...
from argparse import ArgumentParser, FileType from collections import namedtuple from csv import DictReader from io import StringIO from itertools import groupby import re import sys TAHESTIK = 'ABCDEFGHIJKLMNOPQRSŠZŽTUVWÕÄÖÜXY' LINGID = ' · '.join('[[#{taht}|{taht}]]'.format(taht=t) for t in TAHESTIK) WIKI_HEADER = ...
# <NAME> # Flores Lab # Department of Agricultural and Biosystems Engineering # North Dakota State University import sys import argparse import cv2 import numpy as np def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument("--video_device", dest="video_device", help...
######################################################## # Author: <NAME> # Organization: Eindhoven University of Technology ######################################################## import numpy as np import torch import torch.nn as nn import torch.nn.functional as F """ class: __upsample_zeropadding_2D__ Descri...
# -*- coding: utf-8 -*- import optparse import os import sys import yaml import ansiblelint from ansiblelint.version import __version__ _PATH_VARS = ['exclude_paths', 'rulesdir', ] INVALID_CONFIG_RC = 2 def abspath(path, base_dir): """Make relative path absolute relative to given directory. Args: ...
#! /usr/bin/python3 # # Copyright (c) 2020 <NAME> <<EMAIL>> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. #...
""" 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 "License"); you may not use this ...
import requests from bs4 import BeautifulSoup import pandas as pd import seoulbus as sb import seoulsubway as ssub subway_route = pd.read_csv('subway_with_time.csv', encoding='utf-8') subway_route.astype({'time':float}) def get_path_by_subway(start_x, start_y, end_x, end_y): url = 'http://ws.bus.go.kr/api/rest/p...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Collection of parser fonctions for qitests actions """ from __future__ import absolute_import from __future__ import un...
import keyboard import psutil from pprint import pprint import time import requests import _thread, base64 #https://github.com/boppreh/keyboard#api #keyboard.press_and_release('shift+s, space') #keyboard.write('The quick brown fox jumps over the lazy dog.') #keyboard.wait('esc') special = {'enter' :'[en]\n', ...
from flask import Flask, jsonify, request, redirect, make_response import logging, sys, time import cv2 import numpy as np import os, re from werkzeug.datastructures import ImmutableMultiDict import face_recognition import json from google.cloud import firestore from datetime import date # Intializion code. Also reduc...
import itertools import numpy from ..helpers import n_outer class NCubeScheme: def __init__(self, name, dim, weights, points, degree, citation): self.name = name self.dim = dim self.degree = degree self.citation = citation if weights.dtype == numpy.float64: s...
from django.shortcuts import render, render_to_response import json import traceback import sys import csv import os from django.shortcuts import render from django import forms from django.db.models import Q from player_info import find_players NOPREF_STR = 'No preference' RES_DIR = os.path.join(os.path.dirname(__f...
# Copyright (c) 2019. Partners HealthCare and other members of # Forome Association # # Developed by <NAME> based on contributions by <NAME>, # <NAME>, <NAME> and other members of Division of # Genetics, Brigham and Women's Hospital # # Licensed under the Apache License, Version 2.0 (the "License"); # you may no...
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
__source__ = 'https://leetcode.com/problems/basic-calculator-iii/description/' # Time: O() # Space: O() # # https://leetcode.com/problems/basic-calculator-iii/discuss/113592/Development-of-a-generic-solution-for-the-series-of-the-calculator-problems # # Description: Leetcode # 772. Basic Calculator III # # Implement a...
import argparse import csv import json import logging from pathlib import Path from typing import Iterable, Optional from tapi_yandex_direct import YandexDirect, exceptions LOGGING_FORMAT = "%(asctime)s [%(levelname)s] %(pathname)s:%(funcName)s %(message)s" logging.basicConfig(format=LOGGING_FORMAT, level=logging.D...
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Test stylus functionality. Description ----------- Verifies if stylus is functional by asking operator to draw specified lines or shapes using stylus....
from ask import alexa from datetime import date, timedelta, datetime from pytz import timezone import pytz import requests LOGS_ENDPOINT = "https://thawing-basin-65008.herokuapp.com/logs/" DATE_FMT = "%m-%d-%Y" TIME_FMT = "%I:%M:00 %p" CURRENT_TZ = timezone("US/Pacific") # Change this when I go back to SWAT ATTR_MAP ...
from typing import List, Optional from uuid import UUID from essentials.exceptions import ObjectNotFound from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql import text from sqlalchemy.sql.expression import delete, select from domain.vfs import ( FileImageData, FileSystemDataProvider, File...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman **Product Home Page:** http://www.makehumancommunity.org/ **Github Code Home Page:** https://github.com/makehumancommunity/ **Authors:** <NAME>, <NAME> **Copyright(c):** MakeHuman Team 2001-2019 **Licensing:** ...
""" Module contains class ErrorInfo. Structure for errors. """ import inspect from typing import Dict, Union from FaceEngine import FSDKErrorResult # pylint: disable=E0611,E0401 class ErrorInfo: """ Error info Attributes: errorCode (int): error code desc (str): error description ...
import numpy as np import pandas as pd from matplotlib import pyplot as plt import time import argparse from pathlib import Path import pickle import torch from torch import nn, optim from torch.autograd import Variable from model import Model import utils np.random.seed(42) parser = argparse.ArgumentParser(descri...
# # Copyright © 2022 <NAME>, <NAME>, <NAME>, # <NAME>, <NAME> # # 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 t...
import pandas as pd import numpy as np from sklearn.preprocessing import Imputer from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelBinarizer from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import FeatureUni...
# coding=utf-8 # Copyright 2021 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
#! -*- coding: utf-8 -*- # Author: <NAME> <<EMAIL>> """ Reference: DeepCrack: A deep hierarchical feature learning architecture for crack segmentation. https://www.sciencedirect.com/science/article/pii/S0925231219300566 """ import torch import torch.nn as nn import torch.nn.functional as F from myapp.DeepSegmento...
# Credits to https://github.com/ZHKKKe/MODNet for the model. import streamlit as st import numpy as np import matplotlib.pyplot as plt import time import os from PIL import Image, ImageColor from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as tr...
import argparse import torch import torch.autograd as autograd import torch.nn.functional as F parser = argparse.ArgumentParser(description='CNN Ranking') parser.add_argument('--epochs', type=int, default=32, help='number of epochs for train [default: 32]') parser.add_argument('--batch-size', type...
import ctypes import os from PIL import Image, ImageFont, ImageDraw import cv2.cv2 as cv import numpy as np import win32con import win32gui import win32ui def cv_imread(file_path): """读取图片 为支持中文文件名, 不能使用cv.imread """ return cv.imdecode(np.fromfile(file_path, dtype='uint8'), cv.IMREAD_UNCHANGED) def...
from djangae.contrib.gauth.backends import AppEngineUserAPI from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from django.db.utils import IntegrityError from django.http.response import HttpResponse from django.template import Template, Context from django.test import T...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # GUI module generated by PAGE version 6.2 # in conjunction with Tcl version 8.6 # Sep 16, 2021 01:59:13 PM IST platform: Windows NT import sys from tkinter import font try: import Tkinter as tk except ImportError: import tkinter as tk try: ...
#!/usr/bin/env python """ Regression test script. Usage: From this directory, call this script with python: python run_tests.py Notes: - Requires Python 2.7+. (compliant with Python 3) - This file should not be modified when adding new scripts. - To add a new script, create a new .py file in scripts/test...
# Client configuration of MRS1000c LiDAR from __CLIENT__ import * from __INIT__ import * from __VISUALS__ import strip from visuals import * # Construction of a socket object (TCP) # @return the socket object def createSocket(): return socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to the server si...
""" SC101 Baby Names Project Adapted from <NAME>'s Baby Names assignment by <NAME>. Print the screen of baby-name-search engine. """ import tkinter import babynames import babygraphicsgui as gui FILENAMES = [ 'data/full/baby-1900.txt', 'data/full/baby-1910.txt', 'data/full/baby-1920.txt', 'data/full/baby-193...
import re def name(lines): buscados = [] for i in lines: if re.search('^TITLE', i): buscados.append(i) for i in range(len(buscados)): #elimina la palabra TITLE y tambien los espacios en blanco adicionales a la izquierda y derecha junto con la numeracion de linea ...
import os baseLoc = os.path.dirname(os.path.realpath(__file__)) + '/' from gimpfu import * import sys sys.path.extend([baseLoc + 'gimpenv/lib/python2.7', baseLoc + 'gimpenv/lib/python2.7/site-packages', baseLoc + 'gimpenv/lib/python2.7/site-packages/setuptools', baseLoc + 'EnlightenGAN']) from argp...
""" Settings Encoder/Decoder * Initially, Encode an xml file to dist with apps * On runtime apps, decode settings and useful key """ from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.backends import default_backend import time import binascii import base...
import shutil from unittest.mock import Mock import os from pathlib import Path import pytest import boto3 from conftest import git_init from soopervisor.airflow.export import (AirflowExporter, commons as airflow_commons) from soopervisor.argo.export import (ArgoWorkflowsExport...
import os, sys curr_path = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(curr_path, "../../python")) sys.path.insert(0, os.path.join(curr_path, "../../example/image-classification")) import mxnet as mx import logging import argparse import time import numpy as np logger = logging.getLogger...
import torch from torch.utils.cpp_extension import load from torch.nn import Parameter, init import torch.nn.functional as F spmm = load(name='spmm', sources=['spmm.cpp', 'spmm_kernel.cu'], verbose=True) class SPMMFunction(torch.autograd.Function): @staticmethod def forward(ctx, rowptr, colind, colptr, rowin...
# @author 22PoojaGaur from __future__ import division import sys import copy import extract_frequent_pattern class Node(object): """A node in a tree""" def __init__(self, id, value, children=[], is_dummy=False, depth=0): super(Node, self).__init__() self.id = id self.va...
""" Filename: plot_regression_coefs.py Author: <NAME>, <EMAIL> Description: Plot regression coefficients from drift analysis """ # Import general Python modules import sys import os import re import pdb import argparse import numpy as np import pandas as pd import matplotlib.pyplot as plt import seabor...
from config import database #from Crypto.Cipher import AES from Crypto.Hash import MD5 from config import helpers import time import os def insertUser(req, utype): fname = req.forms.get("fname") lname = req.forms.get("lname") address = req.forms.get("address") phone = req.forms.get("phone") email = req.forms.get...
import ray from ray.tune import run_experiments from ray.tune.registry import register_trainable, register_env from env import MultiAgentParticleEnv import ray.rllib.agents.maddpg.maddpg as maddpg import argparse import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def parse_args(): parser = argparse.ArgumentPars...
import math import keras import numpy as np import tensorflow as tf from keras import backend as K from PIL import Image def letterbox_image(image, size): iw, ih = image.size w, h = size scale = min(w/iw, h/ih) nw = int(iw*scale) nh = int(ih*scale) image = image.resize((nw,nh...
import os import tempfile import unittest import chainer import ignite import torch from ignite.engine import Events import chainer_pytorch_migration.ignite import chainer_pytorch_migration as cpm def test_chainer_extensions(): count = 0 def dummy_extension(trainer): nonlocal count count ...
#!/usr/bin/env python # coding: utf-8 from LV_model import loguniform_prior, simulator, lotka_volterra, newData from bnn_model import LVClassifier, sample_local, sample_local_2D, inBin import numpy as np import pandas as pd import time def run_bnn(max_rounds=10,max_gen=10,Ndata=1000,seed=0, multi_dim=False, num_bi...
import pandas as pd import pytest import woodwork as ww from woodwork import DataColumn, DataTable from woodwork.indexers import _iLocIndexer from woodwork.logical_types import ( Categorical, Datetime, Double, EmailAddress, Integer, PhoneNumber ) from woodwork.tests.testing_utils import to_pand...
# -*- coding: utf-8 -*- import logging import os import re from logging.handlers import RotatingFileHandler import click from flask import Flask, render_template, request, send_from_directory from flask_login import current_user, login_manager from flask_sqlalchemy import get_debug_queries from flask_wtf.csrf import...
import yaml import spacy from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS import string import re from nltk.corpus import stopwords from sklearn.feature_extraction import DictVectorizer from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.feature_extraction.text import TfidfVectorizer i...
''' https://leetcode.com/problems/find-median-from-data-stream/ 295. Find Median from Data Stream The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. - For example, for arr = [...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Title : 测试预测 @File : pred_gen.py @Author : vincent @Time : 2020/5/15 10:41 上午 @Version : 1.0 ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths from model.config import ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= ## @file ostap/parallel/parallel_fill.py # (parallel) Fill of RooDataSet frmo looong TChain/TTree # @author <NAME> <EMAIL> # @date 2014-09-23 # =============================================...
from pynvim import Nvim from pynvim.api.common import NvimError from pynvim.api.window import Window from pynvim.api.buffer import Buffer from pynvim.api.tabpage import Tabpage from enum import Enum from asyncio import Future from os import linesep from typing import ( Any, Awaitable, Callable, TypeVar,...
import pytz import requests import operator from utils import dbManager import streamlit as st from utils import spreadManager from datetime import datetime from annotated_text import annotated_text """ Variables globales: - timezone: Huso horario cuyas horas vamos a usar en nuestra hoja - knowledgeBases: Lista de bas...
# /* # * Copyright 2018 IBM 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 applicab...
import pyopencl as cl import largescale.src.support.cl_support as clspt import numpy as np import os thisdir = os.path.split(os.path.realpath(__file__))[0] program = clspt.compile( os.path.join(thisdir, "program.cl") ) # Calcuate the conductance decaying process # The process can be expressed as ODEs: ...
import os import sys import uuid import json import pydoc import getpass import importlib import configparser import pkg_resources from pathlib import Path from ..util.skel import Skel from ..util.cli.cmd import CMD from ..version import VERSION from ..util.skel import Skel, SkelTemplateConfig from ..util.cli.arg impo...
from types import SimpleNamespace from typing import Tuple import PIL import torch import numpy as np import matplotlib.pyplot as plt from pytorch_transformers import BertTokenizer from script.extract_features import FeatureExtractor as BaseFeatureExtractor from vilbert.vilbert import BertConfig, VILBertForVLTasks ...
# NOTE This model may not be working properly yet. import wandb import tensorflow as tf from tensorflow.keras.layers import Input, Dense, Lambda import gym import argparse import numpy as np from collections import deque import random tf.keras.backend.set_floatx('float64') wandb.init(name='DQN', project="deep-rl-tf2...
""" Interfaces for language learning code. """ from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, Generic, Mapping, Optional, Callable, Any from attr import Factory, attrib, attrs from attr.validators import instance_of from immutablecollections import ( immutabledict, Immuta...
# -*- coding: utf-8 -*- # Copyright <NAME> 2018 # # This file is part of GWOSC. # # GWOSC is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from collections import OrderedDict class InnerNode(): def __init__(self, depth, input_channel, input_height, args): self.args = args self.conv = nn.Sequential(OrderedDict([ ...
import html from emoji import UNICODE_EMOJI from autocorrect import spell import ftfy from unidecode import unidecode from check_tweets import (contains_emoji, contains_hashtag, ends_with_punctuation, is_punctuation, is_website) def process_quote(full_text, autocorrect=False, verbose=Fals...
# -*- coding: utf-8 -*- # # Copyright 2014 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
import numpy as np def extract_patterns(weight): """ return a list of patterns in this weight :param weight: :return: """ patterns = [] kernel_dist = np.zeros((weight.shape[0], weight.shape[1])) for oc in range(weight.shape[0]): for ic in range(weight.shape[1]): kern...
import os import numpy as np from PIL import Image import torch import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt ### torch テンソル(バッチ)を受け取って、args.div_numに応じて、描画する mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) def invnorm(img, N): img = img[N,:,:,:].to('c...
from time import strftime, localtime import json #from datetime import datetime #import logging class tweet: """Define Tweet class """ type = "tweet" def __init__(self): pass def getRawURLS(tw, link, config): player = tw.find_all("div","PlayableMedia-player") gif_url, gif_thumb, vide...
import pytest from lark.exceptions import * from arpoc.ac.parser import * def test_plain(): context = {"subject": {}, "object": {}, "environment": {}} assert check_condition('True', context) assert not check_condition('False', context) def test_object_attr(): context = {"subject": {}, "object": {'t...
from collections import Counter, OrderedDict import postprocessing.db as db def relevancy(assocation, entity): """Applies the proposed relevancy formula and returns a relevancy score.""" def score(q): """Scores user's competence in topic surrounding the association's topic.""" topic = 'polit...
from exceptions import MetricNameNotFound, MetricValueNotFound, VimUuidTypeNotSupported, VimTypeNotFound, \ NsUuidNotFound, NsdUuidNotFound, VnfUuidNotFound, VnfdUuidNotFound, VduUuidNotFound def format_monitoring_metric_per_metric_type(input, proper_timestamp): """Convert the Monitoring metric as provided fr...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2022, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ --- module: zpa_provisioning_key s...
import interaccion_usuario import consultas import salida_resultados NOMBRE_ARCHIVO_REGISTROS = "farmacia.csv" CANT_MAX_RESULTADOS = 10 def obtener_opciones_menu_principal(): ''' Devuelve una lista con todas las opciones que tiene el menú principal del programa, en el orden que se mostrarán en pantalla. ...
import pydoc from collections import OrderedDict import re import os module_header = "# Documentation for {0} ({1}.py)\n" class_header = "## class {}" function_header = "### {}" def maybe_a(a, b, func): """ Compute func(a, b) when a could be None. Args: a (any; maybe None) b (any) ...
import getopt import os import re import sys from datetime import datetime from github import Github, GithubException, UnknownObjectException, InputGitAuthor from lib.bamboo import LinkedRepositoriesList, configure_yaml_loader, parse_yml from lib.config import get_or_create as get_or_create_config from lib.travis imp...
from matplotlib import cm import random import numpy as np import pickle import pycolmap from .utils.viz import ( plot_images, plot_keypoints, plot_matches, cm_RdGn, add_text) from .utils.io import read_image def visualize_sfm_2d(reconstruction, image_dir, color_by='visibility', selected...
from prettytable import PrettyTable from collections import defaultdict import os from HW08_Arun_Nalluri import file_reading_gen class Student: """ Need to know: -CWID -name -major -courses """ def __init__(self, cwid, name, major): self._cwid = cwid ...
from base_component import * import os import argparse from multiprocessing import Pool, cpu_count import tempfile class SoundyAnalysisRunner(Component): """ Component which tries to run Soundy Analysis on all the provided entry points. """ def __init__(self, value_dict): soundy_analysis_...
""" Gooey extensions. These extensions to gooey implement the following functionnality: - Set keyboard accelerators for each of gooey's buttons. - Listen to the target executable's stdout. - Allow the value selected by the user in the UI to be transformed before being passed on to the target executable. The exte...