text stringlengths 3.07k 12.6k |
|---|
import os
import csv
import cv2
import numpy as np
import sklearn
from random import shuffle
from numpy import zeros, newaxis
from sklearn.model_selection import train_test_split
test_split = 0.25
samples = []
images = []
angles = []
cam_delta_left = 0.25 # 0.15 # 0.25 0.08
cam_delta_right = 0.25
nb_epoch = 5
batch_... |
from dataclasses import dataclass, field
from typing import Dict
from pathlib import Path
from typing import Any, Union
from yaml import dump, full_load
@dataclass
class Flags:
""" Class to instantiate parameters """
### Required parameters
# The training method to use. Either regular sequence classifica... |
#!/usr/bin/python
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 <NAME> <<EMAIL>>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://moz... |
import requests
# I HATE FOR LOOPS
# I HATE FOR LOOPS
from functools import reduce
from time import sleep
from random import choice, randint
WLIST = "./res/watchlist.ini"
CONT = "./res/oldy.txt"
VERS = "5.131"
TOKEN = "./res/token.ini"
# failed codes.
EMPTY_WALL = -1
BANNED = -2
def has_error(eresp: dict)... |
#!/usr/bin/env python
#
# test_version.py -
#
# Author: <NAME> <<EMAIL>>
#
import os.path as op
import textwrap
import pytest
from . import testdir
import fsl.version as fslversion
def test_parseVersionString():
tests = [
('0.0.0', [0, 0, 0]),
('0.0.10', ... |
import os
import hashlib
import struct
def getFileMd5(filePath):
with open(filePath, "rb") as bf:
file_md5 = hashlib.md5(bf.read())
md5 = file_md5.hexdigest()
return md5
def getFileSize(filePath):
fsize = os.path.getsize(filePath)
fsize = fsize / float(1024)
return round(fsize... |
# Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... |
# -*- coding: utf-8 -*-
import argparse
import os
def process_verbosity(args):
verbosity = os.environ.get('VERBOSITY_LEVEL', None)
if verbosity is not None:
try:
verbosity = int(verbosity)
except ValueError:
verbosity = None
if verbosity is None:
verbosity =... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__a... |
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
import os
from spatial_transformer import transformer
def localization(inputs):
with tf.variable_scope('localization'):
with slim.arg_scope([slim.conv2d],
activation_fn=tf.nn.relu,
... |
import torch
from torch import nn
import utils
class AlexNetEncoder(nn.Module):
def __init__(self, in_channel, feature_dim):
super(AlexNetEncoder, self).__init__()
self._conv_block_1 = nn.Sequential(
nn.Conv2d(in_channel, 48, 3, 1, 1),
nn.BatchNorm2d(48),
nn.Re... |
""" Module to deal with the interface with the global config information."""
import logging
import yaml
import copy
import os
from pathlib import Path
__all__ = ["setConfigFileName", "loadConfig", "get", "findFile", "change"]
class ConfigEnvironmentalVariableNotSet(Exception):
pass
class ParameterNotFoundInCo... |
"""User login and auth.
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
from a... |
# -*- coding: utf-8 -*-
"""
Miscellaneous utilities and tools
"""
from __future__ import absolute_import, print_function
import functools
import keyword
import os
import re
import sys
from contextlib import contextmanager
from operator import itemgetter
from distutils.filelist import FileList
from six import PY2
fro... |
import pygame
import time
import random
pygame.init()
# Define colors, because the PyGame library
# does not do this by default
white = (255, 255, 255)
darkGray = (50, 50, 50)
lightGray = (150, 150, 150)
black = (0, 0, 0)
red = (245, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
display_width = 800
display_height = 6... |
from pdf2image import convert_from_path
import cv2
import numpy as np
from PIL import Image, ImageEnhance
from fpdf import FPDF
import os
from alive_progress import alive_bar
def invertLight(bgr):
# Convert to hls
hls = cv2.cvtColor(bgr, cv2.COLOR_BGR2HLS)
# Extract hls
h, l, s = cv2.split(hls)
... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from cv2 import cv2
import time
import os
import operator
import numpy as np
import argparse
from PIL import Image
__author__ = 'zj'
image_formats = ['jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG']
def is_pgm_file(in_path):
if not os.pa... |
from flask import (
render_template,
request,
redirect,
url_for,
Blueprint,
send_from_directory,
abort,
)
from models.blog import (
Blog,
BlogComment,
)
from models.category import Category
import os
from werkzeug.utils import secure_filename
from config import us... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 29 09:32:34 2021
@author: <NAME>
"""
import numpy as np
import dask.array as da
from magicgui import magic_factory
from napari_plugin_engine import napari_hook_implementation
import napari.types
from napari.types import ImageData, LayerDataTuple
from typing import TYPE_... |
import logging
import datetime as dt
import wukong.errors as solr_errors
from wukong.request import SolrRequest
from wukong.zookeeper import Zookeeper
import json
logger = logging.getLogger(__name__)
def _add_scheme_if_not_there(url, scheme='http'):
if not (
url.startswith('http://')
or url.starts... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
"""I/O that speaks the S3 protocol
The S3 protocol is an HTTP-based protocol spoken by Amazon Web Services, but
also storage systems such as Ceph (used in particle physics). Therefore,
this can be widely used if you know the appropriate endpoint.
Be aware that you must specify the following two environmental variabl... |
import numpy as np
import pandas as pd
from utils.combine import merge_by_index
def add_et_indices(data_trial, data_et, min_gaze_points=3):
data_trial['optionIndex'] = add_option_index(data_trial, min_gaze_points)
data_trial['attributeIndex'] = add_attribute_index(data_trial,
... |
import math
from tkinter import *
from menu import *
from sciencalc import *
from simplecalc import *
from menu import *
def buttonPress(num):
global content
content+=str(num)
answer.set(content)
def pressEqual():
try:
global content
total = str(eval... |
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import matplotlib as mpl
plt.style.use('classic')
import sys
import numpy as np
import os
from scipy.optimize import curve_fit
from matplotlib import cm
import matplotlib.colors as colors
import matplotlib.cm as cm
from functions import count_number_of_fi... |
# -*- coding: UTF-8 -*-
# Copyright (c) 2018, <NAME> & <NAME>
# All rights reserved.
#
# This file is part of the pymatreader Project, see: https://gitlab.com/obob/pymatreader
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... |
"""
CRIS - Request Download Helper
Author: Austin Transportation Department, Data and Technology Services
Description: The purpose of this script is to provide helper functions
that can list and download emails from S3, moving files within the S3
to other folders, parsing emails, downloading the files from a link
with... |
from functools import partial
import html
from signature_altering import decorator
__version__ = '0.0.2'
VOID_ELEMENTS = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'}
RAW_TEXT_ELEMENTS = {'script', 'style'}
ESCAPABLE_RAW_TEXT_ELE... |
import argparse
from functools import partial
from typing import Dict
import torch
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from pytorch_lightning import loggers as pl_loggers
from pytorch_lightning.core.lightning import LightningModule
from transformers import BertConfig, BertForSequen... |
# Copyright (c) 2021 <NAME>. All Rights Reserved.
import os
import pymel.core as pm
import maya.cmds as cmds
import piper.core.util as pcu
import piper.mayapy.util as myu
import maya.internal.nodes.proximitywrap.node_interface as node_interface
def returnToBindPose(joints=None):
"""
Returns the associated b... |
from __future__ import absolute_import
__author__ = 'breddels'
import numpy as np
import logging
from vaex.dataframe import DataFrame
import vaex
from frozendict import frozendict
logger = logging.getLogger("vaex.server.dataframe")
allowed_method_names = []
# remote method invokation
def _rmi(f=None):
def decor... |
# Copyright (c) <NAME>
# See LICENSE
from twisted.internet import interfaces
from zope.interface import implements
import autobahn.twisted.websocket
import json
import twunnel.local_proxy_server__ssl
import twunnel.logger
import twunnel.proxy_server
class WSOutputProtocol(autobahn.twisted.websocket.WebSocketClientPro... |
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description="Analyse the logs produced by torchbeast")
parser.add_argument("--dir", type=str, default="~/logs/torchbeast", help="Directory fo... |
from castledice.common.globals import (
ANIMAL_PREFERENCE,
BARN,
GATHER_PREFERENCE,
JOAN,
RESOURCE_PREFERENCE,
TURN,
)
from castledice.die.dieClass import Die
from castledice.playermat.models import JoanPlayerMat
from castledice.users.models import User
"""
Joan is a simplistic AI built for sol... |
import re
import time
from loguru import logger
from .operate import Operate
from Performance import recoder
class Automation:
def __init__(self, operate: Operate, labelsName, task):
self.operate = operate
self.screen = ""
self.isRun = True
self.labelsName = LabelsName(**labelsNa... |
"""
Mask R-CNN
Train a toy custom dataset and implement color splash effect.
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by <NAME>
Improved by <NAME>
------------------------------------------------------------
Usage: import the module (see Jupyter notebooks f... |
"""Contains tests for the strings module.
"""
import datetime
import logging
import os
import sys
aries_parent = os.path.join(os.path.dirname(__file__), "..", "..")
if aries_parent not in sys.path:
sys.path.append(aries_parent)
from Aries.test import AriesTest
from Aries.strings import AString, FileName
logger = ... |
from dataclasses import dataclass, field, InitVar
import yaml
import logging
from androidcrypto.dataset import Dataset, DatasetException
import androidcrypto.helpers as helpers
import androidcrypto.constants as constants
import typing
import sys
import math
class ConfigException(Exception):
pass
def get_size(o... |
import numpy as np
import math
import NN_From_Scratch as NN
save_path = "" # 保存模型路径
# 字符串转浮点数
def string_float(text):
string_float = 1.0
if text.find('^') != -1 or text.find('**') != -1:
if text.find('^') != -1:
str_list = text.split("^", 1)
string_float = math.pow... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from nni.nas.pytorch.mutables import LayerChoice, InputChoice
from .rnn_utils import EmbeddingDropout, LockedDropout, create_mask2d
class Cell(nn.Module):
def __init__(self, args):
super(Cell, self).__init__()
self.n_hidden = arg... |
import pandas as pd
import numpy as np
import pickle
from utils.config import *
def get_text(*dataframe, columns=["Question", "Dialogue", "Report"], concater=" "):
"""
把训练集,测试集的文本拼接在一起
:param dataframe: 传入一个包含数个df的元组
:param columns: 要拼接的列
:param concater: 怎么拼接列,默认用空格拼接
:return:
"""
te... |
from cv2 import cv2
import dlib
import numpy as np
from messaging.rabbitmq import receive, create_queue
import os
import sys
def shape_to_np(shape, dtype="int"):
"""
Convert landmarks to coordinates array
:param shape: landmarks
:param dtype: array type
:return:
"""
# initiali... |
import sys, os
import django
import csv
import calendar
import datetime
import re
import argparse
import openpyxl
import pandas as pd
from typing import TYPE_CHECKING, Dict, List, Optional
from pandas._typing import FilePathOrBuffer, Scalar
from django.core.mail import send_mail
from django.db import transaction
os.e... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import CubicSpline # for warping
from transforms3d.axangles import axangle2mat # for rotation
'''####################################################################'''
def checknan(x):
if (x != x).any():
idx = np.where(np.isn... |
# -*- coding: utf-8 -*-
import os, sys, typing, threading
import tkinter as tk
from cefpython3 import cefpython as cef
from .assets import base_icon_file, base_js_file
class BrowserAPI:
"""
BrowserAPI base class
func execute_javascript: execute javascript code in webview
func execute_function: execut... |
import math
import tkinter as tk
from tkinter import font
import os
from member import Member
#Wrapper for tk.Tk() incorporating the title and icon already
class Tk_rt(tk.Tk):
ico_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../img/phys.ico")
def __init__(self, title):
super().__init__()
sel... |
# coding: utf-8
# In[1]:
# get_ipython().run_line_magic('matplotlib', 'inline')
# get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'")
import copy
import numpy as np
import pandas as pd
from random import uniform
import matplotlib.pyplot as plt
def MSE(y, Y):
return np.mean((y-Y)**... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
complexity.generate
-------------------
Functions for static site generation.
"""
import json
import logging
import os
import shutil
import re
from binaryornot.check import is_binary
from jinja2 import FileSystemLoader
from jinja2.environment import Environment
fro... |
#!/usr/bin/env python3
# PYTHON_ARGCOMPLETE_OK
from dataclasses import dataclass
from simple_parsing import Serializable
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.tensorboard import SummaryWriter
from top.train.event.hub imp... |
from torchsummary import summary
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
class STN3d(nn.Module):
def __init__(self, channel):
super(STN3d, self).__init__()
self.conv1 ... |
"""
@name: PyHouse/src/Modules/scheduling/sunrisesunset.py
@author: <NAME>
@contact: <EMAIL>
@copyright: (c) 2011-2015 by <NAME>
@note: Created on Mar 6, 2011
@license: MIT License
@summary: Calculate the suns location at local noon, then calculate sunrise and sunset for the day.
Passed all 6 tests ... |
#!/usr/local/bin/python3
# extractSeqs.py
# Pull out FASTA sequences from BLAST output format 6
#
# Author: <NAME> (<EMAIL>
# Created on 14 Jun 2017
# Updated on 21 Jun 2017
from __future__ import print_function, absolute_import, division
import sys
import os
import time
import datetime
import argparse
import re
impor... |
#!/usr/bin/env python3
import argparse
import json
import os
import signal
import subprocess
import sys
import tempfile
import time
from bigchaindb_driver.crypto import generate_keypair
dir = os.path.dirname(__file__)
build_dir = os.path.join(dir, '../build')
# These are names of some OCF desktops
# proper way to do... |
import socket
import pickle
from copy import deepcopy
import threading
import sys
from os import system
import codes as code
import time
from tools import *
import settings
def recv_all_data(server, players_data, cells_data):
print("Recieving...")
while True:
try:
data, addr = recieve(se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dataclasses import dataclass
from typing import Optional, List, Tuple
import nonebot
from nonebot.adapters.cqhttp import Bot, MessageSegment
from nonebot.adapters.cqhttp import Message
from epicteller.bot import bus
from epicteller.bot.controller import combat as com... |
import os, sys
import shutil
import subprocess
import tensorflow as tf
import numpy as np
import tkinter as tk
from skimage.transform import resize as imresize
from glob import glob
from os.path import join as opj
from PIL import ImageTk, Image, ImageDraw, ImageFont
from tkinter.filedialog import askopenfilename
from ... |
# -*- coding: utf-8 -*-
import scipy as sp
import scipy.signal as sp_sig
import scipy.interpolate as interpolate
import pylufia.mir.common as common
import copy
def make_framed_data(input, framesize=512, hopsize=256, window='boxcar'):
"""
Slice waveform per frame
Parameters:
inData: ndarray
... |
#this is the imports section of the code - all of these are necessary for the program to run properly
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from alpha_vantage.timeseries import TimeSeries
import dash
import dash_core_components as dcc
import d... |
import os
import configparser
import math
import json
import random
import pickle
import time
import numpy as np
from VAFile import VAFile
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR,'data/')
print('BASE_DIR: ' + BASE_DIR)
print('DATA_DIR: ' + DATA_DIR)
f = open("13143_64.p... |
import numpy as np
import numba
from scipy.stats import norm
from monte_carlo import mc_bs_eu_numba, longstaff_schwartz, mc_bs_eu_is_numba
@numba.jit(nopython=True, parallel=False)
def call_payoff_numba(x, strike):
return np.maximum(x - strike, 0)
@numba.jit(nopython=True, parallel=False)
def put_payoff_numba(x... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.modeling.make_layers import conv_with_kaiming_uniform
from maskrcnn_benchmark.modeling.make_layers import conv4gcn_with_kaiming_uniform
def initialize_weigh... |
import os
import time
from typing import List, Dict, Any
import numpy as np
import pandas as pd
from ..helpers._utils import multiprocess_map
from .._logger import logger
__all__ = ["NumpyWriter"]
class NumpyWriter:
"""Write dataset into a set of numpy shards.
Args:
shard_size (int, optional):
... |
"""
https://en.wikipedia.org/wiki/Wavefront_.obj_file
test models can be found at:
http://people.sc.fsu.edu/~jburkardt/data/obj/obj.html
"""
from __future__ import print_function
from codecs import open
from numpy import array, unique, hstack, zeros
def read_obj(obj_filename, log=None, debug=False):
"""loads a ... |
# Copyright 2022 DeepMind Technologies Limited. 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 a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME> (<EMAIL>)
# @Date: 2019-04-24
# @Filename: actor.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
from __future__ import annotations
import asyncio
import json
import logging
import os
from tempfile import NamedTemporaryFil... |
from cyvcf2 import VCF
from argparse import ArgumentParser
import pandas as pd
import numpy as np
import pyranges as pr
import sys
from math import ceil
def main():
args = get_args()
targets = get_input(args.input, extension=args.extension)
make_targets_file(targets.df, flanks=args.flanking, prefix=args.p... |
# coding=utf-8
# Copyright 2017-2019 The THUMT Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import torch
import torch.nn as nn
import tagger.utils as utils
import tagger.modules as modules
from tagger.data import load_glove_embeddin... |
from pyrealtime.layer import ProducerMixin, ThreadLayer, TransformMixin, EncoderMixin, DecoderMixin
import time
def find_serial_port(name):
"""Utility function to scan available serial ports by name. The returned object is intended to be passed to the
:meth:`~pyrealtime.serial_layer.SerialWriteLayer.from_port... |
from io import BytesIO
import logging
if 'compatibility' not in globals():
from . import compatibility
__copyright__ = 'Copyright (C) 2019, Nokia'
CHILD_MODULES = [compatibility]
LOGGER = logging.getLogger(__name__)
class MemoizeSingleArg(object):
def __init__(self, f):
self._f = f
self._... |
import uuid
import errno
import os
from installed_clients.AssemblyUtilClient import AssemblyUtil
from installed_clients.DataFileUtilClient import DataFileUtil
from installed_clients.KBaseReportClient import KBaseReport
from installed_clients.MetagenomeUtilsClient import MetagenomeUtils
from installed_clients.Workspace... |
'''
Evoque - managed eval-based freeform templating
Copyright (C) 2007 <NAME> <<EMAIL>>
Licensed under the Academic Free License version 3.0
URL: http://evoque.gizmojo.org/
'''
__url__ = "$URL: svn://gizmojo.org/pub/evoque/trunk/bench/basic.py $"
__revision__ = "$Id: basic.py 1138 2009-01-15 17:44:52Z mario $"
#
# Tem... |
import mxnet as mx
import numpy as np
import numpy.matlib
import numpy.random
import os
import json, pickle
import random
import logging
import lmdb
import time
class SimpleBatch(object):
def __init__(self, data_names, data, label_names, label,
bucket_key=None, qid=None, ans_all=None, splits=None):
... |
import torch
import numpy as np
import torch.nn as nn
import sys
def one_hot(labels, num_classes):
'''
Converts an integer label torch.autograd.Variable to a one-hot Variable.
Parameters
----------
labels : torch.autograd.Variable of torch.cuda.LongTensor
N x 1 x H x W, where N is batch siz... |
import logging
import threading
import time
import keyboard
import activity_log
import notification
import sound
import text_generator
logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')
stop = False # スレッドの終了用
interval = 2 # 記録の間隔
working_state_list = ["start",
"te... |
from __future__ import annotations
from typing import Callable, Iterable, Optional
import argparse
from pathlib import Path
import os
from textwrap import dedent
from rich.console import Console
from argcomplete import autocomplete
import splatlog as logging
from . import io, dyn, err
from .rich_fmt import RichFormat... |
#!/usr/bin/env python
import sys, os
import struct
import dpkt
import socket
from cStringIO import StringIO
_MAGIC = 0x21 # '!'
_TAG_NETAL_FRAME_PUSHED = 0x10
_TAG_NETAL_DATA_SENT = 0x11
_TAG_NETAL_DATA_RECEIVED = 0x12
_TAG_NETAL_FRAME_POPPED = 0x13
_TAG_APP_CMD_SENT = 0x30
_isTx = {_TAG_NETAL_FRAME_PUSHED: True,
... |
from datetime import datetime
import logging
from multiprocessing import Pool
import os
import sys
from typing import Dict, List, Tuple
import carball
import psycopg
logging.basicConfig(
level=logging.INFO,
stream=sys.stdout
)
logger = logging.getLogger("rumbleStats")
item_translation = {
'BALL_FREEZE':... |
"""Tests pairwise interactions given output of mihifepe"""
import copy
import csv
import itertools
import sys
import time
from unittest.mock import patch
import anytree
from anytree.importer import JsonImporter
import numpy as np
from mihifepe.compute_p_values import compute_p_value
from mihifepe import constants
fr... |
import pytest
from collections import OrderedDict
from FeedRecordedFuture import get_indicator_type, get_indicators_command, Client
GET_INDICATOR_TYPE_INPUTS = [
('ip', OrderedDict([('Name', '192.168.1.1'), ('Risk', '89'), ('RiskString', '5/12'),
('EvidenceDetails', '{"EvidenceDetails": []}... |
import inspect
import os
import sys
from jsun import loads
from .color_printer import color_printer as printer
from .exc import LocalSettingsError, SettingsFileDidNotPassCheck
from .loader import Loader
from .util import abs_path, get_file_name, load_dotenv
# Exported (but unused locally)
from .checker import Checke... |
"""
# Nmap helper code
## Performance:
The NMAP default are tailored for a home network (wired/ wireless). To understand the impact, you must read:
* [Port Scanning Techniques](https://nmap.org/book/man-port-scanning-techniques.html)
* [Timing and Performance](https://nmap.org/book/man-performance.html).
* [Timing Temp... |
import datetime
import bs4
import requests
from collections import namedtuple
import telebot
import time
#создаем кортеж для хранения всей необходимой информации по каждой игре
InnerBlock = namedtuple('Block', 'title, sale_price, regular_price, sale, url, image')
class Game(InnerBlock):
#создаем класс для хранения и... |
from collections import deque
import logging
import os
import numpy as np
from chainerrl.experiments.evaluator import Evaluator
from chainerrl.experiments.evaluator import save_agent
def train_agent_batch(agent, env, steps, outdir,
checkpoint_freq=None, log_interval=None,
... |
from PIL import ImageFilter, ImageStat, Image, ImageDraw
from multiprocessing import Pool, cpu_count
from sklearn.preprocessing import LabelEncoder
import pandas as pd
import numpy as np
import glob
import cv2
import processing_images
from keras.wrappers.scikit_learn import KerasClassifier
from keras.models import Seq... |
import sys
import os
import numpy
import pandas as pd
import pydicom
import scipy.ndimage
import SimpleITK as sitk
import matplotlib.pyplot as plt
from skimage import measure, morphology
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
# This code is used to do all of the preprocessing of extracting patches for... |
# Utilities for object detector.
import numpy as np
import sys
import tensorflow.compat.v1 as tf
import os
from threading import Thread
from datetime import datetime
import cv2
from utils import label_map_util
from collections import defaultdict
tf.disable_v2_behavior()
detection_graph = tf.Graph()
sys.... |
#!/usr/bin/env python3
"""
This is a simple script to compute the Roofline Model
(https://en.wikipedia.org/wiki/Roofline_model) of given HW platforms
running given apps
Peak bandwidth must be specified in GB/s
Peak performance must be specified in GFLOP/s
Arithemtic intensity is specified in FLOP/byte
Performance is ... |
# This file is public domain, it can be freely copied without restrictions.
# SPDX-License-Identifier: CC0-1.0
from collections import defaultdict, namedtuple
from itertools import cycle
import matplotlib.pyplot as plt
import cocotb
from cocotb.triggers import Timer
from cocotb.utils import get_sim_time
Dataset = n... |
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, JsonResponse, QueryDict
from .models import SideBarMenus, TeacherProfiles, \
GlobalCodes, Country, State, Distr... |
# -*- coding: utf-8 -*-
'''
Manage Cloudwatch alarms
========================
.. versionadded:: 2014.7.0
Create and destroy cloudwatch alarms. Be aware that this interacts with
Amazon's services, and so may incur charges.
This module uses boto, which can be installed via package, or pip.
This module accepts explici... |
"""
Description: helper module for different apps
"""
import os
from dateutil import tz
from datetime import datetime, date
from collections import OrderedDict
from core.general.exceptions import SIDException
from core.general import settings
def clean_string(i_string):
"""
clean functio... |
"""
Name: NMFD
Date: Jun 2019
Programmer: <NAME>, <NAME>
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
If you use the 'NMF toolbox' please refer to:
[1] <NAME>, <NAME>, <NAME>, and <NAME>
NMF Toolbox: Music Processing Applications of Nonnegative Matrix
... |
from django.db import models
# Create your models here.
#add_to_end: 2017-08-24 08:42:19.063507
from django.urls import reverse #Used to generate URLs by reversing the URL patterns
import uuid # Required for unique book instances
from django.contrib.auth.models import User
from datetime import datetime
#add_to_end: ... |
# Copyright 2020 The mT5 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
from logging import getLogger
logger = getLogger('dungeon')
import random
import itertools
import sys
def neighbors(n):
x, y = n
return (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)
def _AStar(start, goal):
def heuristic(a, b):
ax, ay = a
bx, by = b
return abs(ax - bx) + abs... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
import alsaaudio # Advanced Linux Sound Architecture
import audioop
import numpy
import os
import shutil
import sys
import time
from pyAudioAnalysis import MidTermFeatures as aF
from pyAudioAnalysis import audioTrainTest as aT
import matplotlib
import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile
matpl... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
from dace.memlet import Memlet
import dace.libraries.blas as blas
import dace.libraries.lapack as lapack
import numpy as np
import pytest
###############################################################################
def generat... |
"""
To use the code, users should to config detpath, annopath and imagesetfile
detpath is the path for 15 result files, for the format, you can refer to "http://captain.whu.edu.cn/DOTAweb/tasks.html"
search for PATH_TO_BE_CONFIGURED to config the paths
Note, the evaluation is on the large scale images
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.