text
stringlengths
3.07k
12.6k
from typing import Optional import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras import Model from tensorflow.keras.layers import Layer import numpy as np import rinokeras as rk from rinokeras.layers import WeightNormDense as Dense from rinokeras.layers import LayerNorm, Stack class Ra...
import gzip import logging import logging.handlers import os from cStringIO import StringIO as IO from spreads.vendor.huey import SqliteHuey from spreads.vendor.huey.consumer import Consumer from spreads.vendor.pathlib import Path from flask import Flask, request from spreads.plugin import (HookPlugin, SubcommandHook...
""" ========================================================================== MeshNetworkCL_test.py ========================================================================== Test for NetworkCL Author : <NAME> Date : May 19, 2019 """ import pytest from pymtl3_net.meshnet.MeshNetworkCL import MeshNetworkCL from pym...
"""Home Assistant Python 3 API wrapper for Moving Intelligence.""" import datetime import logging from .utils import Utils _LOGGER = logging.getLogger("pymovingintelligence_ha") class MovingIntelligence: """Class for communicating with the Moving Intelligence API.""" def __init__( self, use...
""" Convnet classifier for MNIST data using TensorFlow. """ import tensorflow as tf import mnist.mnist as mnist import pandas as pd DEFAULT_INPUT_DIMENSIONS = 784 DEFAULT_OUTPUT_DIMENSIONS = 10 DEFAULT_LEARNING_RATE = 0.1 DEFAULT_BATCH_SIZE = 50 DEFAULT_KEEP_PROB = 0.5 class CNNClassifier(...
import gc from torch.autograd import Variable import torch import torch.autograd as ag import torch.nn as nn import torch.nn.functional as F import numpy as np from .context import Context from .nested import * class Function(object): def __call__(self, *args, **kwargs): raise NotImplementedError class ...
import torch import torch.nn as nn from torch.autograd import Variable import sklearn.preprocessing as skp import data_util as du import training class FXLSTM(nn.Module): def __init__(self, input_dim, hidden_size, num_layers, output_seq_len, bias=True, dropout=0, batch_first=F...
import os import csv import subprocess import matplotlib.pyplot as plt from math import ceil from tqdm import tqdm from pandas import read_csv from netCDF4 import Dataset, num2date from multiprocessing import cpu_count, Process from .plot import plot_filtered_profiles_data def download_data(files, storage_path): ...
import copy # Saves room and client list initialMsg = ':JACK! {0.0.0.0, 5000} PRIVMSG #: /JOIN #\n' # {IP,port} msg = "PRIVMSG #cats: Hello World! I'm back!\n" qmsg = "PRIVMSG #cats: /part #cats" client = "('127.0.0.1', 41704)" message = {'nick': '', 'client': '', 'chan': '', 'cmd': '', 'msg': ''} test = ":BEN! {('127...
from django.db import models from django.conf import settings from django.contrib.postgres.search import SearchVectorField from django.contrib.auth.models import AbstractUser from django.utils import timezone # BOOK-RELATED MODELS class Books(models.Model): title = models.CharField(max_length=5125) year...
import explorer import random import os import logic import copy import patches.dungeonEntrances import patches.goal from locations.items import * class Error(Exception): pass class Randomizer: def __init__(self, rom, options, *, seed=None): self.seed = seed if self.seed is ...
''' Investigating the offset of CIV emission in the Cloudy models as a function of ionization, nebular metallicity, stellar metallicity, stellar population type, age, etc. ''' import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from scipy.optimize import curve_...
from struct import pack, unpack, calcsize from enum import Enum import logging START_DELIMITER = 0x7E class XBeeOutFrame(object): def __bytes__(self): raise NotImplementedError("Subclass should implement this method") @staticmethod def calc_checksum(partial_frame): ''' partial_fr...
import pickle import numpy as np import scipy.linalg as sci from scipy import signal # Rotations def wrap2Pi(x): xm = np.mod(x+np.pi,(2.0*np.pi)) return xm-np.pi def Rot(x): return np.array([[np.cos(x),-np.sin(x)],[np.sin(x),np.cos(x)]]) def RotVec(x_vec, rot_vec): rvec = np.array([np.dot(x_vec[i,:-1],Rot(rot_ve...
# python import json import os import random import re import traceback import modo from . import util import yaml from .defaults import get from .symbols import * def yaml_save_dialog(): """ By <NAME> for Mechanical Color File dialog requesting YAML file destination. """ try: return ...
'create a subspace phone-loop model' import argparse import copy import pickle import sys import torch import yaml import beer # Create a view of the emissions (aka modelset) for each units. def iterate_units(modelset, nunits, nstates): for idx in range(nunits): start, end = idx * nstates, (idx + 1) *...
import torch import torch.nn as nn import argparse from torch.utils.data import Dataset import sys ''' Block of net ''' def net_block(n_in, n_out): block = nn.Sequential(nn.Linear(n_in, n_out), nn.BatchNorm1d(n_out), nn.ReLU()) return block class M...
''' Authors: <NAME> and <NAME> Date: July 10, 2017 Pre-cnmf-e processing of videos in chunks: - Downsampling - Motion Correction ''' from os import path, system import pims import av import numpy as np import math from tqdm import tqdm from skimage import img_as_uint from motion import align_video import skimage.io i...
# ------------------ [ Authors: ] ------------------ # # <NAME> # <NAME> # <NAME> import os, json, inspect, discord, asyncio, importlib, sys, keep_alive from helper.cLog import elog from helper.cEmbed import denied_msg, greeting_msg from helper.User import User from helper.Algorithm import Algorithm from c...
from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import List, Union, Optional, Tuple from OCP.BRepFeat import BRepFeat from OCP.TopAbs import TopAbs_FACE from OCP.TopExp import TopExp_Explorer from cadquery import cq from cq_cam.commands.base_command import Command from cq_cam....
from random import choice from flask import Flask, redirect app = Flask(__name__) words = { "1": "One Direction", "2": "Dr Who", "3": "Cup of herbal tea", "4": "Knock at the door", "5": "Johnny's Alive", "6": "Little Mix", "7": "<NAME>", "8": "Golden Gate", "9": "Selfie Time", ...
import pandas as pd import networkx as nx import collections from operator import itemgetter def clean_game_titles(t_names, g_names): t_names_inverse = collections.defaultdict(list) for k,v in t_names.items(): t_names_inverse[v].append(k) to_merge = {} for k,v in t_names_inverse.items(): if len(v) > 1...
from django.conf import settings from django.shortcuts import redirect, render from transport.models import * from transport.forms import * from django.contrib.auth.decorators import login_required import requests,json from django.template.loader import render_to_string, get_template from django.core.mail import Email...
import tensorflow as tf from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding from tensorflow.keras.activations import softmax, linear import tensorflow.keras.backend as K import numpy as np def gelu(x): return 0.5*x*(1+tf.tanh(np.sqrt(2/np.pi)*...
import pandas as pd from xml.etree import ElementTree as etree from pprint import pprint from yattag import * import pdb #------------------------------------------------------------------------------------------------------------------------ # -*- coding: utf-8 -*- #----------------------------------------------------...
""" Run Intervals. Takes 3 values from user, counts down intervals. wanted: Data class that holds state """ from datetime import timedelta import time import toga from toga.style import Pack from toga.style.pack import COLUMN, ROW class RunIntervals(toga.App): """ __init__ values in __init__.py: runsNu...
from enum import Enum import logging from blatann.nrf.nrf_dll_load import driver import blatann.nrf.nrf_driver_types as util from blatann.nrf.nrf_types.enums import * logger = logging.getLogger(__name__) class BLEGapSecMode(object): def __init__(self, sec_mode, level): self.sm = sec_mode ...
import sys import soundcard import numpy import pytest skip_if_not_linux = pytest.mark.skipif(sys.platform != 'linux', reason='Only implemented for PulseAudio so far') ones = numpy.ones(1024) signal = numpy.concatenate([[ones], [-ones]]).T def test_speakers(): for speaker in soundcard.all_speakers(): ass...
import torch from torch import nn, Tensor from typing import Tuple from ..components import ResidualRNN __all__ = ['Encoder', 'RNNEncoder', 'GRUEncoder'] class Encoder(nn.Module): def __init__(self, input_size, hidden_size, embedding_dim, num_layers, bidirectional, device, pad_token=0, drop_rate=0.1): s...
import datetime as dt import logging from collections import Counter, OrderedDict, defaultdict from dataclasses import dataclass from io import StringIO from operator import itemgetter input = """8 2017-01-03,16:18:50,AAPL,142.64 2017-01-03,16:25:22,AMD,13.86 2017-01-03,16:25:25,AAPL,141.64 2017-01-03,16:25:28,AMZN,84...
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod, abstractproperty from collections import Sequence import numpy as np class MatrixBase(object): __metaclass__ = ABCMeta _base_tags = set() @abstractmethod def __init__(self, backend, ioshape, iopacking, tags): self.backend = ...
# -*- coding: utf-8 -*- """ Created on Mon Apr 8 11:09:33 2019 @author: 10365 """ #CreateDataSet import numpy as np import sys sys.path.append('../subway_system') sys.path.append('../ato_agent') import TrainAndRoadCharacter as trc import trainRunningModel as trm import pandas as pds import matplotlib.pyplot as pl...
import binascii import uuid from collections import UserDict from functools import cmp_to_key, wraps from nanolib import Block as RawBlock from nanolib import nbase32_to_bytes, get_account_id __all__ = ( "RawBlock", "BlockProxy", "Callbacks", "CallbackSlot", "AccountIDDict" ) class BlockProxy(object): """ ...
""" Keras implementation of Pix2Pix from <NAME>'s tutorial. https://machinelearningmastery.com/how-to-develop-a-pix2pix-gan-for-image-to-image-translation/ """ from keras.initializers import RandomNormal from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU f...
#!/usr/bin/env python import datetime import json import pathlib import re import sys from typing import List, Optional from vaccine_feed_ingest_schema import location as schema from vaccine_feed_ingest.utils.log import getLogger logger = getLogger(__file__) RUNNER_ID = "az_pinal_ph_vaccinelocations_gov" def _g...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Author: <NAME> <<EMAIL>> # PGP: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x00bebdd0437ad513a4a0e13d93435cab4ca92fb9 # Date: 05.11.2021 import argparse import os # Unicode placeholders and their replacements uc_table = { b"LRE": chr(0x202a)...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ade: # Asynchronous Differential Evolution. # # Copyright (C) 2018-20 by <NAME>, # http://edsuom.com/ade # # See edsuom.com for API documentation as well as information about # Ed's background and other projects, software and otherwise. # # Licensed under the Apache Li...
#!/usr/bin/env python # pylint: disable=wrong-import-position # -*- coding: utf-8 -*- """ To run this script uncomment the following lines in the [options.entry_points] section in setup.cfg: console_scripts = fibonacci = dbupdater.skeleton:run Then run `python setup.py install` which will install the com...
""" Generate download locations within a country and download them. Written by <NAME>. 5/2020 """ import os import configparser import math import pandas as pd import numpy as np import random import geopandas as gpd from shapely.geometry import Point import requests import matplotlib.pyplot as plt from PIL import Ima...
import datetime import appdaemon.plugins.hass.hassapi as hass import calendar SHOULDER_START_HOUR = 13 PEAK_START_HOUR = 15 PEAK_END_HOUR = 19 # SHOULDER_END_HOUR = 21 SUMMER_MONTHS = [6, 7, 8, 9] ON_PEAK = 'on-peak' SHOULDER = 'shoulder' OFF_PEAK = 'off-peak' # PCCA = 0.00401 # DSMCA = 0.00159 # TCA = 0.00203 # CA...
# -*- coding: utf-8 -*- # Natural Language Toolkit: Interface to the TreeTagger POS-tagger # # Copyright (C) <NAME> # Author: <NAME> <<EMAIL>> """ A Python module for interfacing with the Treetagger by <NAME>. """ import os from subprocess import Popen, PIPE from nltk.internals import find_binary, find_file from nlt...
import collections import numpy import pandas import scipy from tqdm import tqdm from .common import say, reconstruct_antigen_sequences def compute_coverage(antigen, sequence, blast_df): """ Extract blast hits for some clones for a single antigen into a DataFrame indicating whether each clone aligns at...
# # Copyright (c) 2020 <NAME>. # # 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...
#!~/.virtualenvs/cv420/bin/python # -*- coding: utf-8 -*- """ Author: <NAME> Created: 4-May-2020 """ import serial import math from threading import Thread import rospy import time import numpy as np from std_msgs.msg import String ser = serial.Serial('/dev/ttyACM1',9600, timeout=5) # Ti MSP430 def inverse_Kinema...
#!/usr/bin/python from config.utils import * from elementals import Prompter from function_context import SourceContext, BinaryContext, IslandContext import os import sys import argparse import logging from collections import defaultdict def recordManualAnchors(library_config, knowledge_conf...
import logging import os import time import requests from lxml import etree import urllib.parse import json import schedule from colorama import Fore,init def getICBCNews()->tuple: logging.debug('Getting icbc news...') url = 'https://www.icbc.com.cn/ICBC/纪念币专区/default.htm' re = requests.get(url) htm...
#!/bin/python3 #Utilities for downloading and parsing Final Fantasy 14 Loadstone content #Copyright <NAME> 2016 BSD 3 clause license import requests from bs4 import BeautifulSoup import re def loastone_login(): print('http://na.finalfantasyxiv.com/lodestone/account/login/') #Get a page from the Loadstone # retur...
""" Reference: https://matheusfacure.github.io/python-causality-handbook/11-Propensity-Score.html# """ import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.neighbors import NearestNeighbors import seaborn as sns from matplotlib import pyplot as plt from causalinference...
import datetime from unittest import mock import pytest from h_matchers import Any from h.tasks import indexer class FakeSettingsService: def __init__(self): self._data = {} def get(self, key): return self._data.get(key) def put(self, key, value): self._data[key] = value clas...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ calibration_rig.py: trilateration microphone calibration Since trilateration doesn't account for the acoustic properties of the sound source, the results will be skewed. To account for this, it's possible to use machine learning to build a lookup table-like...
#!/usr/bin/env python3 # coding=utf-8 # # Copyright (c) 2020 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
# coding=utf8 """Class to compute total electron content.""" from .gnss import * class TecError(Exception): """Class for Tec related errors.""" pass class Tec(object): """Total electron content object. Attributes ---------- timestamp : datetime.datetime instance date and time of the...
import logging from six.moves.urllib.parse import urlsplit from django.conf import settings from django.conf.urls import url, re_path from django.core.exceptions import PermissionDenied from django.urls import reverse from django.utils.html import escape, format_html_join from wagtail.admin.menu import MenuItem from ...
# Copyright (c) 2014-present PlatformIO <<EMAIL>> # # 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...
import numpy as np import torch from pyquaternion import Quaternion from utils.data_classes import Box def anchor_to_standup_box2d(anchors): # (N, 4) -> (N, 4); x,y,w,l -> x1,y1,x2,y2 anchor_standup = np.zeros_like(anchors) # r == 0 anchor_standup[::2, 0] = anchors[::2, 0] - anchors[::2, 3] / 2 a...
# 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 th...
import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import dash_table import plotly.express as px import pandas as pd import requests from bs4 import BeautifulSoup import re from newspaper import Article import sys module_path = './que...
import click import vk.config as config import vk.utils as utils from vk.commands.query import show_layer_state def _add_layers(layer_str, current_layers, set_layers_func): """Append layers to current_layers and set to device props. Args: layer_str: A string in <layer1:layer2:layerN> format. ...
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applic...
from kivy.uix.screenmanager import Screen from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivymd.app import MDApp from kivymd.uix.tab import MDTabsBase from kivymd.icon_definitions import md_icons from kivymd.uix.button import MDRectangleFlatButton from kivy.lang import...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from subprocess import run, PIPE, TimeoutExpired from xmltodict import parse as parsexml # timeout # errorcode class IpsetError(RuntimeError): """ipset returned an error""" def _run_cmd(command, args=[]): """ Helper function to help calling and decoding i...
import asyncio import copy import discord import feedparser import sys import time import datetime import traceback import os import json from discord.ext import commands from urllib.parse import urlparse, parse_qs class Loop: """ Loop events. """ def __init__(self, bot): self.bot = bot ...
#!/usr/bin/env python3 # async_requests.py """Asynchronously get links embedded in multiple pages' HTML.""" import asyncio import logging import re import sys # from typing import IO # Use pathlib instead import urllib.error import urllib.parse import aiofiles import aiohttp from aiohttp import ClientSession impor...
import openmc from scipy import interpolate import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from matplotlib import ticker import matplotx import numpy as np import scipy.ndimage as ndimage def reshape_values_to_mesh_shape(tally, values): mesh_filter = tally.find_filter(filter_type=openmc.Mes...
import abc import time from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional, cast from loguru import logger from rich import print from dubdub import ( Binary, Grouping, Literal, Node, Token, TokenType, Unary, Visitor, dataclass, ) fro...
# Copyright (c) 2020 - present <NAME> <https://github.com/VitorOriel> # # 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, ...
import discord import ctftime import os import random from discord.ext import commands, tasks from datetime import datetime # Token generated from https://discord.com/developers/applications # Keep this private, if exposed generate new one TOKEN = '' # Bot channel ID was grabbed from Settings > Appearance > Developer...
import torch import torch.nn as nn import torch.nn.functional as F from FER.em_network.models.model import TimeDistributed class PhaseNet(nn.Module): def __init__(self): super(PhaseNet, self).__init__() self.group1 = nn.Sequential( nn.Conv2d(12, 24, kernel_size=(5, 5), stride=1, paddi...
"""This module contains all the actual logic of the project. The main method is run when the microcontroller starts and afer each sleep cycle. """ import logging import machine import network import ntptime import os import sdcard import ujson import urequests import utime from Adafruit_Thermal import Adafruit_Therma...
"""Tests the musicbrainz plugin.""" import datetime from unittest.mock import patch import musicbrainzngs # noqa: F401 import pytest import tests.plugins.musicbrainz.resources as mb_rsrc from moe.plugins import musicbrainz as moe_mb @pytest.fixture def mock_mb_by_id(): """Mock the musicbrainzngs api call `get...
# Author: <NAME> # Date: January 29, 2017 import tornado.ioloop import tornado.web import tornado.httpserver import hashlib import base64 import json import mysql.connector as sql dbuser = 'csse' # Register a new user class UserHandler(tornado.web.RequestHandler): def set_default_headers(self): self.set_header...
""" Adapted from https://github.com/hovinh/DeCNN """ import numpy as np from keras import backend as K class Backpropagation(): def __init__(self, model, layer_name, input_data, layer_idx=None, masking=None): """ @params: - model: a Keras Model. - layer_name: name of layer...
import random import numpy as np from gym_multigrid.multigrid import World from gym_multigrid.multigrid import DIR_TO_VEC from gym_multigrid.multigrid import Actions class Agent: def __init__(self, agent_id, agent_type=0): self.id = agent_id self.total_reward = 0 self.action_probabilities ...
from __future__ import annotations import asyncio import typing import types import pandas as pd import tooltime from ctc import evm from ctc import spec async def async_get_lending_flows( wallet: spec.Address, pool_token: spec.ERC20Reference, protocol: typing.Literal['aave', 'compound', 'rari'], w...
import os import wget import paddle from .tokenizer import Tokenizer from .model import CLIP from paddle.vision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize tokenizer = Tokenizer() def get_transforms(image_resolution): transforms = Compose([ Resize(image_resolution, interpolation='...
# -*- coding: utf-8 -*- """ #The following formula is used #Adjusted Volume = Raw Volume - Regression Slope * (TIV - Cohort Mean TIV) #Reference Literature: Voevodskaya et al, 2014: The effects of intracranial volume adjustment approaches on multiple regional MRI volumes in healthy aging and Alzheimer's disease """ i...
# from django.core.cache import cache from django.db.models import Sum from django.http import JsonResponse, Http404, HttpResponse from django.shortcuts import render, redirect from django.core.cache import cache # from django.urls import reverse # from django.views.decorators.csrf import csrf_exempt from blog.models...
# -*- coding: utf-8 -*- u"""zgoubi datafile parser :copyright: Copyright (c) 2018 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkresource from pykern.pkdebug import pkdc, pkdlog, pk...
INPUTPATH = "input.txt" #INPUTPATH = "input-test.txt" with open(INPUTPATH) as ifile: raw = ifile.read() program = tuple(map(int, raw.strip().split(","))) from enum import Enum class Mde(Enum): POS = 0 IMM = 1 REL = 2 from itertools import chain, repeat, islice from collections import defaultdict from typing import...
from collections import OrderedDict import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader torch.set_printoptions(linewidth=120) torch.set_grad_enabled(True) import torchvision from torchvision.transforms import transf...
import FreeCAD import FPEventDispatcher from FPInitialPlacement import InitialPlacements import FPSimServer import FPUtils pressEventLocationXY = dict() rotationAngleAtPress = dict() class FPSimRotaryPotentiometer(InitialPlacements): def __init__(self, obj): InitialPlacements.__init__(self, obj) o...
#!/usr/bin/env python3 # This is a script for using circuitpython's repo to make pyi files for each board type. # These need to be bundled with the extension, which means that adding new boards is still # a new release of the extension. # import mypy import json import pathlib import re def main(): repo_root = p...
import os def get_path(path): return os.path.split(path)[0] def get_filename(path): return os.path.splitext(os.path.basename(path))[0] def extract_turns(input): """ Génère automatiquement un fichier contenant le nombre de tours par locuteur à partir du fichier de tours :param input: :retu...
import copy import logging import torch import numpy as np from torch.utils.data import DataLoader from torchvision import datasets, transforms log = logging.getLogger(__name__) def balanced_batches(dataset, batch_size): unlabled_idx = dataset.unlabeled_idx labeled_idx = list(filter(lambda _: _ not in unlab...
""" amplitude.py measure the maximum peak-to-peak amplitude """ import obspy import types import numpy as np import pandas as pd import madpy.noise as n from typing import Tuple import madpy.checks as ch import madpy.config as config import matplotlib.pyplot as plt import madpy.plotting.amp as plot def measure_ampl...
# -*- coding: utf-8 -*- ''' Script Name: ping_Utility.py Path: \IPS_DecisionFabric\Exception Handling\ Description: This script is considered as a module for the Application level Exception handling in DF framework. Author: <NAME> Version: 1.0 Revision History: ---------------------------------------------...
# polar.py Fast floating point cartesian to polar coordinate conversion # Author: <NAME> # 31st Oct 2015 Updated to match latest firmware # 21st April 2015 # Now uses recently implemented FPU mnemonics # Arctan is based on the following approximation applicable to octant zero where q = x/y : # arctan(q) = q*pi/4- q*(q ...
#%% import numpy as np from scipy import integrate import matplotlib.pyplot as plt import matplotlib as mpl import random import time import copy from matplotlib import animation, rc from IPython.display import HTML def _update_plot (i,fig,scat,qax) : scat.set_offsets(P[i]) qax.set_offsets(P[i]) VVV=...
import sys import os import requests from datetime import datetime, timedelta import argparse import json def parseArgs(): parser = argparse.ArgumentParser() parser.add_argument('--startdate', nargs='?', default=getTodayStr(), type=str, help="Provide a start date, for example: 2019-06-13. \nDefaults to today's...
#- # ========================================================================== # Copyright (C) 1995 - 2006 Autodesk, Inc. and/or its licensors. All # rights reserved. # # The coded instructions, statements, computer programs, and/or related # material (collectively the "Data") in these files contain unpublished...
# Breadth First Search and Depth First Search class BinarySearchTree: def __init__(self): self.root = None # Insert a new node def insert(self, value): new_node = { 'value': value, 'left': None, 'right': None } if not self.root: ...
import boto3, json, time, os, logging, botocore, uuid from crhelper import CfnResource from botocore.exceptions import ClientError logger = logging.getLogger() logger.setLevel(logging.INFO) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) session = boto3.Se...
import os import random import datetime import argparse import numpy as np from tqdm import tqdm from model.unetdsbn import Unet2D from utils.loss import dice_loss1 from datasets.dataset import Dataset, ToTensor, CreateOnehotLabel import torch import torchvision.transforms as tfs from torch import optim from torch.op...
import os from pathlib import Path import pytest from ploomber.util import default from ploomber.exceptions import DAGSpecNotFound @pytest.fixture def pkg_location(): parent = Path('src', 'package_a') parent.mkdir(parents=True) pkg_location = (parent / 'pipeline.yaml') pkg_location.touch() retur...
""" @author: <NAME> @title: SmartSearch - An Intelligent Search Engine. @date: 05/06/2019 """ import requests from uuid import uuid4 from bs4 import BeautifulSoup from urllib.parse import urlsplit DOMAIN = "uic.edu" def check_goodness(url): """ Function to check if the url is a dead end (pds, doc, docx, etc...
import os from .vendored import colorconv import numpy as np import vispy.color _matplotlib_list_file = os.path.join(os.path.dirname(__file__), 'matplotlib_cmaps.txt') with open(_matplotlib_list_file) as fin: matplotlib_colormaps = [line.rstrip() for line in fin] def _all_r...
#!/usr/bin/env python3 """ pass.py Find hardcoded passwords on source code of your project. python pass.py path/to/project """ import os import sys import re import fnmatch import json from argparse import ArgumentParser DEFAULT_BAD_WORDS = ['token', 'oauth', 'secret', 'pass', 'password', '<PASSWORD>'] DEFAULT_ANAL...
import json import random from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String, MetaData, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql import select import monitor_db import monitor_logger import monitor_util Base = declar...
import pygame import os pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = int(SCREEN_WIDTH * 0.8) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Shooter') #set framerate clock = pygame.time.Clock() FPS = 60 #define game variables GRAVITY = 0.75 #define player action va...
import sys import os import numpy as np import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection import FasterRCNN from torchvision.models.detection.rpn import AnchorGenerator import wandb import json from cs329s_waymo_object_detection.utils.gcp_util...