text stringlengths 3.07k 12.6k |
|---|
import cv2
import numpy as np
import os
import argparse
import imageio
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation
from camera_calib.robonet_calibration import display_annotation
tip_coord = []
use_for_calibration = ["berkeley_sawyer_traj973", "berkeley_sawyer_traj5214", "berkeley_sa... |
import sys
import boto3
from botocore.exceptions import ClientError
import json
customer_file = open("customer_assessment_config.json")
customer_config = json.loads(customer_file.read())
customer_file.close()
def generate_account_list():
if 'Customer_Organization_Acct' not in customer_config:
... |
"""A general session store."""
from pickle import load, dump, HIGHEST_PROTOCOL as maxPickleProtocol
from warnings import warn
from time import time
from MiscUtils import AbstractError
def dumpWithHighestProtocol(obj, f):
"""Same as pickle.dump, but by default with the highest protocol."""
return dump(obj, ... |
from tkinter import *
window = Tk()
window.geometry("234x275")
Label(window, text = "Programa de Tradução DNA e RNA").pack()
window.title("BIOLOGIA")
def btn_click(item):
global expression
expression = expression + item
input_text.set(expression)
def btn_clear():
global expression
express... |
"""
Credit: https://github.com/jik876/hifi-gan
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
... |
from timeutil.timeutils import *
"""
Has a dictionary of subclasses. At the moment, new class types must be hardcoded in as follows.
This class is the big superclass controller of all the subclasses.
"""
class Class:
def __init__(self, cursor, ID):
# Initialize class by looking at its data
self.c... |
"""
Module for constructing models for use in MAST-ML.
SklearnModel:
Class that wraps scikit-learn models to have MAST-ML type functionality. Providing the model name as a string
and the keyword arguments for the model parameters will construct the model. Note that this class also supports
construction of ... |
import datetime
import glob
import logging
import os
from pathlib import Path
from typing import List
from datetime import timezone
import dateutil.parser
import xarray
from config.constants import TEMP_MIN_HOUR_UTC, NOAA_GOES16_PATH
from config.logging_conf import GOES_LOGGER_NAME
from plotters_lib.graf... |
import os
import itertools
import pandas as pd
def temp_vulnerability(temp, r_max, t_max, t_min, t_opt):
"""
Determine vulnerability index based on temperature.
Vulnerability scale goes from 1 to 5 with 1 being
the most vulnerable and 5 being the least.
Input
-----
temp (pd.Series): Tempe... |
from django.http import JsonResponse, HttpResponseServerError, HttpResponse
from io import StringIO
from Bio import AlignIO
from Bio.Align import MultipleSeqAlignment
from Bio.SeqUtils import IUPACData
from alignments.views import validate_fasta_string, calculateFastaProps, construct_dict_for_json_response
def handle... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 12 12:26:36 2020
@author: ayman
"""
import torch
import torch.nn as nn
import ptan
from typing import Union
from types import SimpleNamespace
import numpy as np
HYPERPARAMS = ({'cartpole':
SimpleNamespace(**{'ENV_ID':'CartPole-v0',
... |
import cocopod
import cocopod.utils as u
from cocopod.segment_assignment import *
from collections import OrderedDict
def test_get_complete_pairs_dict_from_topology():
from collections import OrderedDict
assert get_complete_pairs_dict_from_topology("ABCDabcd") == \
OrderedDict([('A', ['A',... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from .ternarized_modules import get_centroid, get_quantized, DtoA_3bit, AtoD_3bit
class _quanFunc(torch.autograd.Function):
def __init__(self, tfactor, grain_size, num_bits, M2D, sav... |
from typing import Dict, Any
from datetime import date, datetime, timedelta, timezone
from dateutil.relativedelta import relativedelta
from datahub import logger
from datahub.ggo import Ggo
from datahub.services import eloverblik as e
from datahub.meteringpoints import MeteringPoint
from datahub.services.energytypes i... |
""" Tests for the data.time module"""
from datetime import datetime, timedelta
# Third party imports
import pytest
import numpy as np
# Midgard imports
from midgard.data import time
@pytest.fixture()
def t(request):
return request.getfixturevalue(request.param.__name__)
@pytest.fixture
def t_dt_utc_s():
"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 1 23:18:20 2021
@author: changxin
"""
import os
import yaml
import argparse
import torch
import time
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from model import XLSR
from dataset import create_dataloader
from los... |
import dataclasses
from typing import Callable, Dict, FrozenSet, Iterable, List, Tuple, Union
import gamla
import knowledge_graph
from computation_graph import base_types
from knowledge_graph import primitives
from config_to_bot import dag_reducer
_Triplet = Tuple[str, str, Union[str, Tuple[str]]]
_Node = Union[Lis... |
import base64
import pathlib
import secrets
import operator
from operator import itemgetter
def test_get_hash(LIB, vectors_2):
for data, hashes in [operator.itemgetter("data", "hashes")(i) for i in vectors_2]:
for algo, encoding, digest in [operator.itemgetter("algo", "encoding", "digest")(j) for j in has... |
# ex3_kidou
import numpy as np
import matplotlib.pyplot as plt
def euler(t_start, t_end, dt, x_0, u_0, y_0, v_0, ax):
t = t_start
tary = [t]
xary = [x_0]
uary = [u_0]
yary = [y_0]
vary = [v_0]
while t < t_end:
r3 = np.sqrt(x_0 ** 2 + y_0 ** 2) ** 3
x_1 = x_0 + u_0 * dt
... |
#!/usr/bin/env python
import pdb
import os
import subprocess
import sys
import eventlet
eventlet.monkey_patch()
from config import Config
from flask_script import Manager, Command, Server as _Server, Option
from gesture_recognition import create_app, db, socketio
from offline import reset_tables
import shutil
manager ... |
import numpy as np
import argparse
import cv2
import scipy.optimize as opti
import matplotlib.pyplot as plt
from bead_util import find_all_fnames
import sem_util as su
gauss_kernel = 10
img_dir = '/Users/manifestation/Stanford/beads/photos/sem/20200624_gbeads-7_5um/'
substr = '7_5um_calibration_15000x_uc'
savep... |
"""
Run full recognition process.
"""
# Copyright (c) 2017 <NAME>. All rights reserved.
import sys
import cv2
from handwriting import findlines, findwords, findletters, extract, util
from handwriting import analysisimage, improc
from handwriting.prediction import Sample
from handwriting.cnn import ExperimentalCNN... |
import pygame as pg
from .. import setup
from .. import constants as c
from . import powerups
from . import coin
class Brick(pg.sprite.Sprite):
"""Bricks that can be destroyed"""
def __init__(self, x, y, contents=None, powerup_group=None, name='brick'):
"""Initialize the object"""
pg.sprite.Sp... |
#!/usr/bin/env python3
"""This version of numero ensures that each digit changes to a different digit
in each iteration."""
import os
import random
import shutil
import sys
import time
### Global "Constants" ###
SECS_TO_RUN = 3
SECS_TO_WAIT = 0.05
MAX_SECS_TO_WAIT = 0.5
DIGIT_SEP = ' '
NUM_DIGITS = 5
MIN_NUM_DIGIT... |
"""
Copyright 2022 Objectiv B.V.
"""
from typing import Any, Tuple, TYPE_CHECKING, Dict, Optional, Mapping
from sqlalchemy.engine import Dialect
from bach.series import Series
from bach.expression import Expression, join_expressions
from bach.types import DtypeOrAlias, get_series_type_from_dtype, StructuredDtype, Dty... |
#!/usr/bin/env python3
''' Starbot - posting Zkillboard Kills matching foo to Discord '''
import json
import configparser
import asyncio
import logging
import websocket
import discord_notify as dn
## Settings
CONFIG_FILE = "/home/starbot/starbot.ini"
## No touchy
#websocket.enableTrace(True)
logging.basicConfig(f... |
import pytest
from typing import Generator, Tuple
from itertools import product
from eightdad.core import VideoRam
def all_coordinates(vram: VideoRam) -> Generator[Tuple[int, int], None, None]:
"""
Syntactic sugar abstracting iteration over all pixels
:param vram: the video ram to get width and height f... |
import os
import shutil
import sys
import pathlib
from typing import Union
import click
from mass_apk import logger as log
from mass_apk.adb import Adb
from mass_apk.apk import AdbError, map_apk_paths
from mass_apk.exceptions import MassApkFileNotFoundError
from mass_apk.helpers import MB
from mass_apk.ziptools impo... |
from simple_rest_client.resource import Resource
class CustomerResource(Resource):
actions = {
"list": {"method": "GET", "url": "customers"},
"create": {"method": "POST", "url": "customers"},
"retrieve": {"method": "GET", "url": "customers/{}"},
"update": {"method": "PUT", "url": "... |
'''
Author: <NAME>
Script for evaluation metric methods
'''
from scipy.stats import logistic
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score
from sklearn.metrics import matthews_corrcoef, confusion_matrix
from sklearn.metrics import mean_squared_error as mse
impo... |
"""
This module provides tools to call moto using moto and botocore internals without going through the moto HTTP server.
"""
import sys
from functools import lru_cache
from typing import Callable
from botocore.parsers import create_parser
from moto.backends import get_backend as get_moto_backend
from moto.core.except... |
import math
from kivy.app import App
from kivy.graphics import *
from kivy.properties import NumericProperty, ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stencilview import StencilView
from kivy.uix.widget import Widget
from kivy.uix.behaviors.button import ButtonBehavior
from cont... |
#!/usr/bin/env python
# Copyright (c) 2019, <NAME>
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
from __future__ import print_function, division, absolute_import
# Try to keep imports to a minimum; from the standard library as much
# as possible. We have to conda... |
#!/usr/bin/env python
# coding: utf-8
# In[61]:
from datetime import datetime
from sklearn.preprocessing import RobustScaler
from sklearn.model_selection import KFold, cross_val_score
from sklearn.metrics import mean_squared_error , make_scorer, mean_absolute_error
from sklearn.linear_model import ElasticNetCV, Lass... |
#!/usr/bin/python2
"""Controls Pi on cart."""
import multiprocessing
import time
import numpy as np
import serial
import zmq
import sys
import struct
import freenect
import cv2
class MotorControlProcess(multiprocessing.Process):
"""Send commands to motor control board."""
def __init__(self, command_queue, se... |
"""
Generator and Predictor classes for the byte-level CharNER model for NER.
"""
# pylint: disable=too-many-locals
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-statements
# pylint: disable=invalid-name
import tensorflow as tf
import numpy as np
import ner.data.dataset as data
from ner... |
"""
Copyright 2015 Rackspace
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
dist... |
"""
哔嘀影视新域名: https://www.mp4er.com/
网页端加入了验证码, 考虑到验证码形式容易改变, 故未使用机器学习识别
新版本接口:
GET https://www.mp4er.com/api/v1/search/$(keyword)/1
token: <KEY>...(需计算)
token := encrypt(timestamp, key)
timestamp 为时间戳字符串经过 UTF-8 编码的二进制数组
key 为 { 73, 76, 79, 86, 69, 66, 73, 68, 73, 89, 73, 78, 71, 82, 72, 73 }, 即 "ILOVEBIDIYINGRHI"
R... |
#!usr/bin/env python3
import subprocess
import colorama
import re
from prettytable import PrettyTable
from colorama import Style, Fore
from sys import exit
# for terminal colors
colorama.init(autoreset=True)
BRIGHT_WHITE = Style.BRIGHT + Fore.WHITE
BRIGHT_YELLOW = Style.BRIGHT + Fore.YELLOW
BRIGHT_RED = Style.BRIGHT +... |
class Node:
""" The linked list contains a series of connected nodes. Each node holds data. """
def __init__(self, data):
""" Constructor for Node class
:param data: any data that the node will hold
"""
self.data = data
self.next = None
def __repr__(self):
... |
import importlib
from sqlalchemy import Column, ForeignKey, Enum as SQLAEnum
from sqlalchemy.orm import relationship, reconstructor
from sqlalchemy.dialects.postgresql import UUID
from pydantic import ValidationError as PydanticValidationError
from transitions import Machine
from transitions.extensions.states import ... |
"""Tests for finish_release.py"""
from datetime import datetime
import re
import os
import pytest
from exception import VersionMismatchException
from lib import check_call
from release import create_release_notes
from release_test import make_empty_commit
from finish_release import (
check_release_tag,
finish... |
import sys
import matplotlib.pylab as plt
from statistics import mean
iocs = {} # global index of coincidences dict (period, avg)
sequences = {} # global storage of periods and corresponding sequences
deciphered = [] # global storage of min chi-sq values corresponding indices
english_letters_index = {'A': 0, 'B':... |
import threading
from uldaq import (get_daq_device_inventory,
DaqDevice,
InterfaceType,
DigitalDirection,
DigitalPortType)
from enum import Flag, auto
import argparse
import time
import paho.mqtt.client as mqtt
import os
interfaceType = Interf... |
#!/usr/bin/env python
"""
mail2tsv.py: convert email file to tsv data for orange3
usage: mail2tsv.py file1 [file2 ...] > file.tsv
20190722 erikt(at)xs4all.nl
"""
import csv
from datetime import datetime
import re
import sys
import time
IDFIELD = "id"
FILEFIELD = "file"
FROMFIELD = "from"
TOFIELD = "to"
DA... |
'''
'''
import numpy as np
import fusilib.io.spikes2 as iospikes
time_locked_events_matrix = iospikes.time_locked_spike_matrix
def time_locked_delay_matrix(event_ids,
oldtimes,
newtimes,
dt,
delay_windo... |
import pathlib
import re
import tempfile
import urllib.request
import f90nml
def typecast_value(value: str):
if "real(" in value:
value, exponent = value.split("(")[-1].split(",")[0].lower().split("d")
return float(f"{value}e{exponent}")
elif "_rkind" in value:
return float(value.spli... |
import torch
import torch.nn as nn
class AADLayer(nn.Module):
def __init__(self, h_channel, z_channel, z_id_size=256):
super(AADLayer, self).__init__()
self.normalization = nn.BatchNorm2d(h_channel)
self.conv_h = nn.Conv2d(h_channel, h_channel, kernel_size=3, stride=1, padding=1)
se... |
"""Binary search tree."""
class Node(object):
"""BST Node object class."""
def __init__(self, val, parent=None):
"""Constructor method for BST Node."""
self.val = val
self.left = None
self.right = None
self.parent = parent
class BST(object):
"""Binary search tree... |
'''
Module with a class to create a generator for low-frequency images.
'''
# System imports
import time
# Standard imports
import numpy as np
import matplotlib.pyplot as plt
import itertools
class LowFreqGenerator(object):
'''
A class to create a generator of low-frequency images.
'''
def __init__... |
'''
This script reads initial and final density data cubes from PLUTO and computes
the gamma-ray flux in all computational cells inside a region defined by a .reg file.
Then integrate along y-axes.
The script can work on multiple processors
'''
import os
import sys
import pyregion
import numpy as np
import astropy.unit... |
import math
import random
import torch
import numpy as np
def box_muller_transform(x: torch.FloatTensor):
r"""Box-Muller transform"""
shape = x.shape
x = x.view(shape[:-1] + (-1, 2))
z = torch.zeros_like(x, device=x.device)
z[..., 0] = (-2 * x[..., 0].log()).sqrt() * (2 * np.pi * x[..., 1]).cos()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Health check running container."""
import argparse
import contextlib
import datetime
import json
import os
import subprocess # nosec
import sys
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from argparse import ArgumentParser
from typing impo... |
import bl2sdk
class Lootbeams(bl2sdk.BL2MOD):
Name = "Loot Notificator"
Description = "Adds Special Particles to all Red Text gear. Also plays a sound. src and Reborn."
Author = "Juso"
SettingsInputs = {"Enter": "src"}
_Exodus = False
_Reborn = False
def SettingsInputPressed(self, name):
... |
# Originally from edusense/production: https://github.com/edusense/production
import argparse
import datetime
import os
import subprocess
import sys
import tempfile
import csv
import logging
# duration for each class
metadata = {
# '05418A': 10
}
NUM_GPUS = 6
def writelog(message, f):
if f is not None:
... |
"""
vdfutils.py
Utilities for processing Valve KeyValue data formats.
"""
from collections import OrderedDict
VALID_CHARS = (
'abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'
'-_.'
)
WHITESPACE = ' \r\n\t'
# Byte that gets appended to keys to ensure uniqueness
UNIQUEIFIER = ... |
"""
Dino Runner Clone
"""
from os import SEEK_SET
import sys
import time
from pygame.display import get_window_size
import settings
from settings import *
from display import *
import gameover
# 변수 설정
class element:
scores = 0
gravity = 5
time1 = time.time()
velocidade = 100
game_speed = 1.2
ga... |
# License: Apache 2.0. See LICENSE file in root directory.
# Copyright(c) 2021 Intel Corporation. All Rights Reserved.
# we want this test to run first so that all tests run with updated FW versions, so we give it priority 0
#test:priority 0
#test:device L500*
#test:device D400*
import pyrealsense2 as rs, sys, os, su... |
import pandas as pd
import ukpopulation.snppdata as SNPPData
#import ukpopulation.myedata as MYEData
import ukcensusapi.Nomisweb as CensusApi
from .utils import lad_lookup
def map_ages(df_syoa):
# age mapping for DC2101EW
age_mapping = {
1: (0, 4),
2: (5, 7),
3: (8, 9),
4: (10, 14),
5: (15, 15... |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... |
import golly as g
import random
def rand_rule(prob):
isotropicsetS = isotropicsetB = {"0",
"1c", "1e",
"2c", "2e", "2k", "2a", "2i", "2n",
"3c", "3e", "3k", "3a", "3i", "3n", "3y", "3q", "3j", "3r",
"4c", "4e", "4k", "4a", "4i", "4n", "4y", "4q", "4j", "4r", "4t", "4w", "4z",
... |
"""
Container class for a radio source.
Author: <NAME>
Contact: <EMAIL>
"""
from . import CONFIGURATION as config
import astropy, math
from astropy.time import Time
from astropy import units as u
from astropy.coordinates import SkyCoord, EarthLocation, AltAz, ICRS, Galactic
import time, ephem, datetime
import numpy as... |
'''
@file: dataprepare.py
@author: qxLiu
@time: 2020/3/4 10:45
'''
import numpy as np
import os
import os.path as path
IN_ESBM_DIR = os.path.join(path.dirname(os.getcwd()), 'data', 'in_ESBM_benchmark_v1.2')
IN_EMBED_DIR = os.path.join(path.dirname(os.getcwd()),'data','in_embed')
OUT_MODEL_DIR = os.path.join(path.dirnam... |
"""
LSH for cosine distance.
"""
from pyspark import SparkContext, RDD
import numpy as np
from types import GeneratorType
from datming.utils import join_multiple_keys
__all__ = [
"CosineSimilarity"
]
class CosineSimilarityLSH(object):
def __init__(self, n_dimension: int, threshold: float=0.,
... |
from django.db import models
from django.shortcuts import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class Portfolio(models.Model):
"""Model describing Portfolio metadata."""
# NOTE:
# The three features image fields are configured as a FileField
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torchvision
import numpy as np
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
from maskrcnn_benchmark.structures.keypoint import Buildi... |
"""Integration with Arvados Keep. using the API with arvados-python-sdk.
"""
import os
import six
import toolz as tz
from bcbiovm.shared import retriever as sret
# ## Arvados specific functionality
KEY = "keep"
CONFIG_KEY = "arvados"
def _get_api_client(config=None):
if not config: config = {}
if "token" i... |
#!/usr/bin/env python3
import re
def parse_time_to_ms(time_string: str) -> float:
"""Given a time string with various unit, convert
to ms in float:
wrk time unit reference
https://github.com/wg/wrk/blob/master/src/units.c#L17-L21
Example:
"71.91ms" -> 71.91
"50us" -> ... |
import logging
import os
import re
from collections import defaultdict
from subprocess import Popen, PIPE
from typing import List, Tuple, Union, Optional, Any
import pandas as pd
from refseq_masher.const import REGEX_FASTA, REGEX_FASTQ
from .const import REGEX_FASTQ, REGEX_FASTA
NT_SUB = {x: y for x, y in zip('acgtr... |
from functools import cached_property
from textwrap import indent
from importlib import import_module
from pathlib import Path
from uuid import uuid4
from contextlib import contextmanager
from distutils.core import setup, Extension as _Extension
from tempfile import TemporaryDirectory
from sys import platform
from os i... |
from collections import defaultdict
from functools import partial
from json import loads
import generator
BASE_NESTED = {"ids": generator.attrdict}
def model_from_item(client, item):
type_ = item["type"]
return TYPE_MAP[type_](client, item[type_])
class BaseModel(object):
id_key = None
extendabl... |
#!/usr/bin/env python3
#
# python wrapper for conformance suite API
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import asyncio
import json
import re
import httpx
import os
import shutil
import time
import traceback
import zipfile
class RetryTransport(... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 28 17:33:12 2019
@author: Adam
"""
import os
import sqlite3
import datetime
import pytz
import warnings
import logging
logger = logging.getLogger(__name__)
# ploting
from bokeh.core.properties import value
from bokeh.io import curdoc
from bokeh.models.callbacks import Cus... |
from unittest import TestCase
import unittest
from utility_functions.databricks_uf import rdd_to_df
from market_basket.mb_run import market_basket_sql, market_basket_stats
from division_view_market_basket.cvm_pre_processing import MarketBasketPullHistory
from division_view_market_basket.cvm_post_processing import CVMPo... |
from colorfield.fields import ColorField
from django.db import models
from django.core.validators import MaxValueValidator
from django.utils.translation import ugettext_lazy as _
from .constants import IMAGE_EFFECT_BW, IMAGE_EFFECT_CHOICES
class TileDesignOptions(models.Model):
'''
Tile design options.
... |
import actsUtils, re, string
from stylesheet import *
from PyQt6 import QtWidgets, QtGui, QtCore
aUtils = actsUtils.ActsUtils()
# Fills main window with data about law acts
def fillLinkList(self):
self.linkList.clear()
for act in aUtils.getSearchResutList(): #TODO http://isap.sejm.gov.pl/api/isap/dee... |
#!/usr/bin/env python3
from flask import Flask, url_for, redirect, render_template, flash, request
import os
import google
import sql
import auth
import forms
import prefix
app = Flask(__name__)
baseurl = os.environ.get("BASEURL")
if baseurl is not None:
app.wsgi_app = prefix.PrefixMiddleware(app.wsgi_app, prefi... |
from itertools import izip, islice, compress
import numpy as np
import pytest
from learntools.data.dataset import Column, TimeColumn, EnumColumn, MatColumn, Dataset
# match by getting a single truth value (this is complicated by the fact that
# numpy array eq returns an array rather than a single value)
class AWrap... |
import os
import time
import sys
from PIL import Image, ImageFilter
import pyautogui
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
sys.setrecursionlimit(2000) # 递归次数限制
pic_path = 'pic.jpg' # 图片路径
alpha = 0.05 # 高斯核标准差
winSize = 21 # 高斯核大小
draw_delay = 0.001 # 绘制延迟
jd = 1 # 绘制精度
gl = 200 #... |
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merg... |
import os
import json
import redis
import shutil
import docker
import subprocess
import urllib.request
from time import time
from zerobnl.config import *
from zerobnl.logs import logger
from zerobnl.simulation import CoSimCreator
from zerobnl.simulation.compose import create_full_yaml
here = os.path.dirname(os.path... |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
from __future__ import absolute_import, unicode_literals
# stdlib imports
import json
# 3rd party imports
import pytest
from mock import Mock, patch
# Project imports
from restible import RestEndpoint, RestResource
#####################
# Test data ... |
# Copyright © 2017-2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribut... |
import torch
import warnings
import torch.nn as nn
import os.path as osp
import graphgallery as gg
from graphgallery import functional as gf
class TorchKeras(nn.Module):
"""Keras like PyTorch Model."""
def __init__(self, *args, **kwargs):
self.__doc__ = super().__doc__
super().__init__(*arg... |
# @th3_protoCOL
import os, re, yara
from tqdm import tqdm
from elasticsearch import Elasticsearch
class EXT_yara():
def __init__(self, id):
self.id = id
self.dir = "static/output"
def scan_ext(self, rule):
id = self.id
print("\033[93m[*]\033[00m Starting yara scan for "+id+" wi... |
import signal
import os
import time
from threading import Event
from threading import Thread
from scapy.all import Ether, ICMP, IP, get_if_hwaddr, sendp
from simple_switch.simple_switch_runner import SimpleSwitchDocker
from simple_switch.simple_switch_runner import make_switch
from simple_switch.compile import compi... |
# Copyright (c) 2019-present, <NAME>
from fairseq.models import (
FairseqEncoderDecoderModel,
register_model,
register_model_architecture,
)
from fairseq import options
from fairseq.models.lstm import LSTMDecoder
from sightseq.models.text_recognition_encoder import TextRecognitionEncoder
@register_model... |
# coding=utf-8
'''
Created on 2016-9-27
@author: dengdan
'''
# Copyright [yyyy] [name of copyright owner]
# Copyright 2020 Huawei Technologies 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 ob... |
from __future__ import division
from collections import namedtuple
__all__ = ["parse_paf"]
__version__ = "0.0.9"
try:
import pandas as pd
except Exception as E:
pandas = False
e = E
else:
pandas = True
class _PAF:
"""Base PAF methods, can't guarantee field names here so use indices"""
def... |
import cv2
import numpy as np
import os
import h5py
# Get the Image
def imread(path):
img = cv2.imread(path, 0) #grayscale
img = img/255. #normalize so that values lie between 0 and 1
img = np.expand_dims(img, axis=2) #(48, 48) -> (48, 48, 1)
return img
def imsave(image, path, config):
#checkim... |
from tree.tree import Binary_Tree, TNode
from tree.binary_search_tree import Binary_Search_Tree
import pytest
@pytest.fixture
def fixture_tree():
bt = Binary_Tree(1)
bt.root = TNode(5)
bt.root.left = TNode(4)
bt.root.right = TNode(14)
bt.root.left.left = TNode(2)
bt.root.left.right = TNode(-1)
... |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import flask
from flask import Flask
from flask import request
from flask import jsonify
from flask_restful import Resource, Api, reqparse
from flask_apispec import marshal_with, doc, use_kwargs
from flask_apispec.views import M... |
import asyncio
import contextlib
import json
import locale
import logging
import os.path
import signal
import subprocess
from asyncio.subprocess import PIPE, create_subprocess_exec
import psutil
import lambentlight.server as server
from .config import default_folder as default
from .resources import LocalResource
fro... |
# - coding: utf-8 -
import struct
from collections import namedtuple
from ..exceptions import ERROR_CODES
from ..utils import Serializable, ApiVersionAware, struct_helpers
class Request(Serializable, ApiVersionAware):
"""Base class for all Requests. Handles writing header information"""
HEADER_LEN = 21 # co... |
# Algorithm to compute pi via subdividing unit square recursively
# and seeing it is part of the circle or not.
from __future__ import division
def iterate(x, y, iteration, N):
'''
Determines whether a square
size = (1 / 2 ^ iteration)
at coord (x, y)
is inside the unit circle or not.
returns... |
import json
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
import attr
import morecantile
import planetary_computer as pc
from cachetools import TTLCache, cached
from cachetools.keys import hashkey
from cogeo_mosaic.errors import NoAssetFoundError
from fastapi import HTTPException
from geojson_... |
# Copyright (C) 2018 <NAME>
# <pierrejean dot fichet at posteo dot net>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "... |
# coding: utf-8
"""
purpose: this utility converts xml doc exported by Draw.io to json used by Learning Anything mindmap
created_by: weng
created_on: 2017-07-13
"""
try:
from lxml import etree as etree
except ImportError:
import xml.etree.ElementTree as etree
import collections
import re
la_node_data = {... |
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without res... |
link_list = [
[
"Office Hours",
"475 653 618",
"officehour",
"https://oklahoma.zoom.us/j/475653618?pwd=cGpreUNhNGNSMklxSnVsUFU0SFQ2dz09",
],
[
"AG Reading Course",
"139 716 655",
"386420",
"https://oklahoma.zoom.us/j/139716655?pwd=<PASSWORD>GZ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.