text
stringlengths
3.07k
22.1k
# -*- coding: utf-8 -*- #----------Metadata-------------------------------- #This script is responsible for the auto cycle modus. # #----------Imports-------------------------------- import serial import time import Tools import flap_control as flap import threading import temperature_limits as TempLimits import sys,o...
#!/usr/bin/env python import click from click_option_group import optgroup from functools import partial from itertools import chain import json from multiprocessing import Pool from numpy import log10 as log import os import re import shutil import subprocess from tqdm import tqdm # Authorship __author__ = "<NAME>" ...
# Copyright 1999-2017 Alibaba Group Holding 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 a...
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
"""Helpers for indexing functionality.""" from typing import Tuple, Union def format_indexing_element(indexing_element: Union[int, slice]) -> str: """Format an indexing element. This is required mainly for slices. The reason is that string representation of slices are very long and verbose. To give an e...
# coding=utf-8 # Copyleft 2019 project LXRT. import os import collections import torch import torch.nn as nn from torch.utils.data.dataloader import DataLoader from tqdm import tqdm from param import args from pretrain.qa_answer_table import load_lxmert_qa from model import VQAModel import os import psutil process ...
import logging import warnings import click import validators as val from praw.models import Submission from sqlalchemy import sql from tabulate import tabulate from . import extract from . import helper as h from . import paramtypes as types class EBFormatter(logging.Formatter): def format(self, record): ...
# coding=utf-8 from __future__ import print_function import numpy as np import tensorflow as tf from ome import OME import data_process import time import os import pandas as pd import subprocess tf.set_random_seed(22) np.random.seed(22) def numpy_floatX(data): return np.asarray(data, dtype=np.float32) class CSR...
# # Licensed Materials - Property of IBM # 6949-04J # © Copyright IBM Corp. 2020 All Rights Reserved # import glob import json import numpy as np import os import pandas as pd import requests from sqlalchemy import text, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import se...
import argparse from src import dataloader as mydatasets, model as models from src import adni_models import os, sys, time, shutil import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F import torch.optim as optim import datetime as dt from src.average_meter import AverageMeter...
import os import psutil from datetime import timedelta import time import numpy as np import pandas as pd from num2words import num2words def genData(NX=3, num_active_tfs=2, NY=50, AvgNTF=0.5): # Start generating simulated data # The TFs: Number of TF and activation state of each # the target genes: Numb...
import os import time import numpy as np import pandas as pd import torch import torch.nn as nn from algorithms import Models from algorithms.train_LSTNet import train_lstn from algorithms.learning import Learner from algorithms.runHTS import hts_train_and_pred from evaluation.plot import ts_plot, forecast_plot, foreca...
import subprocess from pathlib import Path import datapane as dp import pandas as pd import plotly.express as px from anovos.data_analyzer.association_evaluator import ( correlation_matrix, variable_clustering, IV_calculation, IG_calculation, ) from anovos.data_analyzer.quality_checker import ( du...
import torch import numpy as np torch.manual_seed(0) from torch import nn from torch.autograd import Function from torch.autograd import Variable from torch_nurbs_eval.surf_eval_cpp import pre_compute_basis as cpp_pre_compute_basis, forward as cpp_forward, backward as cpp_backward from torch_nurbs_eval.surf_eval_cuda i...
import gym from gym import spaces from gym.utils import seeding from .rendering import * from .window import Window import numpy as np import pickle # ENCODE_DIM = 6 # TODO create goal object that is agent specific class Actions: available=['still', 'left', 'right', 'forward', 'toggle'] still = 0 lef...
__source__ = 'https://leetcode.com/problems/boundary-of-binary-tree/' # Time: O(N) # Space: O(N) # # Description: Leetcode # 545. Boundary of Binary Tree # # Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. # Boundary includes left boundary, leaves, and right bound...
# -*- coding: utf-8 -*- """Implementation of the ``roh_calling`` step The roh_calling step allows for calling runs of homozygosity from germline VCF files. Currently, it only employs ``bcftools roh`` with simple parameters but in the future more involved approaches could be added. ========== Stability ========== Th...
"""A method to create a segmented version of an RGB dataset.""" import os import glob import shutil import hashlib import numpy as np import pandas as pd from PIL import Image from tqdm import tqdm def _hash(mapping: dict) -> str: """ Return a hash of an entire dictionary. Args: mapping: a dictio...
#! /usr/bin/env python3 """Create random subsampels of input sequences.""" import argparse as ap import glob import gzip from multiprocessing import Pool import os import random import subprocess import numpy as np GENOME_SIZE = None BA_FASTA = None BCG_FASTA = None BA_KMERS = None BCG_KMERS = None def read_coverages...
from __future__ import division import json import numpy as np import os import types from PIL import Image from PIL import ImageDraw import torch import torch.nn as nn import torchvision.transforms from . import model from . import utils def build(config_path: str = '') -> nn.Module: """Builds a pytorch com...
"""Functions for retrieving data from the Census API.""" from asyncio import Future, gather from contextlib import asynccontextmanager from io import BytesIO from json.decoder import JSONDecodeError import logging from logging import Logger import os from pathlib import Path from typing import AsyncGenerator, Dict, It...
from itertools import chain from sys import exc_info, stdout from traceback import print_exception from typing import List, Tuple, Union from libs.config import gget TUPLE_OR_LIST = Union[List, Tuple] def get_min_string(wordlist): return "".join(chain.from_iterable(filter(lambda a: len(a) == 1, [set([chr(y[x]) ...
import sys sys.path.append("/home/zhiyi/pycharm-tmp/basicsr/archs") import cv2 from torch import nn, sqrt import torch #from .arch_util import Upsample from basicsr.archs.arch_util import Upsample from basicsr.utils.registry import ARCH_REGISTRY from .coatnet3d.MBConv3d import MBConvBlock3d from .coatnet3d.SelfAttenti...
from common import get_ssh_client, vsql, get_parser import os CREATE_TABLE_STMTS = [ ('store_sales', ''' create table if not exists store_sales ( ss_sold_date_sk int, ss_sold_time_sk int, ss_item_sk int, ss_customer_sk int, ss_cde...
# !/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Maxwell' import pymysql, datetime, sys import load_config from prettytable import PrettyTable CONFIG_FILE = 'sys.conf' timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] banner = 'Welcome to login the user info table' try_times = 1 ...
from bs4 import BeautifulSoup from selenium.webdriver import Chrome from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By import selenium.webdriver from selenium.webdriver import Chrome import time import datetime i...
""" MIT License Copyright (c) 2021 <NAME>, <NAME> Copyright (c) 2018 Microsoft (<NAME>, <NAME>) """ import sys import json import os import glob import numpy as np OTB2013 = ['carDark', 'car4', 'david', 'david2', 'sylvester', 'trellis', 'fish', 'mhyang', 'soccer', 'matrix', 'ironman', 'dee...
import datetime from django.conf import settings from django.utils import timezone import os from eulfedora.views import datastream_etag from eulfedora.server import Repository from eulfedora.util import RequestFailed from readux.annotations.models import Annotation from readux.books.models import Volume, VolumeV1_0,...
import random # グラフ描写用 import matplotlib.pyplot as plt import japanize_matplotlib # 定数 WEIGHT_LIMIT = 5000 POPULATION = 10 MAX_GENERATION = 100 # グラフ描画用 average_fitness = [] max_fitness = [] generations = [] # 各個体の適応度の計算用 def get_elements_gene_weight_and_value(elements_gene, elements_number, elements_weight, elemen...
#!/usr/bin/python # -*- coding: utf-8 -*- from entities.models import Place, Person, Institution, Event, Work from metainfo.models import Uri, Collection from apis.settings.NER_settings import autocomp_settings as ac_settings from django.conf import settings from .custom_autocompletes import * from dal import autocomp...
#!/usr/bin/env python import csv import logging import os import sys import traceback from typing import Dict, List import requests from mongoengine import connect, NotUniqueError, StringField, Document from pymongo.errors import DuplicateKeyError from selftarget.profile import CrisprLine from scripts.wge_to_ccid.con...
import logging import discord import traceback import asyncio import json import time from datetime import datetime, timedelta from greenbot.models.user import User from greenbot.models.message import Message from greenbot.managers.db import DBManager from greenbot.managers.schedule import ScheduleManager from greenb...
import string from functools import wraps from urllib.parse import urlencode from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.core.pa...
#! /usr/bin/env python3 # Formatted with black (https://github.com/ambv/black). """ Simple file tagging. The tags are stored in file names. Here are the characteristics of this approach: * Cons: * The amount/length of the tags is hard-limited by the given filesystem's max filename length. * Easy to...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # Mon 4 Feb 2019 18:00:00 from __future__ import division import tensorflow as tf FLAGS = tf.app.flags.FLAGS tf.logging.set_verbosity(tf.logging.INFO) def _conv(_input, n_filters, kernel_size, reg_val, na...
import sys import numpy as np import pinocchio from crocoddyl import (ActionModelImpact, ActivationModelWeightedQuad, ActuationModelFreeFloating, CallbackDDPLogger, CallbackDDPVerbose, CallbackSolverDisplay, ContactModel6D, ContactModelMultiple, CostModelCoM, CostModelCont...
#!/usr/bin/python # -*- coding: utf8 -*- import os from datetime import datetime from os.path import isfile, join, exists from datetime import datetime import markdown from flask import Flask, g, request, render_template, abort, make_response, url_for, send_from_directory from flask_babel import Babel app = Flask(__n...
import argparse import glob import os import time import cv2 import numpy as np from utils import prepare_ground_truth as gt_tools from utils import tools from utils import visualisation as v from utils.tf_object_detection import ObjectDetection extensions = ['jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG'] def get_a...
from collections import defaultdict, deque from itertools import cycle import os import re import subprocess import tempfile import threading import time import sublime, sublime_plugin _TEMP_DIR = tempfile.mkdtemp() ERROR = 'RunPMD.error' WARNING = 'RunPMD.warning' SETTINGS = sublime.load_settings("...
import logging import unittest import yaml import datetime from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound from vantage6.server.controller.fixture import load from vantage6.server.model.base import Database from vantage6.server.globals import PACAKAGE_FOLDER, APPNAME from vanta...
''' The MIT License (MIT) Copyright (c) 2016 Nordeus LLC 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, merg...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This module provides C++ language specific implementations of code_node.CodeNode. """ from .code_node import CodeNode from .code_node import CompositeNod...
"""Some basic methods that can be employed for preprocessing of images to PINK. This is not meant to be an exhaustive set. Merely here as a reference. """ import logging from typing import Tuple, List, Dict, Iterator import numpy as np from skimage.morphology import closing, convex_hull_image from skimage.measure im...
#!/usr/local/bin/python # coding: utf-8 __author__ = 'spouk' from .exceptions import SiberiaHTTPRouteErrors, SiberiaPluginInvalidType from .data import ProxyStack from .plugins import SiberiaPlugin from aiohttp import web import aiohttp.web_exceptions as httperrors import inspect import asyncio from mailer import Mes...
""" Fileutils.py: A collection of file utilities for Graphyne """ __author__ = '<NAME>' __copyright__ = 'Copyright 2016, <NAME>' __license__ = 'MIT' __version__ = '1.0.0' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Production' import types import re import sys import os import zipfile impor...
from sklearn.model_selection._search import BaseSearchCV import numpy as np from optimization import grid_to_bounds, grid_types, cast_parameters, zip_one from deap import base, creator, tools import random import warnings from optimization import BaseOptimizer # NSGA-II and NSGA-III algorithm # DEAP genetic algorithms...
""" ================================================= Università degli Studi Di Palermo Corso di Laurea Magistrale in Informatica Anno Accademico 2020/2021 Cloud e High Performance Computing @author <NAME> Serial Concurrent Wave Equation - Python Version ================================================= """ ...
# ====================================================================================================================== # KIV auxiliary functions: based on matlab codes of the authors # https://github.com/r4hu1-5in9h/KIV # ==============================================================================================...
# -*- encoding: UTF-8 -*- import random import datetime import pandas as pd import numpy as np from sklearn import metrics from common import stock_utils from common.config import ConfigUtils from common.stock_utils import get_recently_trade_date from strategy_modules.models.lightgbm import LGB root = ConfigUtils.get...
# -*- coding: utf-8 -*- """ Created on Wed Nov 23 16:45:32 2016 @author: Pedro """ #import sys import tempfile from contextlib import contextmanager import os from collections import namedtuple import logging import itertools import warnings from functools import wraps import numpy as np from enum import Enum from t...
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import gym import scipy.signal import time def discounted_cumulative_sums(x, discount): # Discounted cumulative sums of vectors for computing rewards-to-go and adventage estimates return scipy.signal....
#!/usr/bin/env python # Copyright (c) 2019-2020, Intel Corporation # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of co...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Xiangtai(<EMAIL>) # Pytorch implementation of paper Low-Latency Video Semantic Segmentation (CVPR2018) """ Key idea: low level features matter baseline: resnet-101 (here use the deeplab v3+) training methods: 1, first train on the cityscape use the ...
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
""" Advent of code 2020, day 16 --------------------------- As you're walking to yet another connecting flight, you realize that one of the legs of your re-routed trip coming up is on a high-speed train. However, the train ticket you were given is in a language you don't understand. You should probably figure out what...
import cv2 import numpy as np colors = [[0.76590096, 0.0266074, 0.9806378], [0.54197179, 0.81682527, 0.95081629], [0.0799733, 0.79737015, 0.15173816], [0.93240442, 0.8993321, 0.09901344], [0.73130136, 0.05366301, 0.98405681], [0.01664966, 0.16387004, 0.94158259], ...
#!/bin/env python from argparse import ArgumentParser import socket ## Protocol # Common ACK = b'\xff' DENY = b'\xfe' # Client -> Server JOIN_QUEUE = b'\x01' QUIT_QUEUE = b'\x02' # not implemented RESUME_GAME = b'\x05' ASK_AGAIN = b'\x06' ANSWER_A = b'\x10' ANSWER_B = b'\x11' ANSWER_C = b'\x12' PASS...
# pylint: disable=W0212,W0143,R0201 import logging from collections import Counter from django.db import models, router, transaction from django.db.models.deletion import Collector from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from ..utils import console from .signals impo...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
import string from typing import Any, Dict, List, Optional, Tuple, Mapping, Callable, Union import pandas as pd import numpy as np import pytest def _resolve_random_state(random_state: Union[int, np.random.RandomState]) -> np.random.RandomState: """ Return a RandomState based on Input Integer (as seed) or RandomS...
# custom libraries from lib.extraction.common import PyNexus as PN from lib.extraction.common import Check_dead_pixels import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.colors as colors from PIL import Image import os import sys ...
import os import pickle import webbrowser from utils import * import tkinter as tk from tkinter import * from tkinter import ttk import tkinter.font as font from tkinter import filedialog,Checkbutton,Canvas from tkinter.messagebox import askyesno,askquestion,showinfo,showerror REPOS = 'repos' FONT = ("Courier", 10) if...
# -*- coding: utf-8 -*- """Utility functions .. module:: mgmetis.utils .. moduleauthor:: <NAME>, <<EMAIL>> """ import ctypes as c import numpy as np from .enums import ERROR def get_so(lib): """Get the shared object inside `_cython` Parameters ---------- lib : {"metis", "metis64", "parmetis", "pa...
"""The main entrypoint to vulnture.""" import argparse import configparser import json import logging from pathlib import Path import sys from time import gmtime from project.modules.models import Asset, EmailNotification, VulnerabilitySource from project.plugins.assets import dynamodb from project.plugins.vulnfeeds ...
# -*- coding: utf-8 -*- # @Author : LG import numpy as np from LG_flow import Math_op import copy float32 = np.float32 float64 = np.float64 int16 = np.int16 int32 = np.int64 class Tensor: def __init__(self, data, from_tensors=None, grad_fn=None, grad=None, dtype=float32, requires_grad=False): if not isi...
# Written by <NAME> - <EMAIL> # Project Cloud-Connect from flask import Flask, render_template, redirect, jsonify, session, sessions, request import sqlite3 import controls import time from flask_restful import Api, Resource from flask_cors import CORS import jwt import os import uuid from functools import wraps from ...
from __future__ import print_function import re iToCord3 = {0:(0,-2,2),1:(-1,-1,2),2:(-2,0,2),3:(1,-2,1),4:(0,-1,1),5:(-1,0,1),6:(-2,1,1),7:(2,-2,0),8:(1,-1,0), 9:(0,0,0),10:(-1,1,0),11:(-2,2,0),12:(2,-1,-1),13:(1,0,-1),14:(0,1,-1),15:(-1,2,-1),16:(2,0,-2),17:(1,1,-2), 18:(0,2,-2)} cordToI3 = {y:x for x,y in iToCord3....
# Copyright 2019 D-Wave Systems 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 or...
import pandas as pd import numpy as np from pathlib import Path from datetime import datetime as dt def mergeManagers(managers, gameLogs): #Get visiting managers visitingManagers = gameLogs[['row','Date','Visiting team manager ID']] visitingManagers['yearID'] = pd.DatetimeIndex(pd.to_datetime(v...
import torch import torch.nn as nn import torch.nn.functional as F import json import numpy as np from models.layers import build_cnn from models.layers import GlobalAvgPool from models.bilinear import crop_bbox_batch # from models.initialization import weights_init import torch.backends.cudnn as cudnn cudnn.benchmark ...
#!/usr/bin/env python3 import minimalmodbus import serial import time import datetime import paho.mqtt.client as mqtt import logging from logging.handlers import TimedRotatingFileHandler import gzip import os from configparser import ConfigParser ###################################### # # V 1.0: 03.02.2021: Initai...
import re from JsonResponseResult import JsonResponseResult from Neo4jConnectionPool import ConnectionPool import logging logger = logging.getLogger('django') """ normally, u just initialize a JsonResponseResult obj and dot ok(). and send back to the data you queried Api response will be like this: { "code": 200...
""" Proper scoring rules for probabilistic forecasts. General usage: import comparecast as cc brier = cc.BrierScore() scores = brier([0.7, 0.1, 0.5], [1, 0, 1]) # binary forecasts scores = brier( [[0.2, 0.1, 0.7], [0.9, 0.1, 0.0]], [2, 0], ) # categorical forecasts expecte...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from decimal import Decimal import gestpypay from django.conf import settings from django.conf.urls import url from django.contrib import messages from django.core.exceptions import SuspiciousOperation from django.core.urlresolvers import ...
""" .. versionadded:: 0.24.11-d We use the excellent `Dash`_ app for documentation, but some documentation is nice to have on the local machine. This may even be extended to cover training materials, e-books, etc. .. _Dash: https://kapeli.com/dash """ # Imports from collections import OrderedDict import commands i...
from . import lexer from . import tokens from . import ast class ParserError(Exception): def __init__(self, value): self.value = value def __str__(self): return 'parser error: ' + repr(self.value) class Parser(object): class precedence: LOWEST = 0 INFIF ...
"""Mixin for object detection""" import os import json import pickle import time import torch from torchvision.models.detection import fasterrcnn_resnet50_fpn from ..losses import IoULoss, AVAILABLE_IOU from ..utils import attempt_use_apex USE_APEX, AMP = attempt_use_apex() class ObjectDetectionModelMixin(): """...
import math class ProdEstimator: """ Pure python production version of an XGBoost model that is defined by the JSON model dump. Extracts trees from the model dump, and returns the total leaf value added to the base_score as the prediction for regression problems, and transforms it with the lo...
# -- encoding:utf-8 -- from abaqus import * from abaqusConstants import * from caeModules import * from driverUtils import executeOnCaeStartup from odbAccess import * import mesh import datetime import os from propellent_03_function.propellent_03_function import * userfile_path = os.getcw...
from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session, url_for from flask_session import Session from passlib.apps import custom_app_context as pwd_context from tempfile import mkdtemp import datetime from helpers import * # configure application app = Flask(__name__) # ensu...
""" General OCP object """ import os import logging import time import yaml from ocs_ci.ocs.exceptions import CommandFailed from ocs_ci.utility.utils import TimeoutSampler from ocs_ci.utility.utils import run_cmd from ocs_ci.ocs import defaults log = logging.getLogger(__name__) class OCP(object): """ A basi...
""" Iterative version This version assumes that keys of all nodes in a tree are different, that they don't repeat. Uncomment desired test calls. """ import BST_Iter as BST def printTree(bst, verbose = False): """If boolean verbose is True, it will print(all nodes, in BFS order. """ print() ...
from rxn4chemistry import RXN4ChemistryWrapper from api_info import API_KEY, PROJECT_ID import rdkit.Chem as Chem import time def wait(): if request_count % 5 == 0 and request_count != 0: time.sleep(60) else: time.sleep(2) def collect_reactions(path): """ Input: synthetic path repres...
import logging import os import sys from tqdm import tqdm import random import joblib import h5py import numpy as np import torch from sklearn.cluster import MiniBatchKMeans logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ....
from __future__ import print_function from PyQt5 import QtWidgets from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize from PyQt5.QtGui import QColor, QPalette, QTextCursor, QIcon, QFontDatabase from base64 import b64decode import pty, select, os, struct try: from queue import Queue except ImportError: from...
######################################################################################################################## ### ### ### This script uses a width of max. 120 characters ...
#!/usr/bin/env python """ Synthesize directly connected interfaces """ from ipaddress import IPv4Network from ipaddress import IPv6Network from ipaddress import ip_address from ipaddress import ip_interface from ipaddress import ip_network from tekton.graph import NetworkGraph from tekton.utils import VALUENOTSET fro...
# create predictions from the other stuff """ Go from proposals + scores to relationships. pred-cls: No bbox regression, obj dist is exactly known sg-cls : No bbox regression sg-det : Bbox regression in all cases we'll return: boxes, objs, rels, pred_scores """ import numpy as np import torch from lib.pytorch_misc ...
# -*- coding: utf-8 -*- # Copyright 2014 Google 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...
"""Support for reading data from a serial port.""" # region Imports import codecs import logging from datetime import timedelta from enum import Enum import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.components.binary_sensor import (DEVICE_CLASS_PLUG, ...
import click import os class AbstractParameter(object): """Abstract wrapper for click parameters. Forbids use setting ``required``, because we do that for each command individually. Parameters ---------- args : args to pass to click parameters kwargs : kwargs to pass to c...
#!/usr/bin/env python3 # # Copyright © 2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause # import re import sys import wikitextparser as wtp import xml.etree.ElementTree as ET from enum import IntEnum from peewee import * db = SqliteDatabase(None) class IntEnumField(IntegerField): def __init__(self...
import torch import torch.nn as nn import torch.optim as optim from sklearn.model_selection import train_test_split from sklearn.svm import SVC import numpy as np from collections import defaultdict class EasyDict(dict): __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ ...
import time import timeit import numpy from textblob import TextBlob import re import pandas as pd import datetime as dt from pysentimiento import SentimentAnalyzer from pysentimiento.preprocessing import preprocess_tweet companies = [ "GOOG", "GOOGL", "MSFT", "TSLA"] # companies = ["AAPL", "AMZN"] intervals = ["30m...
import torch from torch import nn import numpy as np from torch.nn import functional as F from coda.modules.utils import AdaptiveSumPool2d from coda.project_utils import to_numpy class CoDAConv2d(nn.Module): def __init__(self, weighting_module): """ Base implementation of a DAU convolution in 2...
#!/usr/bin/python3 """ some code taken from huffman.py """ import sys from functools import reduce from operator import add from math import log, log2 from random import shuffle, choice, randint, seed from bruhat.argv import argv EPSILON = 1e-8 def is_close(a, b): return abs(a-b) < EPSILON class Multiset...
import zmq import json import numpy as np import struct import re import operator from numbers import Number import functools # for "rsetattr" and "rgetattr" tg1 = 0.0 tg2 = 0.0 def rsetattr(obj, attr, val): """ Drop-in replacements for setattr, which can also handle dotted attr strings. from: http://st...
"""Z80 instruction and support classes""" import abc import logging import colecovision.cpu.condition #----------------------------------------------------------------------------- # Module Data #----------------------------------------------------------------------------- # module logger _logger = logging.getLogger...
import argparse import os import shutil import sys import time import numpy as np import torch import torch.nn as nn from sklearn import metrics from torch.autograd import Variable from torch.utils.data import DataLoader from cgcnn.data import CIFData from cgcnn.data import collate_pool from cgcnn.model import Crysta...
from tqdm import tqdm from discordmovies.exceptions import MovieIdentityError from discordmovies.utils import Utils from typing import Union, List, Dict import copy class MovieCategories: """ A class that contains the possible attributes a movie could have. """ def __init__(self, categories: List[str...