text
stringlengths
3.07k
12.6k
#!/usr/bin/env python from flask import Flask, jsonify, render_template, request, send_file, make_response import json from influxdb import InfluxDBClient import numpy as np from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplo...
import os import matplotlib.pyplot as plt import numpy as np from pyplanscoring.core.calculation import DVHCalculation, PyStructure from pyplanscoring.core.dicom_reader import PyDicomParser from pyplanscoring.core.types import Dose3D, DoseUnit def plot_dvh(dvh, title): x_label = 'Dose [Gy]' y_label = 'Volum...
import base64 import hashlib import json import re from django.db import transaction from django.conf import settings from django.contrib.auth.models import User from cities_light.models import Country from mozilla_django_oidc.auth import OIDCAuthenticationBackend from waffle import switch_is_active from mozillians....
# coding: utf-8 # In[2]: # FIXME : 以下の関数は定義されたファイルの形式に依存するので、utilsに記載できない。 def is_env_notebook(): """Determine wheather is the environment Jupyter Notebook""" if 'get_ipython' not in globals(): # Python shell return False env_name = get_ipython().__class__.__name__ if env_name == 'T...
import aiohttp import asyncio import logging from .errors import TwitchException from .extension import Extension from .game import Game, PartialGame from .stream import Stream from .transaction import Transaction from .user import User, PartialUser, BannedPartialUser logger = logging.getLogger(__name__) class HTT...
from collections import deque from math import inf from typing import List, Union, Deque from hwt.code import Concat from hwt.hdl.types.bits import Bits from hwt.hdl.types.bitsVal import BitsVal from hwt.hdl.types.hdlType import HdlType from hwt.hdl.value import HValue from hwt.synthesizer.rtlLevel.constants import NO...
import torch import cv2 import matplotlib.pyplot as plt import collections import numpy as np import os import pprint import sys from PIL import Image import json sys.path.append('../') from utils.util import file_list from torch.utils.data import Dataset cell_cls_dict = { 'HSIL': ['HSIL'], 'AS...
import os from typing import List, Dict import logging import sys class CannotBuildError(Exception): pass class Builder: ALWAYS = 1 """Always run the task's action regardless of requirements and outputs.""" PRESENT = 2 """Targets must be present for the task to be up to date.""" OLDER = 4...
# -*- coding: utf-8 -*- import os import time import logging import numpy as np import jieba from gensim.models import KeyedVectors import sys file_root = os.path.dirname(__file__) sys.path.append(file_root) from get_file import get_file pwd_path = os.path.abspath(os.path.dirname(__file__)) USER_DATA_DIR = pwd_path ...
import spacy nlp = spacy.load("en_core_web_sm") def parse_label_from_text(text, person_dict, loc_dict): """ Parses all the spacy objects in the given text that match one of the labels given in the label_lst Parameter: label_lst: list of label strings text: text to be parsed attempt_count: integer of the curr...
#!/usr/bin/env python3 import json import os import re import time # Relative path from this file to the notebook from which to generate. IPYNB_PATH = os.path.join('..', 'notebooks', 'GANerator.ipynb') # Relative path from this file to the source file to generate. PY_PATH = 'GANerator_generated.py' # For this to ...
""" Copyright 2019 <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 agreed to in writing, software distribut...
import unittest from unittest.mock import patch from tmc import points, reflect from tmc.utils import load, load_module, reload_module, get_stdout, check_source from functools import reduce import os import os.path import textwrap import inspect, re from random import choice, randint, shuffle exercise = 'src.regular_...
# This script is deployed on thomaxxl.pythonanywhere.com # # This is a demo application to demonstrate the functionality of the safrs_rest REST API # # It can be ran standalone like this: # python demo_relationship.py [Listener-IP] # # This will run the example on http://Listener-Ip:5000 # # - A database is cr...
from re import search from json import dump, load from selenium.webdriver import Chrome from colorama import init, Fore, Back, Style from selenium.webdriver.chrome.options import Options def styled(text: str, fore: str = 'white', back: str = 'black', style: str = 'normal') -> None: """ This function returns s...
""" Tic Tac Toe Player Game A game in which two players alternately put Xs and Os in compartments of a figure formed by two vertical lines crossing two horizontal lines and each tries to get a row of three X's or three O's before the opponent does. Implemented using Artificial Intelligence based on Minimax algorithm....
import os import sys import hashlib from urllib.request import urlopen from math import ceil from loguru import logger from tqdm import tqdm from nltk.internals import is_writable path_list = [] _paths_from_env = os.environ.get("TPS_DATA", str("")).split(os.pathsep) path_list += [d for d in _paths_from_env if d] i...
import os import cv2 as cv from time import perf_counter, sleep from windowcapture import WindowCapture from vision import Vision from hsvfilter import HsvFilter from bot import TOMBot from pynput import keyboard import numpy as np import multiprocessing as mp from enum import Enum DEBUG_CLICK_MODE = False class Sta...
from __future__ import print_function import argparse import torch.backends.cudnn as cudnn import torch.nn.functional as F import torch.optim as optim import torch.utils.data.distributed from torchvision import models import timeit import numpy as np import os import byteps.bytescheduler.torch.optimizer as bps """ Th...
import math import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageFilter from skimage import io, measure from scipy.cluster.vq import kmeans # can identify up to 255 objects def mark_objects(image: Image.Image): new_image = image.copy() current = 0 free_labels = [] pixels = ...
## -*- coding: utf-8 -* from __future__ import division import numpy as np from odelab.scheme import Scheme class McLachlan(Scheme): r""" Solver for the Lagrange-d'Alembert (LDA) equations using the algorithm given by equation (4.18) in [MLPe06]_. The scheme will work for any system as long as the necessary meth...
import aiohttp import asyncio import pytest from asynctest import CoroutineMock, patch from kutana import Kutana, Plugin, RequestException, Attachment from kutana.backends import Telegram from test_telegram_data import MESSAGES, UPDATES, ATTACHMENTS def test_no_token(): with pytest.raises(ValueError): Tel...
# coding: utf-8 import dataclasses import typing import serpyco from guilang.description import Description from guilang.description import Part from guilang.description import Type from rolling.action.base import CharacterAction from rolling.action.base import get_character_action_url from rolling.exception import I...
''' Authors: <NAME>. Copyright: Copyright (c) 2018 Microsoft Research 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, mo...
#!/usr/bin/env python # Created by: <NAME> # Description: A module that contains functions for extraction of genbank records. # # Requirements: - This module requires the Biopython module: http://biopython.org/wiki/Download # --------------------------------------------------------------------------------------------...
import os import re import cv2 import json import numpy as np from mayavi import mlab import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import utils as utls def atoi(text): return int(text) if text.isdigit() else text def int_keys(text): return [atoi(c) for c in re.split(r'(\d+)', text...
# show HOI detection from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths from model.config import cfg from model.test import im_detect from model.nms_wrapper import nms from datasets.factory import get_imdb from utils.timer import Timer impo...
""" terminal.py: Responsible for GUI and input handling Contributors: <NAME> """ import os import sys from datetime import datetime import time import random # might remove the D in front of all the names but for now it helps with making it not generic class DTheme(object): def __init__(self, defau...
import gspread_dataframe as gd import gspread import pandas as pd from sqlalchemy import create_engine from oauth2client.service_account import ServiceAccountCredentials import json from pangres import upsert import os import sys from string import punctuation def create_keyfile_dict(): """ Creates a keyfile ...
import numpy as np import matplotlib.pyplot as plt import cv2 import random from skimage import measure import torch from torchvision import utils def make_numpy_grid(tensor_data): # tensor_data: b x c x h x w, [0, 1], tensor tensor_data = tensor_data.detach() vis = utils.make_grid(tensor_...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for # full license information. import gc import inspect import os import weakref import time import logging import importlib logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) ...
from __future__ import annotations from typing import Callable, Optional, Tuple class Spell: def __init__(self) -> None: self.name = "" self.cost: int = 0 self.start: Optional[Callable] = None self.effect: Optional[Callable] = None self.end: Optional[Callable] = None ...
#!/usr/bin/python3 import numpy as np from sklearn.cluster import DBSCAN # from sklearn import metrics import matplotlib.pyplot as plt import logging import propagation import RGreedy import main def DBSCANAlg(X, ClusterParams): db = DBSCAN(eps=ClusterParams.eps, min_samples=ClusterParams.min_samples).fit(X) labe...
import numpy as np import torch from torch.utils.data import DataLoader from torch import nn, optim from torchvision import transforms, datasets from shakeshake import * from collections import OrderedDict import random import importlib dataset_dir = 'd:/dataset/' outdir = '/logs' device = 'cuda:0' EPOCHS = 1800 batc...
from typing import Tuple, Optional import datetime import os from flask import abort, render_template, Flask, redirect, request, jsonify, url_for from werkzeug import Response from flask_jwt_extended import JWTManager, create_access_token, get_jwt_identity, jwt_required, set_access_cookies, unset_jwt_cookies from dote...
""" derivative.py part pymfree/core This module provides classes and helper functions that deal with derivatives. Their functional implementation and properties. """ # Initial imports import numpy as np import torch from pymfree.core.function import DomainFunction from pymfree.util.utils import check_pymfree_type fr...
import logging from typing import List from airflow_monitor.common import capture_monitor_exception from airflow_monitor.common.airflow_data import ( AirflowDagRun, AirflowDagRunsResponse, DagRunsStateData, ) from airflow_monitor.common.base_component import BaseMonitorComponent, start_syncer logger = l...
from click.testing import CliRunner from coreapi import Document, Link from coreapi.transports import HTTPTransport from coreapi_cli import __version__ as version from coreapi_cli.main import client, coerce_key_types import pytest import os import shutil import tempfile mock_response = None def set_response(doc): ...
#!/usr/bin/env python # 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...
import networkx as nx import csv import random import collections import pandas as pd from networkx.readwrite.gml import write_gml from networkx.readwrite.edgelist import write_edgelist from networkx.classes.function import density from graphs import * from datasets.channels_statistics import * from datasets.statistics...
from pygate_grpc.client import PowerGateClient from pygate_grpc.ffs import get_file_bytes, bytes_to_chunks, chunks_to_bytes from google.protobuf.json_format import MessageToDict from pygate_grpc.ffs import bytes_to_chunks import redis import json import time import threading import fast_settings import queue import sql...
# # Author: <NAME> <<EMAIL>> # # Copyright (C) 2017-2018 <NAME> """ Template views system based on Jinja2 """ from six import add_metaclass import sys from os import walk from os.path import join, dirname, abspath from importlib import import_module import yaml import datetime import time from singleton import Single...
#!/usr/bin/env python """ reads: simulating reads Usage: reads [options] <genome_table> <abund_table> <output_dir> reads -h | --help reads --version Options: <genome_table> Taxon genome info. <abund_table> Taxon abundance info. <output_dir> Output directory. --sr-seq-depth=<d> Numb...
""" Model Serializers ----------------- Defines serializers for the various models in the system. """ from marshmallow import Schema, validates_schema, ValidationError from marshmallow.fields import Integer, Boolean, String, Email, Nested, DateTime, Float, Url, List from server.models.bike import CalculatedBikeStatu...
# -*- coding:utf-8 -*- # /usr/bin/env python """ 获取全量历史交易数据 """ import time import json import threading import os import talib as ta import akshare as ak import numpy as np from data_urls import a_detail_url from comm_funcs import requests_get from comm_funcs import except_handle from comm_funcs import find_trade_dat...
""" Match company names on a focal list, to company names (1-to-1 or 1-to-many) on an alter list """ from datetime import datetime from compare import * from support import * from settings import * # MAIN MATCHING FUNCTION ---------------------------------------------------------------------------------...
__all__ = ['Bias2d', 'BlurPool2d', 'Conv2dWs', 'Noise', 'Upscale2d'] import torch import torch.nn.functional as TF from torch import nn from .. import functional as F class Noise(nn.Module): def __init__(self, std: float): super().__init__() self.std = std def forward(self, x: torch.Tensor)...
import os import shutil # from ._version import __version__ from .git import Git import mizuna.utils from .utils.utils import verbose_print, all_of_type import warnings # NOTE: this hook into shutil._samefile will force all files to be considered different, thus overwriting # networked drives considers two files in t...
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F class YOLONetV1(nn.Module): def __init__(self, channel=3, height=448, width=448): super(YOLONetV1, self).__init__() self.conv1 = nn.Conv2d(channel, 64, 7, stride=2, padding=3) self.pool1 = nn.AvgPool2d(2...
""" Copyright 2020 <NAME>, <NAME>, <NAME> - RWTH AACHEN UNIVERSITY Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the fo...
""" SC101 Baby Names Project Adapted from <NAME>'s Baby Names assignment by <NAME>. YOUR DESCRIPTION HERE """ 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-1930.txt', 'data/full/...
# Experiment 11 - Tilemap # # By <NAME> (https://github.com/Taffer) # MIT license, see LICENSE.md for details. import os import pygame import pygame.freetype import sys import time from xml.etree import ElementTree SCREEN_TITLE = 'Experiment 11 - Tilemap' SCREEN_WIDTH = 1280 # 720p screen SCREEN_HEIGHT = 720 BLAC...
# Load the necessary libraries # Set the seed to 123 import pandas as pd import numpy as np # load the dataset into the memory data = pd.read_csv('Logistic_regression.csv') # Pre-processing steps '''You may need to clean the variables, impute the missing values and convert the categorical variables to one-hot encod...
# # handler.py # Lamba functions for scheduling check-ins via the Southwest API # import json import logging import os import sys import uuid import boto3 # Add vendored dependencies to path sys.path.append('./vendor') from lib import swa, email, exceptions # NOQA # Set up logging log = logging.getLogger(__name__...
import json import urllib.parse from typing import Optional, Dict, Any, List import requests_unixsocket from fastapi import FastAPI, File, UploadFile from pydantic import BaseModel app = FastAPI( title='Coding Drills API', description='Docker Engine API にリクエストを投げてコードを実行します。<br>' '各プログラミング言語の D...
#!/usr/bin/env python3 # # main.py # # Command-line utility for interacting with PSU Controller in PDDF mode in SONiC # try: import sys import os import click from tabulate import tabulate from utilities_common.util_base import UtilHelper except ImportError as e: raise ImportError("%s - require...
from dataset_utils import int64_feature, float_feature, bytes_feature import decorations import math import os import xml.etree.ElementTree as ElementTree import shutil import tensorflow as tf tf.app.flags.DEFINE_string( 'path_to_decorations', '/home/paul/Data/decorations', 'path to decorations dataset') tf.app.fl...
from pymongo.write_concern import WriteConcern from pymodm import MongoModel, fields class Accessory(MongoModel): name = fields.CharField(primary_key=True, required=True) description = fields.CharField(required=True) level = fields.IntegerField(required=True) rarity = fields.IntegerField(required=True...
#!/usr/bin/env python3.8 ############################################################################### # Copyright (c) 2019, <NAME>, <NAME> and <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are...
#!/usr/bin/env python3 # vim: set fileencoding=utf-8 # Copyright © 2021 <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 r...
import os import tensorrt as trt import pycuda.driver as cuda import pycuda.autoinit import cv2 import numpy as np import torch from utils.decode import decode from utils.post_process import post_process import time MEAN = np.array([0.485, 0.456, 0.406], np.float32).reshape(1, 1, 3) STD = np.array([0.229, 0.224, 0...
import math import tensorflow as tf import numpy as np import utils def get_distance(point1, point2): x1 = point1[0] x2 = point2[0] y1 = point1[1] y2 = point2[1] dist = math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2)) return dist def get_distance_between_frames(frames, target_labels_all, last_f...
# https://adventofcode.com/2019/day/15 import matplotlib.pyplot as plt import numpy as np def load_file(filename: str) -> list: with open(filename) as f: program = f.readline()[:-1].split(',') program = [int(char) for char in program] return program def get_instructions(code: int) -> list: i...
#-*-coding: utf-8-*- """ Copyright [2018] [Souza Jr, B. G.] 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 agre...
from PIL import Image import numpy as np import os import torch import scipy import scipy.interpolate import cv2 import torchvision.transforms as transforms def resize_img(image_path, w, h, output_path_, output_filename,device): """ Resize image to width x height dimensions and normalize to [0-1] :param i...
import typing from abc import ABC, abstractmethod from dataclasses import dataclass, field from decimal import Decimal from typing import Dict, List, Optional from hummingbot.connector.utils import combine_to_hb_trading_pair, split_hb_trading_pair from hummingbot.core.event.utils import interchangeable if typing.TYPE...
"""Functions to process CMIP6 siconc grids""" import os import glob import datetime as dt import cftime import xarray as xr # TODO: move to constants.py DATA_PATH = "/home/apbarret/Data/CMIP6" SICONC_PATH = os.path.join(DATA_PATH, "siconc", "SImon") AREACELLO_PATH = os.path.join(DATA_PATH, "areacello") MAXTIME = cft...
import json from django.shortcuts import render, reverse, get_object_or_404 from django.http import HttpResponse, JsonResponse, HttpResponseRedirect, Http404 from django.contrib.auth import login, logout from .models import User, Post, Store, Product, Cart, Account, Like from django.contrib.auth.decorators import login...
import pytest import time import random import logging import json import os from filelock import FileLock from tests.integration.canary_test.util import ( setup_canary_cluster, patch_job, dump_job_stats, read_job_spec, RESPOOL_FILE_NAME, MAX_RETRY_ATTEMPTS, ) from tests.integration.common import Integrati...
import argparse import glob import httplib import imp import logging import os import sys import traceback import urlparse from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ForkingMixIn import yaml from . import log from .version import __version__ class ResolvePath(argparse.Acti...
import time import socket import sys import os import pygame import threading from pongClient import Paddle, Ball, WIDTH, HEIGHT, UP, DOWN from constants import LEFT_PADDLE_ID, RIGHT_PADDLE_ID, DEFAULT_PORT, PADDLE_HEIGHT, PADDLE_WIDTH, FPS, SYMMETRIC, ASYMMETRIC , SERVER_NAME import logging from MyCrypt import * loggi...
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
""" Pipeline for tranferring ATSAC videos to the cloud and processing them. """ import argparse import os import subprocess import fsspec import streamz import tornado def check_manifest(of: fsspec.core.OpenFile, manifest: str) -> bool: """ Check to see if a given string exists in a manifest file. Param...
"""Main module.""" __author__ = """<NAME>""" __contact__ = '<EMAIL>' __copyright__ = "Copyright 2020 United Kingdom Research and Innovation" __license__ = "BSD - see LICENSE file in top-level package directory" import argparse import os from glob import glob import yaml from cerberus import Validator class TextCol...
class Node(object): def __init__(self, data, next=None): self.data = data self.next = next def __repr__(self): return str(self.data) class LinkedList(object): def __init__(self): self.head = None self.tail = None def add_in_start(self, value): if self.hea...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015 <NAME> # Serial data to and from Arduino Master import serial import const #import argparse import datetime import MySQLdb as mdb import sys DODEBUG = 1 #parser = argparse.ArgumentParser() #parser.add_argument("serialName", help="The name of the serial port") #ar...
from numpy import inf from numpy import linalg from numpy import sqrt from algos.GLASSO.base import base from utils.common import cp_soft_threshold from utils.GLASSO.glasso import cuda_objective_f_cholesky class cuda_NL_fista(base): def __init__(self, T, N, lam, inner_T, ls_iter, step_lim): super(cuda_NL_...
from keras import backend as K from keras.applications import inception_v3 # You won’t be training the model, so this command # disables all training- specific operations. K.set_learning_phase(0) # Builds the Inception V3 network, without its convolutional base. # The model will be loaded with pretrained ImageNet wei...
from pygame import * from random import randint from time import time as timer win_width = 700 x = 50 score = 0 goal = 20 lost = 0 max_lost = 10 life =3 img_bullet = ("bullet.png") img_bullet1 = ("bullet2.png") img_bullet2 = ("bullet1.png") img_enemy = ("ufo.png") img_ast = "asteroid.png" #a = randint(10,650) #b = ra...
#!/usr/bin/python #Student name: <NAME> #Email: <EMAIL> #Student ID: 20235871 #GitHub: https://github.com/ivabu/ARC/upload/master/src import os, sys import json import numpy as np import re ### YOUR CODE HERE: write at least three functions which solve ### specific tasks by transforming the input x and returning th...
import math import logging from treehopper.api import DeviceCommands from treehopper.api.interfaces import Pwm from treehopper.api.pin import Pin, PinMode from treehopper.utils import utils class HardwarePwm(Pwm): """Hardware PWM module.""" ## \cond PRIVATE def __init__(self, pin: 'Pin'): self._...
import pygame from enum import Enum from framework.AssetsManager import AssetsManager from game.tools import Direction class GhostType(Enum): BLINKY = 1 PINKY = 2 INKY = 3 CLYDE = 4 BLUE = 5 WHITE = 6 class Ghost(pygame.sprite.Sprite): # Public def __init__(self, ghost_type, block...
from copy import deepcopy import pytest import torch.nn.functional as F from typing import Tuple, List, Dict, Any import torch from collections import namedtuple import os from dizoo.classic_control.cartpole.config import cartpole_ppo_config, cartpole_ppo_create_config, \ cartpole_dqn_config, cartpole_dqn_create_c...
from django.http import HttpResponse, HttpResponseRedirect, get_host from django.shortcuts import render_to_response as render from django.template import RequestContext from django.conf import settings from django.utils.http import urlquote_plus, urlquote import md5, re, time, urllib from openid.consumer.consumer imp...
import torch import torch.nn as nn class InceptionV1Reimpl(nn.Module): ''' Reimplementation of inception module with dimension reductions https://arxiv.org/pdf/1409.4842.pdf ''' def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes ): super(InceptionV1Reimpl, self)._...
import csv import itertools from collections import namedtuple from django.core.management import BaseCommand, CommandError from corehq.apps.change_feed import data_sources, topics from corehq.apps.change_feed.producer import producer from corehq.apps.hqadmin.management.commands.stale_data_in_es import DataRow, HEADE...
import unittest from medcat.cat import CAT from medcat.config import Config from medcat.utils.model_creator import create_models from pathlib import Path class EntityLinkingTest(unittest.TestCase): """Test entity linking after creating MedCAT CDB and Vocab models. During class setup, MedCAT CDB and Vocabular...
# SPDX-FileCopyrightText: 2021 jedgarpark for Adafruit Industries # SPDX-License-Identifier: MIT # Pico motor party demo board # Hardware setup: # Servo on GP0 # DC motor via L9110 H-bridge driver on GP28, GP27 (they're on different PWM channels) # Stepper motor via DRV8833 driver breakout on GP21, GP20, GP19, G...
from __future__ import print_function import argparse import os import numpy as np import pandas as pd def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--input_dir', '-i', type=str, required=True, help='directory with generated utterances') parser.add...
__author__ = 'sulantha' import glob, subprocess, re from Utils.DbUtils import DbUtils import os from distutils import file_util, dir_util import shutil DBClient = DbUtils() def recurseBeastFolder(): fileList = [] for name in glob.glob('/data/data03/ADNI/BEAST/adni_*/t1/beast/*'): mainFolder = name ...
#!/usr/bin/python2 from __future__ import print_function import re import sys import os import os.path import mutagen.id3 from mutagen.id3 import ID3,ID3NoHeaderError,Frames from mutagen.flac import FLAC,FLACNoHeaderError from mutagen.oggvorbis import OggVorbis,OggVorbisHeaderError from mutagen.oggopus import OggOpu...
from __future__ import print_function import inspect import pkgutil import six from rdopkg import exception from rdopkg.utils import log if six.PY2: inspect_getargspec = inspect.getargspec else: inspect_getargspec = inspect.getfullargspec class Arg(object): def __init__(self, name, **kwargs): se...
import requests, html, json from bs4 import BeautifulSoup s = requests.Session() root_url = None previous_url = None def login(root, sid, pin, security_answer): global root_url root_url = root url = root_url + "/PRODCartridge/twbkwbis.P_GenMenu?name=bmenu.P_RegMnu" r = s.get(url) cookies = dict(r....
from __future__ import absolute_import from __future__ import division from __future__ import print_function import networkx as nx import numpy as np from scipy.spatial import cKDTree import util class GraphMap(object): def __init__(self, size, top_k=3, largest_correlation=.9, closest_k=0): # Create a simple...
import json import logging from datetime import datetime, timedelta from hashlib import sha256 from billiard import Pipe, Process from celery import shared_task, chord from celery.result import AsyncResult from celery.states import READY_STATES, PENDING #from celery_haystack.tasks import CeleryHaystackSignalHandler, C...
############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
import torch import torch.nn as nn class LinMod(nn.Linear): '''Linear modules with or without batchnorm, all in one module ''' def __init__(self, n_inputs, n_outputs, bias=False, batchnorm=False): super(LinMod, self).__init__(n_inputs, n_outputs, bias=bias) if batchnorm: self.b...
""" Copyright start Copyright (C) 2008 - 2021 Fortinet Inc. All rights reserved. FORTINET CONFIDENTIAL & FORTINET PROPRIETARY SOURCE CODE Copyright end """ import base64 import requests from connectors.core.connector import ConnectorError, get_logger from .constants import * logger = get_logger('riskiq-digi...
import logging from flask import request from flask import Flask, render_template from flask_restful import Api, Resource, reqparse import requests from random import choice #импортируем необходимые библиотеки app = Flask(__name__) api = Api(app) logging.basicConfig( filename='map.log', format...
from __future__ import absolute_import import os import cv2 import random import mxnet as mx import numpy as np import mxnet.ndarray as nd def mx_create_data_iterator(batch_size, train_set_file=None, val_set_file=None, shape=None, dtype=np.float32, data_aug=False): train_iter = N...