text
stringlengths
3.07k
12.6k
import argparse import json import socketserver import ssl import time import traceback import webbrowser import os from functools import wraps from http import HTTPStatus, server from http.server import HTTPServer from urllib.error import URLError from urllib.parse import unquote, urlparse, parse_qs from urllib.reques...
from contextlib import contextmanager import logging import os from os.path import join, abspath, dirname import simplejson import tempfile from stolos.initializer import initialize as _initialize from stolos import util from stolos import queue_backend as qb from stolos import dag_tools as dt from stolos import conf...
import unittest import random from pyduino import Arduino class Arduino_Mock(Arduino): """ Mocks the Arduino object Proxies the write() and readline() calls to an Arduino_Connection_Mock """ def __init__(self): self.conn = Arduino_Connection_Mock() class Arduino_Connection_Mock(): """...
import datetime import os import re from contextlib import closing from etl import base from utils.format_helper import ( derived_submitter_id, format_submitter_id, remove_time_from_date_time, idph_last_reported_date, get_date_from_str, ) from utils.metadata_helper import MetadataHelper CURRENT_DI...
import torch.nn as nn import torch from torch.autograd import Variable # Define a resnet block class ResnetBlock(nn.Module): def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False): super(ResnetBlock, self).__init__() self.conv_block = self.build_conv_block(di...
#!/usr/bin/env python # noinspection PyUnresolvedReferences import vtkmodules.vtkInteractionStyle # noinspection PyUnresolvedReferences import vtkmodules.vtkRenderingOpenGL2 from vtkmodules.vtkCommonColor import vtkNamedColors from vtkmodules.vtkFiltersSources import vtkSphereSource from vtkmodules.vtkIOImage import (...
# EXCEL TO SHARED PARAMETER FILE import sys print(sys.version) print(sys.path) import clr import System from System.Collections.Generic import * clr.AddReference("RevitAPI") from Autodesk.Revit.DB import * clr.AddReference("RevitAPIUI") from Autodesk.Revit.UI import * from Autodesk.Revit import Creation clr.AddRefe...
import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras.models import Model from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Activation from tensorflow.keras.layers import Dropout from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Input...
# -*- coding: UTF-8 -*- import numpy as np from pypcd import pypcd from .geometry import * import random import numba import json from math import * from scipy.spatial.transform import Rotation as R def get_objects_from_label(label_file): values = json.load(open(label_file, 'r')) objects = [Object3d(value) f...
import numpy as np from tensorflow.keras.models import Sequential, load_model from tensorflow.keras.layers import Input, Dense, Embedding, LSTM, Concatenate, Reshape, GRU, Bidirectional, Dropout from tensorflow.keras.layers import Conv1D, Flatten, TimeDistributed from tensorflow.keras.layers import BatchNormalization,...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Provide a test() function that can be called from package __init__. """ import os # Pytest args for main() to ignore several warnings that show up regularly in # testing but can be ignored. PYTEST_IGNORE_WARNINGS = ( # See https://github.com/nu...
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse, logging import numpy as np import struc2vec from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence from time import time from log import set_up_log from data import * from train import * from model import * import graph import random...
from astropy.io import fits import numpy as np import matplotlib.pyplot as plt import os def loadSpc(fileName): hdu = fits.open(fileName) header=hdu[0].header if False: # print(f"header= {header}") for k in header: print(f"{k} = {header[k]} \t\t\t '{header.comments[k]}''") ...
#!/usr/bin/python # Copyright 2021 Expedient # # 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...
# -*- coding: utf-8 -*- """ Tyre Pressure tracker sending data over MQTT. Target homeassistant MQTT integration. """ import asyncio import datetime import json import logging import time import paho.mqtt.client as mqtt from bleak import BleakScanner discoveryPayload = { "name": "Pressure Sensor", "stat_...
import hmac import json import urllib.parse import requests.auth from requests import PreparedRequest as P from requests import Response as R from . import base class AuthBase(requests.auth.AuthBase): def __call__(self, r: P): raise NotImplementedError('Auth hooks must be callable.') @staticmethod...
from chatterbot.trainers import ListTrainer from chatterbot import ChatBot from random import choice import random from time import sleep import os import sys import asyncio import time bot=ChatBot('Test') random_bye=["You are a good, person, bye!","Really man, i want to talk with you","If you say it, i have ...
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
"""This file holds the classes necessary to provide the "algebraic intermediate representation" (AIR) of the computation. Informally, the key step needed here is the "arithmetization" of the computation. That is, the computation must be configured to work within a given finite field. That is, the states of the computat...
from keras.models import Model from keras.layers import Input, Dense, Flatten, Dropout, Activation, Conv1D, MaxPooling1D, AveragePooling1D from keras.optimizers import Adam import keras.models from .spectral_layers import MultiGraphCNN from .utils import * from collections import defaultdict import matplotlib.pyplot as...
''' Created on 21.02.2022 @author: michael ''' from pathlib import Path import os from xml.dom.minidom import parse from injector import singleton, inject from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import A4 from reportlab.platypus.doctemplate import SimpleDocTemplate from report...
import sqlite3 as lite from pandas.io import sql from datetime import date import pandas as pd import six import tushare as ts from datetime import date from dateutil.relativedelta import relativedelta from rqalpha.data.base_data_source import BaseDataSource cnx = None cnxname=None #def save_data(df,code=None, ...
#!/usr/bin/env python # coding: utf-8 # In[1]: import pickle import random import re import matplotlib.pyplot as plt import numpy as np import seaborn as sns import sklearn.datasets import tensorflow as tf from sklearn import metrics from sklearn.cross_validation import train_test_split from sklearn.feature_extract...
""" pages API endpoint """ from django.http import JsonResponse, Http404 from django.shortcuts import get_object_or_404 from backend.settings import BASE_URL from cms.models import Region, Page from ..decorators import json_response def transform_page(page_translation): """ Function to create a dict from a ...
import os import numpy as np from scipy import special from scipy.special import sph_harm from scipy.special import genlaguerre from scipy.special import factorial as fact from .hwf import real_wf_nlm_xyz, psi_xyz, radial_wf, bohr_rad_A, elec_mass_amu def real_wf_cartesian_density(n,l,absm,plusminus,nx,ny,nz,dx,dy...
import discord import os import json import random as rand from discord.ext import commands client = commands.Bot(command_prefix = '.') token = '******.*************.****************************' os.chdir('C:\Storage A\BOT') #-------------------------- LEVEL -------------------------------------- lv1 = 100...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Module that hold the information about the Game class.""" from random import randint from exceptions import TooManyPlayersError from player import BotPlayer, HumanPlayer class Game: """Class representing the game. Holds the information about the players, t...
import sys import scipy.sparse as sparse import scipy.stats import scipy.sparse.linalg as slinalg import numpy as np import numpy.linalg as linalg import scipy.io as sio import matplotlib.pyplot as plt from scipy.ndimage.filters import median_filter from CSMSSMTools import * def getLaplacianEigs(A, NEigs): DEG = s...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
# -*- coding: utf-8 -*- from keras.applications.inception_resnet_v2 import InceptionResNetV2 from keras.applications.inception_v3 import InceptionV3 from keras.applications.resnet50 import ResNet50 import os import sys from LossHistory import LossHistory from DataGenerator import DataGenerator from datetime import dat...
from common import * # NOQA import pytest CLUSTER_NAME = os.environ.get("CLUSTER_NAME", "") RANCHER_CLEANUP_PROJECT = os.environ.get("RANCHER_CLEANUP_PROJECT", "True") namespace = {"p_client": None, "ns": None, "cluster": None, "project": None, "testclient_pods": [], "workload": None} def test_dns_reco...
# -*- coding: utf-8 -*- """ Created on Fri Apr 26 06:33:58 2019 @author: sindu """ import sys import numpy as np import time filename = "Weather_1000"#"Light_100"#"Graph_Sample9.txt" #"Light_100" SEP = "," #easy to change separator start_time = time.time() def mapper1_emit_uv(file_name): graph_f...
# https://leetcode.com/problems/construct-binary-tree-from-string/discuss/100422/ # We perform a recursive solution. There are four cases for what the string might look like: # empty # [integer] # [integer] ( [tree] ) # [integer] ( [tree] ) ( [tree] ) # When there is no '(', we are in one of the first two cases and p...
import logging from BaseImage import printMaskHelper from skimage import io, img_as_ubyte from skimage.draw import polygon import os from pathlib import PurePosixPath, Path import json import xml.etree.ElementTree as ET import numpy as np def get_points_from_xml(xml_fname): """ Parses the xml file ...
# # Copyright 2018 IBM Corp. 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 a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # data source management import json import logging import os import time import warnings import geopandas as gp # type: ignore import requests from shapely.geometry import box, LineString, Point # type: ignore from typing import List SCREEN_PRECISION: int = 2 # ro...
import pandas as pd import argparse import re import numpy as np import sys def fixheadernumbering(header,padding=4): header_template = "%%s_%%0%sdins%%0%sd"%(padding,padding) if "ins" in header: gene, position = header.split("_") ins_index = position.index("ins") pos = int(posi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ FRET-IBRA is used to create fully processed ratiometric images from input donor and acceptor intensity TIFF images """ import os, sys, getopt import configparser from functions import logit import background_subtraction as bs import ratiometric_processing as rp impor...
## Function required in the main program import numpy as np import xarray as xr import netCDF4 import pandas as pd # function to make preciptation rate to preciptation def convert_to_precipitaion(ds): temp = ds * 24 # temp = temp.to_dataset() return temp # Function to obtain seasonal mean def season_mean...
import os import gym from gym import wrappers import random import torch.optim as optim from dqn_model import DQN, Dueling_DQN from dqn_learn import OptimizerSpec, dqn_learning from utils.schedule import LinearSchedule from utils.gym_utils import get_env, get_wrapper_by_name import logz REPLAY_BUFFER_SIZE = 100000 L...
""" A key-value store implementation based on sqlite3. """ from __future__ import annotations import contextlib import math import sqlite3 import string import threading import time import typing as t from ._api import KeyValueStore def _fetch_all(cursor: sqlite3.Cursor) -> t.Iterable[tuple]: while True: ro...
# -*- coding: utf-8 -*- """ Created on Fri Aug 7 16:47:38 2020 @author: eilxaix """ import nltk import re from tqdm import tqdm # ============================================================================= # from nltk.corpus import stopwords # stop_words = set(stopwords.words("english")) # ========================...
import re import json from pathlib import Path from configparser import ConfigParser from typing import Dict, Any, List, Union from schema_entry import EntryPoint from pmfp.const import PMFP_CONFIG_HOME, PMFP_CONFIG_DEFAULT_NAME def setup_cfg_handdler(p: Path) -> Dict[str, Any]: config = ConfigParser() result...
import numpy as np from PIL import Image import matplotlib.pyplot as plt palette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153, 153, 153, 153, 250, 170, 30, 220, 220, 0, 107, 142, 35, 152, 251, 152, 70, 130, 180, 220, 20, 60, 255, 0, 0, 0, 0, 142, 0, 0, 70, 0, 60, 100, 0...
import retro import os import tensorflow as tf import numpy as np import time import matplotlib import matplotlib.pyplot as plt from tf_agents.specs import array_spec from tf_agents.specs import tensor_spec from tf_agents.networks import network from tf_agents import specs from tf_agents.agents.dqn import dqn_agent f...
import sys import os from random import randint from math import sin from tkinter import Tk, Canvas, LabelFrame, Button, FLAT, GROOVE, \ RAISED, SUNKEN, CENTER, W, E, N, messagebox, ttk import serial import serial.tools.list_ports serial_run = False for port in list(serial.tools.list_ports.comports()...
# Apache License # Version 2.0, January 2004 # http://www.apache.org/licenses/ # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache Li...
# # NAME # problem_set2_solutions.py # # DESCRIPTION # Open, view, and analyze action potentials recorded during a behavioral # task. In Problem Set 2, you will write create and test your own code to # create tuning curves. # #Helper code to import some functions we will use import numpy as n...
from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView from django.views.generic import UpdateView from django.views.generic.dates import MonthArchiveView from django.contrib.auth.mixins import LoginRequiredMixin from django.utils import timezone from django.urls import reve...
""" Lunch Money - Budgets https://lunchmoney.dev/#budget """ import datetime import logging from typing import Any, Dict, List, Optional from pydantic import Field from lunchable._config import APIConfig from lunchable.models._base import LunchableModel from lunchable.models._core import LunchMoneyAPIClient logger...
import numpy as np from pyfpgrowth import find_frequent_patterns class FeatureDiscretizer(): def __init__(self, bins=5, onehot=True): self.bins = bins self.onehot = onehot def fit(self, X, feature_names=[], feature_types=[]): self.X_ = X origin_feature_names = feature_names if...
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import pandas as pd pd.set_option('max_rows',20) import plotly.express as px import plotly.io as pio pio.renderers.default = "browser" df = pd.read_csv("data.csv") def fig_world_trend...
#!/usr/bin/env python3 # coding: utf-8 import sys import ui SYMBOL_BACKSPACE = '<' SYMBOL_ENTER = '>' SYMBOL_SPACE = ' ' class CinFile: def __init__(self, cin_file_name): self.cname = None self.__key2char = dict() self.__char2key = dict() self.__key2symbol = dict() self.__...
#!/usr/bin/env python import json import matplotlib import numpy as np import click from collections import namedtuple Calc = namedtuple( "Calc", [ "wins", "losses", "saves", "goals", "assists", "shots", "lose_score", "win_score", "goal_d...
# coding=utf-8 """ Preprocess data sets by computing BallTree range index and kNN graph, and also fit MRkNNCoP tree. """ import argparse import logging import os import pickle from os import path import h5py import numpy import pandas from sklearn.datasets import make_blobs from sklearn.neighbors import BallTree, knei...
"""Parse genome assemblies from NCBI by their level of completion. This script fetches current and historical Assembly Reports from NCBI, and extracts metadata on assemblies that are relevant for Single Cell Portal. See get_assembly_report docstring for more detail on historical Assembly Reports. Only assemblies that...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # filtered-js-gatherer - Scripts for MWSCup 2017 # https://github.com/h-uekawa/filtered-js-gatherer # # Copyright (c) 2017 Team Security Anthem (Okayama Univ.) # Released under the MIT License, see LICENSE.txt # ## import sys from tweepy.streaming import StreamListe...
import sys import re import itertools from contextlib import contextmanager import io import ctypes from ctypes import windll import textwrap import collections from jaraco.windows.api import clipboard, memory from jaraco.windows.error import handle_nonzero_success, WindowsError from jaraco.windows.memory import Locke...
import asyncio import ipaddress import pickle import secrets from pathlib import Path from typing import AsyncGenerator from typing import Optional from typing import TypedDict from typing import Union import aiohttp import aioredis import cmyui import databases import datadog.threadstats.base as datadog_client import...
import logging from django.contrib.sites.models import Site from rdmo.conditions.models import Condition from rdmo.core.imports import (fetch_parents, get_foreign_field, get_m2m_instances, set_common_fields, set_lang_field, validate_instance) from rdmo.dom...
import numpy as np import pytest from fdm import forward_fdm, backward_fdm, central_fdm, FDM from .util import approx def test_construction(): with pytest.raises(ValueError): FDM([-1, 0, 1], 3) @pytest.mark.parametrize("f", [forward_fdm, backward_fdm, central_fdm]) def test_correctness(f): approx(f...
# -*- coding: utf-8; -*- """Utilities for splicing the actual code into a code template.""" __all__ = ["splice_statements", "splice_dialect"] import ast from copy import deepcopy from .astfixers import fix_missing_locations from .coreutils import ismacroimport from .walker import Walker def splice_statements(body,...
from rest_framework.viewsets import ModelViewSet from django_filters.rest_framework import DjangoFilterBackend from .models import PrintingHouse, PostOffice, Newspaper, Order, PrintRun from .filters import PrintRunFilter, PrintRunFunc3Filter, PrintRunFunc4Filter from mainapp.serializers import ( PostOfficeSerializer,...
#!/usr/bin/env python3 import io import os import sys import time import bottle from os import path from glob import glob from optparse import OptionParser from markdown import markdownFromFile import mdx import utils # bottle templates dir bottle.TEMPLATE_PATH.insert(0, path.join(path.dirname(__file__), 'template...
import yaml import os import packtivity.logutils as logutils from . import datamodel as _datamodel class packconfig(object): def __init__(self, **kwargs): self.handler_selection = kwargs fromenv = os.environ.get("PACKTIVITY_SYNCCONFIGFILE", None) if fromenv: override = yaml.sa...
"""Doodba child project tasks. This file is to be executed with https://www.pyinvoke.org/ in Python 3.6+. Contains common helpers to develop using this child project. """ import json import os from glob import glob, iglob from pathlib import Path from invoke import task PROJECT_ROOT = Path(__file__).parent.absolute...
from pytube import YouTube, Playlist import re import sys class bgcolors: OKGREEN = '\033[92m' #GREEN OKBLUE = '\033[94m' #BLUE OKCYAN = '\033[96m' #CYAN WARNING = '\033[93m' #YELLOW FAIL = '\033[91m' #RED RESET = '\033[0m' #RESET COLOR BOLD = '\033[1m' #BOLD UNDERLINE = '\033[4m' #UNDE...
import json import logging import sys from argparse import ArgumentParser from typing import List, NamedTuple, Dict, Optional import docker from thriftybuilder._logging import create_logger from thriftybuilder.builders import DockerBuilder from thriftybuilder.common import ThriftyBuilderBaseError from thriftybuilder.c...
# Copyright 2015 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. import unittest from telemetry.core import util from telemetry.timeline import memory_dump_event util.AddDirToPythonPath(util.GetTelemetryDir(), 'third_par...
# ------------------------------------------------------------------------- # Copyright (c) PTC Inc. and/or all its affiliates. All rights reserved. # See License.txt in the project root for # license information. # -------------------------------------------------------------------------- r"""`channel` exposes an AP...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # fxp2ardour.py # """Convert one or more VST2 FXP preset files to Ardour VST presets XML files. """ import argparse import hashlib import os import sys from base64 import b64encode from collections import namedtuple from os.path import exists, isdir, join from struct im...
# Copyright (c) 2019, <NAME> # Licensed under the BSD 3-clause license (see LICENSE.txt) from __future__ import absolute_import, division, print_function import io import json import os import sys import pandas as pd import numpy as np import scipy from sklearn import preprocessing, random_projection from sklearn....
""" ulsys stochastic L-System module. License follows ------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "...
from __future__ import print_function import os import argparse import torch import torch.backends.cudnn as cudnn import numpy as np import time from models.img_registration_model import TwowayResNet,ResBlock import cv2 import torchvision.models as models import numpy as np from scipy.optimize import leastsq import ran...
import unittest from ember import * import cantera as ct from cantera.test.utilities import CanteraTest class TestPremixedStrained(CanteraTest): def setUp(self): self.conf = Config( Paths(outputDir='build/test/work/premixedStrained', logFile='build/test/work/premixedStrained....
# YOLOv3 common modules """ Directly Imported from yolov3 - needed for the yolo.py script""" import math import torch import torch.nn as nn from detectron2.layers import CNNBlockBase, Conv2d, get_norm def autopad(k, p=None): # kernel, padding # Pad to 'same' if p is None: p = k // 2 if isinstance(k...
''' The following script does the following: - checks for cloned Panacea Lab Twitter repo; if not present in current directory, clones the Repo - pulls most recent data from Panacea repo, to ensure contents are up-to-date - creates list of daily folders located in Panacea repo - creates raw_dailies folder within my cov...
# Copyright 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://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying...
"""Geometry routines for working Geogrid""" import logging import os from typing import Tuple import isce # noqa: F401 import isceobj import numpy as np from contrib.demUtils import createDemStitcher from contrib.geo_autoRIFT.geogrid import Geogrid from isceobj.Orbit.Orbit import Orbit from isceobj.Sensor.TOPS.Senti...
"""Merge People together!""" from pprint import pformat import json from tqdm import tqdm from django.db import transaction from django_import_data import BaseImportCommand from cases.models import Person from utils.merge_people import find_similar_people, merge_people THRESHOLD_DEFAULT = 0.9 def proportion(val...
import pytest from delphin.lnk import Lnk from delphin.mrs import ( MRS, EP, HCons) from delphin.codecs import indexedmrs from delphin import semi @pytest.fixture def simple_semi(): return semi.SemI.from_dict({ 'variables': { 'u': {'parents': []}, 'p': {'parents': ['u...
from argparse import ArgumentParser from pathlib import Path import time import os import gin import numpy as np import torch import torch.nn as nn import torch.optim.lr_scheduler as lr_scheduler from torch.nn import CrossEntropyLoss from datasets import get_dataset from models.gan import get_architecture from torch....
# ___ _ _ ___ __ __ _____ __ # / __| || |_ _| \/ | _ \ \ / / # | (__| __ || || |\/| | _/\ V / # \___|_||_|___|_| |_|_| |_| # # Copyright (c) 2020 <NAME>. All rights reserved. # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>....
import argparse import json import asyncio import websockets import re import requests from pathlib import Path WORK_DIR = Path(__file__).parent WORDSET_FILE = WORK_DIR / 'words.json' assert WORDSET_FILE.exists() def read_config(): try: with open(WORK_DIR / 'config.json') as f: return json.lo...
import numpy as np import matplotlib matplotlib.use('Agg') import os import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader class EBMAligner: """Manages the lifecycle of the proposed Energy Based Latent Alignment. """ def __init__(self, ebm_latent_dim=2048, ...
#library imports import discord import time import json from fuzzywuzzy import fuzz #local imports import config # command imports from commands import help, add_role, remove_role, lfg, list_roles, pizza, weather, raid, tradeskilladd, tradeskill, tradeskillremove, leave_server, giphy from rules import lfg_channel_clea...
# -*- coding: utf-8 -*- import logging import re import shlex from datetime import datetime from bot import listen_to from bot import respond_to from datasource import QueryableManager, QueryableManagerError, QueryPhrase @respond_to('^(.*)$') @listen_to('^(.*)$') def query_dispatcher(message, command_body): ''...
import lvgl as lv import widgets as w import icons as i import game as g import time as t NIGHT_THEME = lv.theme_night_init(210, lv.font_roboto_16) DEFAULT_THEME = lv.theme_default_init(210, lv.font_roboto_16) MATERIAL_THEME = lv.theme_material_init(210, lv.font_roboto_16) DISP_SCALE_X = 5 DISP_SCALE_Y = 4 class Ap...
import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff import math import os import sys import random from tqdm import trange def get_logistic_regression_dataset(dimension, num_samples_per_client, num_clients): """Creates logistic regression datset. Returns: A...
#! /usr/bin/env python3.6 """ This file contains configuration to prune MobileNet on the Imagenet dataset using the Dynamic Network Surgery strategy. """ from functools import partial import numpy as np import tensorflow as tf from nnet.datasets import imagenet_data from nnet.models.mobilenet import mobilenet_v1 fr...
import logging import shutil import numpy as np import os import torch class Reshape(torch.nn.Module): """Module that returns a view of the input which has a different size Parameters ---------- args : int... The desired size """ def __init__(self, *args): super().__init__() ...
# -*- encoding: utf-8 import itertools import json import time from datetime import datetime import requests from bs4 import BeautifulSoup, Tag # Making this a separate class from Work bc the URL being fetched is different and we will need to iterate through pages of comments. class WorkNotFound(Exception): pa...
import bottle import os from model import * rps_controller = RPS_controller() tiar_controller = GameController(TIAR) fiar_controller = GameController(FIAR) USERNAME_COOKIE = "username" COOKIE_SECRET = 'A common mistake that people make when trying to design something completely foolproof is to underestimate the ingen...
#!/usr/bin/env python import socket import time, sys from datetime import datetime from tld import get_tld #assign variables host = '' min_port = 20 max_port = 30 # This dictionary contains the most popular ports used # You can add ports here. # The key is the port number and the values is the service u...
from flask import Flask, request, render_template, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy # Time zones import pytz # time & atexit: scheduler of temperature recording import time import atexit from apscheduler.schedulers.background import BackgroundScheduler import datetime impor...
""" Copyright (c) 2021, <NAME>, Computational Imaging Science Lab @ UIUC. This work is made available under the MIT License. Contact: <EMAIL> """ import sys sys.path.append("../") import numpy as np import tensorflow as tf from fastMRI.common import subsample class GaussianSensor(object): """ A random gaussian ...
import os import sys import tarfile import numpy as np import sfdmap import extinction import hostphot from astropy import wcs from astropy.stats import sigma_clipped_stats from photutils.utils import calc_total_error def calc_sky_unc(image, exptime): """Calculates the uncertainty of the image from the sky s...
import numpy as np import EpidemiologicalModels.CellManagement as CellManagement class SystemMetrics: """Metricas que se monitorean por cada modelo: statusInTheSystem => Cantidad de individuos por estado numberOfIndividuals => Cantidad de individuos en el sistema percentagesInTheSystem => Cant...
""" CODE IS AMMENDED FROM: https://bitbucket.org/tanya14109/cqasumm/src/master/ """ import re import numpy import nltk from sklearn.feature_extraction.text import TfidfVectorizer from bs4 import BeautifulSoup class ANSWER: def __init__( self, answer, user_upvote_count, user_downvote_count, user_reputati...
from __future__ import annotations from collections import deque from operator import add, mul from typing import ( Callable, Deque, Dict, List, NamedTuple, NoReturn, Optional, Tuple, Union, ) from aoc import split_number_by_places ParameterModeList = List[int] class Instruction...