text
stringlengths
3.07k
12.6k
#!/usr/bin/python3 import sys import numpy as np import scipy.special class BezierSpline: def __init__(self, control_points): self.control_points = control_points self.calculate_coefficients() def calculate_coefficients(self): self.coefficients = np.zeros(self.control_points.shape) ...
# -*- coding: utf-8 -*- # # Copyright (c) 2019, doudoudzj # All rights reserved. # # InPanel is distributed under the terms of the (new) BSD License. # The full license can be found in 'LICENSE'. '''Module for FTP''' import os from ftplib import FTP class FTPClient(): '''FTP Module''' def __init__(self, ho...
# author:Nushrat #given a world meterological union subregion, parse the grdc stations data import os import glob import shutil import numpy as np import pandas as pd from io import BytesIO from zipfile import ZipFile import matplotlib.pyplot as plt from matplotlib import animation from urllib.request i...
#%% # ============================================================================= # Dependencies # ============================================================================= # Get the dependencies from re import I import cdsapi import datetime as dt import os.path import cordex as cx import xarray as xr import nu...
import os import sys import argparse import glob import re from PIL import Image from decimal import Decimal, getcontext, FloatOperation, ROUND_HALF_UP getcontext().traps[FloatOperation] = True def create_parser(): parser = argparse.ArgumentParser() parser.add_argument( "source", type=str, ...
""" Testing routine. Usage: test.py <version> test.py (classification|ner) <version> test.py (-h | --help) test.py --version Options: <version> The version of the dataset to use, the model produced will also be in the same dir. -h --help Show this screen. --version Show version. """ import o...
import kivy from kivy.app import App from kivy.logger import Logger from kivy.uix.image import Image from kivy.uix.button import Button from kivy.clock import Clock from kivy.uix.floatlayout import FloatLayout from kivy.factory import Factory from kivy.uix.popup import Popup from kivy.properties import ObjectProperty,...
import discord, feedparser, ast, datetime from discord.ext import commands, tasks class FeedModule(commands.Cog): def __init__(self, bot): self.bot = bot self.feedPush.start() @tasks.loop(minutes=5) async def feedPush(self): await self.mmfeed() async def mmfeed(self): ...
#The MIT License # #Copyright (c) 2017 DYNI machine learning & bioacoustics team - Univ. Toulon # #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 limitatio...
from django.db import models from django.utils.translation import ugettext_lazy as _ from simple_history.models import HistoricalRecords CURRENT_HOUSING_CHOICES = [ ("Omistusasunto", "Omistusasunto"), ("Vuokra-asunto", "Vuokra-asunto"), ("Asumisoikeusasunto", "Asumisoikeusasunto"), ("Muu", "Muu"), ] H...
# coding: utf-8 """ .. module:: albator_utils.commons Commons functions to help with the Api runtime """ __author__ = "<NAME>" # standard import os import logzero from typing import Dict import json import asyncio import pathlib from pprint import pprint import zipfile # installed import uvloop import aioredis from r...
import re from more_itertools import flatten import pandas as pd import numpy as np def originHandle(): with open("./renmin.txt", "r") as inp, open("./renmin2.txt", "w") as outp: for line in inp.readlines(): line = line.split(" ") i = 1 while i < len(line) - 1: ...
# Copyright 2019 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 to in writing, ...
# # # # # ipfw.py # # University of Illinois/NCSA Open Source License # Copyright (c) 2015 Information Trust Institute # All rights reserved. # # Developed by: # # Information Trust Institute # University of Illinois # http://www.iti.illinois.edu # # Permission is hereby granted, free of charge, to any person obtaining...
def read_lines(): with open('doc.txt', 'r') as f: text = f.read() lines = text.splitlines(keepends=True) # print(lines) return lines def join(strs: list): return ''.join(strs) def new_long_str(s: str): return "\'\'\'{0}\'\'\'".format(s) def new_region(region_name: str, ...
import streamlit as st import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import plotly.graph_objects as go from plotly.subplots import make_subplots def growth_scatter(df): fig=go.Figure() fig.add_trace(go.Scatter(x=df.index, y=df["Confirmed"], ...
import paraview.simple as pvs from paraview import coprocessing as cp # # ParaView Catalyst pipeline for visualising global winds in 3D using # lon lat rad coordinates. Creates a rendered image of the slice, and # stores it as an image file in png format. # # A list of available filters and writers can be foun...
# SPDX-FileCopyrightText: 2022 geisserml <<EMAIL>> # SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause import io import pytest import logging import contextlib import pypdfium2 as pdfium from ..conftest import TestFiles @pytest.fixture def toc_doc(): doc = pdfium.PdfDocument(TestFiles.toc) yield doc do...
from re import finditer, escape, DOTALL from re import sub from mythril.annotary.codeparser import find_matching_closed_bracket, get_newlinetype class Rewriting: def __init__(self, gname, text, pos, line, col): self.text = text self.pos = pos self.line = line self.col = col ...
import os import re def generate_level0_title_segments(input_path, output_path): ''' this file take whole manual labeled resumes from dir path given and convert into segment like basic_info.txt education.txt extra.txt experience.txt skills.txt projects.txt ...
''' Use this file to initialise data used for unittesting different modules. The unittests will be run by doctest ''' # data for curate module def create_seqinfo(): return def create_reproin_test_strings(): strings = [ 'anat-localizer', 'anat-AAHScout', 'anat-Localizer-aligned', 'anat-T1w'...
# Referenced: # https://stackoverflow.com/a/8577226/11039508 # https://stackoverflow.com/a/2257449/11039508 import os import tempfile import subprocess from sandbox import Sandbox import string import random import time import requests # Handles running the code in the specified language # Returns the output from r...
import numpy as np import pandas as pd from pandas import DataFrame, Series import random import time import math import datetime as dt import random import copy from datetime import datetime from time import mktime import os import json from functools import cmp_to_key from itertools import groupby import matplotlib.p...
import sys import torch import torch.nn as nn from torch.autograd import Function class WildcatPool2dFunction(Function): """ Wildcat paper: <NAME>, <NAME>, <NAME>, and <NAME> (2017), “WILDCAT: Weakly Supervised Learning of Deep ConvNets for Image Classification, Pointwise...
import os import pandas as pd import warnings warnings.filterwarnings("ignore") import calmap # for making GitHub-style calendar plots of time-series import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters # Plot using Pandas datatime objects register_matplotlib_converters() rc_fon...
import pytest from geocoding.slf.locparser import * @pytest.mark.parametrize('ngsi_geom_type', [ None, '', 'geo:???', 'geo: ', 'geo: line' # note the space! ]) def test_lookup_parser_return_fail_parser_on_unknown_geom(ngsi_geom_type): parser = lookup_parser(ngsi_geom_type) assert parser is not None ...
import json import os from pathlib import Path from typing import List import matplotlib.pyplot as plt new_json_dir = Path("/home/mark/Data/NFT_Dataset/json") media_dir = Path("/home/mark/Data/NFT_Dataset/media") def cleanup_1(): """ 1. Keep filename only for media file paths. 2. Add id to each file. ...
import util_functions import gsheet_functions def update_target_list(): import pandas as pd from pycoingecko import CoinGeckoAPI # 70 tokens from cryptobanter's youtube video target_tokens_list = ['btc', 'eth', 'sol', 'ada', 'luna', 'dot', 'avax', 'matic', 'algo', 'ftm', 'un...
# -*- coding: utf-8 -*- """ Romanization of Thai words based on machine-learnt engine ("thai2rom") """ import numpy as np from keras.layers import Input from keras.models import Model, load_model from pythainlp.corpus import download, get_file class ThaiTransliterator: def __init__(self): """ Tran...
from http.server import BaseHTTPRequestHandler, HTTPServer from sqlalchemy import create_engine, inspect from sqlalchemy.orm import sessionmaker from database_setup import Restaurant, Base, MenuItem import cgi #HTTPRequestHandler to handle HTTP protocols and requests between the client and the server class CustomHTTPR...
from lib.cog import Cog from lib.command import Command, command from kodipydent import Kodi import json from lib.paste import pastebin my_kodi = Kodi('192.168.1.123') def get_activeplayer(): my_kodi.Player.GetActivePlayers() def get_movies(): my_kodi.VideoLibrary.GetMovies() def ctrl_play_pause(): my_kodi.Player.Play...
import re from django.db.models import Q from Bio.Seq import Seq from goldenbraid.settings import REBASE_FILE, MANDATORY_DOMEST_ENZYMES def filter_feature_by_user_perms(query, user): if user.is_staff: return query if user.is_authenticated(): query = query.filter(Q(featureperm__owner__userna...
""" *k*-mer profile distance library. .. moduleauthor:: Leiden University Medical Center <<EMAIL>> .. moduleauthor:: <NAME> <<EMAIL>> .. moduleauthor:: <NAME> <<EMAIL>> .. Licensed under the MIT license, see the LICENSE file. """ from __future__ import (absolute_import, division, print_function, ...
''' bytestring ========== This module provides integer constants for power-of-two byte size units, and functions for converting between ints and human-readable strings. E.g.: bytestring.bytestring(5000000) -> '4.768 MiB' bytestring.parsebytes('8.5gb') -> 9126805504 Commandline usage: > bytestring number1 [number2 nu...
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.7 # kernelspec: # display_name: Python [conda env:gis_38] # language: python # name: conda-env-gis_38-p...
from omegaconf import DictConfig, OmegaConf from torch.utils.data import Dataset import cv2 from hydra.utils import to_absolute_path import os import albumentations as A import pandas as pd from utils.utils import load_obj import torch import glob from PIL import Image import numpy as np cv2.setNumThreads(0) def get_...
import datetime import logging import os import pickle import random import re from html import escape from typing import Union, List # noinspection PyPackageRequirements from telegram import Message, User, Bot, Chat # noinspection PyPackageRequirements from telegram.error import BadRequest, TelegramError from telegra...
# Copyright 2020 <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...
from typing import Dict, List from google.cloud import aiplatform import numpy as np import pandas as pd from elasticsearch import Elasticsearch from elasticsearch import helpers import json import time from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence impor...
from numpy import mintypecode import utils import torch import train_ as train import pyro import layers import torch.nn.functional as F import numpy as np class GraphEnv: def __init__(self, dataset, k_hops = 1, cuda = True): A, features, labels, _, _, _ = utils.load_data(dataset) saved_model, id...
import os #os.environ['CUDA_VISIBLE_DEVICES'] = "0" import argparse import datasets import experiments from experiments import * parser = argparse.ArgumentParser() parser.add_argument('--experiment_index', type=int, required=True) parser.add_argument('--host_filesystem', type=str, required=True) parser.add_argument(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 28 09:27:06 2020 @author: thotran """ #'LDLR', 'APOB', 'PCSK9' import dash_core_components as dcc import dash_html_components as html DEFAULT_VARIANTS = {'breast cancer': {'chrom': 13, 'mut_type': 'Insertion', 'gene': 'BRCA2', ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import csv import hashlib from typing import ContextManager import srt import pandas import functools from pydub import AudioSegment from datetime import datetime, timedelta from pathlib import Path from praatio import tgio from .clean_transcript import clea...
# -*- coding: utf-8 -*- """ Created on Mon Apr 11 09:11:51 2016 @author: tvzyl """ import numpy as np import pandas as pd from numpy import linalg as la from numpy.linalg import det, inv from scipy.stats import multivariate_normal, norm from math import factorial from numpy import ones, sum, ndarray, array, pi, dot,...
from django.shortcuts import render # Create your views here. from django.contrib.messages.views import SuccessMessageMixin from django.shortcuts import render,redirect from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.forms impor...
"""Isolates rows of the coral reef as video feed goes on This should be one of the drivers of the process Consider running with a lower framerate Hello, currently this script will : -- Isolate and draw Pink Lines -- Identify what kind of lines a pink line is (vertical vs horizontal) -- Define what we want the increment...
#!/usr/bin/env python3 import csv from importlib import import_module import logging import os import requests import shutil from urllib.parse import unquote as unquote from .batch import * from .transform import * from .mapping import * def create_lookup(path): '''Create a lookup table for adding keywords to ...
import requests from bs4 import BeautifulSoup from random import randint import wikipedia def showCmnds(user_name): res = "Hi "+user_name+", I'm mochazbot. 🤖" cmnds = [ "\n\n/start - Start the bot.😜", "\n\n/psc - Shows 20 PSC ques & ans.📖", "\n\n/compile\_lang\_code - Programming lan...
""" Unit tests for the msa_fun module """ import pytest import numpy as np from skbio import TabularMSA, Protein import os import sys # PARENT = [os.path.join('..')] # sys.path.extend(PARENT) import msa_fun from globalvars import AA_TABLE class TestMakeNumMtx(): def test_ok_1(self): aln = TabularMSA([Pr...
# Copyright 2019, The TensorFlow Federated 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 applicable law o...
# KVM-based Discoverable Cloudlet (KD-Cloudlet) # Copyright (c) 2015 Carnegie Mellon University. # All Rights Reserved. # # THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT...
import gevent import logging import random import traceback import ajenti from ajenti.api import * from ajenti.api.sensors import Sensor from ajenti.ui.binder import CollectionAutoBinding from ajenti.ui import on, UIElement, p from ajenti.users import UserManager, PermissionProvider from ajenti.plugins.main.api import...
# 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 # distributed under t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2012 <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 re...
import random import copy from collections import namedtuple, deque import numpy as np import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class OUNoise: """Ornstein-Uhlenbeck process.""" def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2): """Initialize par...
""" Hbond extension Find all hydrogen bonds as determined by the cutoffs specified. Uses PDB2PQR to determine donors and acceptors, and displays all available bonds to file. The original bonding parameters were an angle of 20.0, distance of 3.30, and using the old method for calculating ...
"""내부 코드에서 공용으로 사용되는 기능 클래스 모듈. Classes: CommonSent DataFilter DupItemCheck KoreanSupport """ # 사용 라이브러리 import os import pickle import time # 클래스 목록 class CommonSent: """자주 사용되는 관용구 묶음 클래스. 모든 함수는 staticmethod로, 클래스의 self를 선언하지 않는다. Functions: not_ok() end_comment() n...
import datetime from supra.Utils.Classes import Angle, Position, Trajectory, Supracenter def strToBool(my_str): return (my_str.lower() == 'true') def tryFloat(statement): try: return float(statement) except: return None def tryInt(statement): try: return int(statement) ...
import json import re from collections import namedtuple from functools import partial from itertools import chain from token import COMMENT, NAME, NEWLINE, STRING from wordsegment import WORDS from .websocket import register_handler from .word_completer import is_prefix, wait_until_initialized SpellingError = named...
""" <NAME> 01/2022 Utility Functions: 1. create_dir - create directory at the selected absolute path. 2. save_raster - save a numpy raster in GeoTiff format. 3. load_tiff - read GeoTiff raster ad a numpy array. 4. load_netcdf - read raster saved in NetCDF format. Python Dependencies: numpy: package for scientific ...
from __future__ import print_function import datetime import ftplib import sys import time class GetGBMData(object): def __init__(self, trigger=None, daily=None): self.ftp = ftplib.FTP('legacy.gsfc.nasa.gov', 'anonymous', '<EMAIL>') if trigger is not None: self._type = 'triggered' ...
import os import pathlib from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter import shutil import torch import numpy as np import scipy from scipy.misc import imread from scipy import linalg from torch.autograd import Variable from torch.nn.functional import adaptive_avg_pool2d from inception import Inc...
""" """ import os import tensorflow as tf import vdsr.dataset as dataset import vdsr.model_vdsr as model_vdsr def build_model(): """ """ FLAGS = tf.app.flags.FLAGS # NOTE: placeholder as source sd images sd_images = tf.placeholder( shape=[None, None, None, 3], dtype=tf.float32, ...
from collections import defaultdict from json import JSONEncoder import logging import hashlib class Node(object): APPENDIX = u'appendix' INTERP = u'interp' REGTEXT = u'regtext' SUBPART = u'subpart' EMPTYPART = u'emptypart' INTERP_MARK = 'Interp' def __init__(self, text='', children=[],...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 from airflow import DAG, settings, secrets from airflow.operators.python_operator import PythonOperator, BranchPythonOperator from airflow.operators.dummy_operator import DummyOperator from airflow.contrib.operators.a...
import time import click import numpy as np from yahtzotron.agent import Yahtzotron from yahtzotron.game import Scorecard def play_interactive(model_path): yzt = Yahtzotron(load_path=model_path) def speak(msg, action=None): click.echo("> ", nl=False) time.sleep(0.2) for char in msg...
import numpy as np import cv2 import networkx import CVml # ---------------------------------- Graph cut segmentation ---------------------------------- def build_bayes_graph(img, labels, sigma=10, kappa=2): # build a graph on 4-connection components(pixels). # front and back define on label - 1 - front, -1 -...
import json import random from django.apps import apps from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from django.http import JsonResponse from datetime import datetime, date, timedelta from .serializers import * SERIALIZERS = { 'Turm...
#!/usr/bin/env python # encoding: utf-8 ''' Create shapefile from a CSV file with joining a column to the Landsat WRS png file <NAME>, Feb 5, 2014 ''' import logging import matplotlib matplotlib.use("AGG") def cmap_discretize(cmap, N): if type(cmap) == str: cmap = matplotlib.cm.get_cmap(cmap) import numpy as...
# # Copyright 2020 Two Sigma Open Source, 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 agree...
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
""" Miscellaneous matrix functions """ #***************************************************************************** # Copyright (C) 2008 <NAME> <<EMAIL>> # # Distributed under the terms of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOU...
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.db.models import Sum from django.contrib import messages from django.utils import timezone from .forms import * from django.utils import tran...
# # derived from https://github.com/happyhorseskull/you-can-datamosh-on-linux # MIT License # Do what you will with this # import sys, os, subprocess, random from argparse import ArgumentParser, ArgumentTypeError import tempfile def bail_on_notfile(path): '''Validator for file existence for use in argparsing''' ...
"""Parsers for TARIC envelope entities.""" import logging import os import time import xml.etree.ElementTree as etree from typing import Any from typing import Mapping from typing import Optional from django.conf import settings from django.contrib.auth import get_user_model from django.core.exceptions import Validati...
from django.core.exceptions import ImproperlyConfigured,PermissionDenied from django.urls import reverse_lazy from django.template.context_processors import csrf from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_requir...
""" This module implements omics-based simulation methods. Author: <NAME> """ from __future__ import division from framed.solvers import solver_instance from framed.cobra.simulation import FBA, pFBA from numpy import percentile def gene2rxn(gpr, gene_exp, and_func=min, or_func=sum): def f_and(x): x2...
""" A collection of tools and functions for creating instances from tiddlywebplugins packages providing an initial config and optionally hosting pre-determined tiddlers, bags, and recipes. """ import os import sys from time import time from random import random from pprint import pformat from tiddlyweb.manage import...
# -*- coding: utf-8 -*- """ Author : <NAME> Copyright (c) 2018 <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 to use, copy, mo...
from __future__ import absolute_import from collections import deque, namedtuple import warnings import random from typing import overload import numpy as np # [reference] https://github.com/matthiasplappert/keras-rl/blob/master/rl/memory.py # This is to be understood as a transition: Given `state0`, performing `act...
#%% from style import plot_style, get_markers from fitread import read_data, fit_thresholds, get_fit_func import matplotlib.pyplot as plt from matplotlib.lines import Line2D from collections import defaultdict import numpy as np alpha=1 lw=1 def plot_sequential( file_name, ax0, ax1, latts=[], pro...
# Copyright 2021 cstsunfu. 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 applicable law or agr...
import numpy as np import torch from scipy.special import logsumexp from spn.algorithms import Inference from spn.algorithms.Inference import log_likelihood from spn.algorithms.LearningWrappers import learn_parametric, learn_classifier from spn.algorithms.TransformStructure import Copy from spn.experiments.layers.laye...
import pandas as pd from sklearn.base import TransformerMixin, BaseEstimator from pyadlml.dataset import TIME def _tres_2_pd_res(res): if _is_hour(res) or _is_sec(res): return res if _is_min(res): return res[:-1] + 'min' def _tres_2_discrete(resolution): """ create resolution for one da...
from pygaggle.qa.fid_reader import FidReader from typing import List, Optional from pathlib import Path import logging import json import numpy as np import subprocess from pydantic import BaseModel from .args import ArgumentParserBuilder, opt from pygaggle.qa.base import Reader, Question, Context from pygaggle.qa.dp...
# Copyright 2021 <NAME>. 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 applicable law or ag...
"""Models which relate to the EMPI (JTRACE) database""" from typing import Any, List from sqlalchemy import ( Boolean, Column, Date, DateTime, ForeignKey, Index, Integer, MetaData, String, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Mapped, r...
# -*- coding: utf-8 -*- """Utility functions for supporting time-series based outlier detection. """ import numpy as np from sklearn.utils import check_array # def get_sub_sequences(X, window_size, step=1): # """Chop a univariate time series into sub sequences. # Parameters # ---------- # X : numpy ...
from collections import defaultdict from django.conf import settings from django.contrib.auth.models import User from django.core.paginator import Paginator from django.db.models import Count, Prefetch from django.db.models.query import QuerySet from django.db.models.query_utils import Q from django.http.response impo...
# A Simon game for Circuit Playground Express # Press button A or button B to start. Button B will include number correct # after each round of play. # # A round in the game consists of the device lighting up one or more buttons # in a random order, after which the player must reproduce that order by press...
import sys, ssl, pika, ssl, uuid from netaddr import IPNetwork # <NAME> 29100317 def networkRun(canal, metodo, propiedades, cuerpo): """Function that runs network operations""" cuerpoList = str(cuerpo).split(" ") commandRecived = cuerpoList[0][2:] print (commandRecived) if commandRecived == makeNetC...
from __future__ import division, print_function import os import numpy as np import yaml from visual_dynamics import envs from visual_dynamics import policies from visual_dynamics.utils.config import ConfigObject from visual_dynamics.utils.rl_util import do_rollouts, discount_returns class Algorithm(ConfigObject):...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ A flavor is a string identifier that controls build configurations. Options contained in a flavor can include `build_appliance` as well as...
from itertools import product from random import randint from io import BytesIO import pathlib import ui import numpy as np from PIL import Image as ImageP from cpu import CPU from cartridge import Rom from bus import Bus PATH = '../' ROM = 'snake' NES_PATH = pathlib.Path(PATH + ROM + '.nes') init_img = ImageP.new(...
# Copyright 2020 SmsTid AB. # # 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, s...
import collections import sys def make_clique(graph, nodes): for v1 in nodes: for v2 in nodes: if v1 != v2: graph[v1].add(v2) def count_fillin(graph, nodes): """How many edges would be needed to make v a clique.""" count = 0 for v1 in nodes: for v2 in nodes:...
""" Functions for combining Transformations """ # Lots of relative imports within functions here to avoid circular # imports from collections import defaultdict import copy import numpy as np def get_highest_type(first, second): """ When combining two arbitrary transforms, the output will be of the same ...
"""Utility functions.""" def get_ack_status(code): """Get ack status from code.""" ack_status = {0: "No", 1: "Yes"} if code in ack_status: return ack_status[code] + " (" + str(code) + ")" return "Unknown ({})".format(str(code)) def get_event_status(code): """Get event status from code....
import youtube_dl import os import requests from datetime import datetime, timedelta from pytz import timezone from pytz.reference import Eastern def get_live_url(url=None): if not url: url = os.environ.get('EVENT_URL') else: url = url print(url) # ydl_opts = {} ydl_opts = { ...