text stringlengths 3.07k 22.1k |
|---|
import os
import numpy as np
import torch
import pdb
from trajectory.utils import discretization
from trajectory.utils.arrays import to_torch
from .d4rl import load_environment, qlearning_dataset_with_timeouts
from .preprocessing import dataset_preprocess_functions
def segment(observations, terminals, max_path_lengt... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Create the data for the LSTM.
"""
import os
import sys
import argparse
import numpy as np
import h5py
import itertools
from collections import defaultdict
class Indexer:
def __init__(self, symbols = ["<pad>","<unk>","<s>","</s>"]):
self.vocab = defaultdict... |
"""
Original file: cartpole.py
Modifications by <NAME>
"""
"""
Classic cart-pole system implemented by <NAME> et al.
Copied from https://webdocs.cs.ualberta.ca/~sutton/book/code/pole.c
"""
''' To do:
- Import all cart pole specs form the config.json file
'''
import logging
import math
import numpy as np
from ... |
from models import *
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.http import HttpRequest, HttpResponse
import time, smtplib, math, urllib2, random, datetime
from django.template import Context, loader
import urllib
def game_view(request, game_id):
game = get_object_or_4... |
#!/usr/bin/python
# (c) Copyright 2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# 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/licen... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: mmcdaniel
@date: 2018-06-05
@brief: A small plotter tool
"""
import matplotlib.pyplot as plt
import sys
import os
import re
import pandas as pd
import shutil
import pathlib
import argparse
"""
This script assumes you are running from the command line.
A... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import num... |
import json
import numpy as np
import pandas as pd
def add_languages(df):
"""
Extract languages data from pandas dataframe and return complete dataframe
with language columns added
:param df: pandas dataframe
:return: pandas dataframe
"""
df = df.reset_index()
languages = df['language... |
"""
TRAINING FUNCTIONS: this file in run in 'script mode' when `.fit` is called
from the notebook. `parse_args` and `train_fn` are called in the
`if __name__ =='__main__'` block.
"""
import argparse
import joblib
from lightgbm import LGBMClassifier
import os
from pathlib import Path
from sklearn.base import BaseEstimat... |
# Copyright (c) 2019-2020, NVIDIA 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... |
#!/usr/bin/env python
import sys,string
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors, AllChem
import os
from optparse import OptionParser
'''
Given a list of SMILES strings, generate 3D conformers in sdf format using RDKit.
Energy minimizes and filters conformers to meet energy window and rms cons... |
import struct
import numpy as np
import pygimli as pg
def importGTT(filename, return_header=False):
"""Import refraction data from Tomo+ GTT data file into DataContainer."""
header = {}
with open(filename, 'rb') as fid:
block = fid.read(100)
nshots = struct.unpack(">I", block[:4])[0]
... |
import threading
import time
from functools import wraps
import statsd
import strgen
from flask import make_response
from flask import request
from flask_login import current_user
from flask_login import login_user
import config as base_config
import database.user
import util.cache
import util.response
from linkr imp... |
#! /usr/bin/env python
import argparse
import datetime
import os
import pickle
import time
import tensorflow as tf
from sklearn.model_selection import KFold
from data_helpers import batch_iter
from model_config import DEFAULT_CONFIG
from text_cnn import build_model
def _define_model_config(data, pre_embedding, conf... |
"""Create the vaccination groups and the vaccination rank.
Vaccination Groups
==================
1 = Highest Priority
--------------------
- overall 8.6 Mio individuals = ~10% of the population
- 1% live in nursing homes (https://bit.ly/3vFsByz) and not covered in our data
=> target of 9%
- over 80 year olds -> 4%... |
import os
import sys
import h5py
import pickle
import argparse
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
# from pytorch_transformers.modeling_bert import BertForSequenceClassification, BertConfig, MultimodalBertForSequenceClassification
# from pytorch_t... |
import argparse
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
INTELLIJ_VERSION_FLAG = "-intellij-version"
def is_environment_in_jdk_table(environment_name, table):
for elem in table:
for subelem in elem:
attribute = subelem.attrib
if attribute.get("valu... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 17:37:16 2020
@author: Ronin
"""
import pandas as pd
import numpy as np
from ast import literal_eval
from pydantic import BaseModel, Field, validator
import os
import json
import ast
import praw
import requests
from bs4 import BeautifulSoup
import re
import pickle
from... |
#!/usr/bin/env python
# en esta versión usamos pyqtgraph para mostrar la posición
# de la cámara en 3D
# python pose3D.py --dev=../../images/rot4.mjpg
import pyqtgraph as pg
import pyqtgraph.opengl as gl
from pyqtgraph.Qt import QtCore, QtGui
import cv2 as cv
import numpy as np
import numpy.linalg as la
from um... |
# Some experiments in adding character encoding conversions to xmlproc.
# This module is not yet used by the released xmlproc, since I'm awaiting
# a reorganization.
#
# $Id: charconv.py,v 2.2 1999/06/14 21:34:18 larsga Exp $
import string
# --- Conversion tables
# CP 850 to ISO 8859-1
# First element... |
#
# Please note that this file has been modified by Unbound Tech
#
""" Functional tests for encryption / decryption """
import collections
import logging
import pytest
from pypkcs11.default_templates import get_default_key_template, get_default_key_pair_template, \
MECHANISM_LOOKUP_EXT
from pypkcs11.defines impor... |
import os
from random import shuffle
from collections import deque
import networkx as nx
import numpy as np
import graph_methods as gm
global random
global social
global friends
global acquaintance
global bridges
random = 0
social = 1
friends = 2
acquaintance = 3
bridges = 4
# random = 0 # random defined above
d... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PyCOMPSs Testbench Tasks
========================
"""
# Imports
from pycompss.api.task import task
from pycompss.api.parameter import *
import types
# #### DECORATORS #####
from decorator import decorator
import time
# #### SERIALIZER #####
import sys
if sys.version_i... |
"""
Module with auxillary
jit-compiled functions
for resize of
CT scans
"""
from numba import jit
import scipy.ndimage
from PIL import Image
import numpy as np
@jit(nogil=True)
def resize_scipy(patient, out_patient, res, order=3, factor=None, padding='edge'):
""" Resize 3d scan and put it into out_pa... |
# encoding: utf-8
#
# 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://mozilla.org/MPL/2.0/.
#
# Author: <NAME> (<EMAIL>)
#
from __future__ import unicode_literals
from jx_python import jx
from... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import numpy as np
from scipy.special import gamma, psi
from scipy import stats
from sklearn.neighbors import NearestNeighbors
from typing import Optional
from sklearn.base import BaseEstimator
from sklearn.utils import gen_batches
from .ensemble import Batch, BootStrap
from sklearn.utils import check_random_state, che... |
import matplotlib.pyplot as plt
import numpy as np
import os
import math
# import debugging tools
from korbinian.utils import pr, pc, pn, aaa
def save_hist_AAIMON_single_protein (fig_nr, fig, axarr, df_cr, s, TMD, binarray, zipout, row_nr, col_nr, fontsize, savefig, AAIMON_hist_path_prefix):
"""Save histogram show... |
import re
import json
import random
import logging
import MeCab
import pkuseg
import markovify
import pycld2 as cld2
from itertools import islice
from ckiptagger import data_utils, construct_dictionary, WS, POS, NER
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)... |
"""
*"The Grammar of Graphics (2005)"* by **Wilkinson**, **Anand** and
**Grossman** describes three types of transformations.
* *Variable transformations* - Used to make statistical operations on
variables appropriate and meaningful. They are also used to new
variables.
* *Scale transformations* - Used to make sta... |
"""
Runs tests with invalid zone files on different implementations.
Generates queries using GRoot equivalence classes.
Either compares responses from mulitple implementations with each other or uses a expected
response to flag differences (only when one implementation is passed for testing).
usage: test_with_invalid_... |
#
# Image processing
# Some codes come from https://github.com/rpautrat/SuperPoint
# input image is supposed to be 3D tensor [H,W,C] and floating 0~255 values
#
import cv2 as cv
import numpy as np
import tensorflow as tf
from misc import get_rank
def ratio_preserving_resize(image, size, method=tf.image.Res... |
#!/usr/bin/python
# Copyright (c) 2017, 2020 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
'''
@Author : <NAME>
@Email : <EMAIL>
@CreateTime : 2018/11/3
@Program : 绘制游戏的背景和元素
'''
import pygame
from sudoku import function
from sudoku.SetVar import SetVar
from sudoku.function import selected_array
setting = SetVar()
def statistics(gameArray):
# 统计游戏数组中各个数字出现的次数。
num_dict = {}
... |
import concurrent.futures
import csv
import math
import os
import sys
from datetime import timedelta
from glob import glob
from os.path import join
from time import time
import cv2
import GPUtil
import keras
import numpy as np
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
from matplo... |
"""
Copyright 2018 Software Reliability Lab, ETH Zurich
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 t... |
import time
import argparse
import numpy as np
import torch
import torch.optim as optim
from utils import accuracy
from models_calibration import *
from utils import *
from util_calibration import _ECELoss
from util_calibration import *
import os
global result
result = []
# Training settings
parser = ar... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
try:
import Tkinter as tk
import tkFileDialog
except:
import tkinter as tk
from tkinter import filedialog as tkFileDialog
import platform
import sys
import os
from PIL import Image
# Default Configuration
# ---------------------
# Initial Directory
initial_dir ... |
# Import BeautifulSoup
from bs4 import BeautifulSoup as bs
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
#from xml2sdk import xml2sdk
content = []
events = ''
states = ''
stateNames = []
transitions = ''
eventLabel = ''... |
import ply.yacc as pyyacc
from .exprlex import tokens
from .astdef import (
AstConstant,
AstExpression,
AstExprType,
AstOperator,
AstSymbol,
AstSymbolFlag
)
precedence = (
("left", "PLUS", "MINUS"),
("left", "MUL", "DIV", "DOT"),
("left", "EXP", "CROSS"),
("left", "APOSTROPHE"),... |
import folium
import logging
import os
from statistics import mean
from folium.plugins import MarkerCluster
#doc clustering https://nbviewer.jupyter.org/github/python-visualization/folium/blob/master/examples/MarkerCluster.ipynb
#doc popup https://nbviewer.jupyter.org/github/python-visualization/folium/blob/m... |
import numpy as np
import pandas as pd
import os
from jrieke import utils
from tqdm import tqdm_notebook
import multiprocessing
from settings import settings
import torch
from torch.utils.data import Dataset, DataLoader
from tabulate import tabulate
# Binary brain mask used to cut out the skull.
mask = utils.load_n... |
#! /usr/bin/python
# Take a directory full of things to be signed, and do the right thing.
# Make sure you cert-sign the windows installers, first
from __future__ import print_function
import sys
import os
import time
import shutil
################################################################################
def e... |
from setuptools import Distribution, find_packages, setup
from setuptools.extension import Extension
from distutils.version import LooseVersion
import glob
import io
import os
from os.path import exists, join, splitext
import platform
import struct
import sys
from Cython.Build import cythonize
import Cython.Compiler.... |
"""
This file contains all necessary plugins classes that the framework will use to let a user interact with custom models, data loaders, etc...
The Registry pattern used here is inspired from this post: https://realpython.com/primer-on-python-decorators/
"""
import inspect
import json
import logging
import os
from ab... |
from __future__ import division
from models import *
from utils.utils import *
from utils.datasets import *
import os
import sys
import time
import datetime
import argparse
from PIL import Image
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable... |
"""
Copyright (c) 2014 <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, distribute, sublice... |
"""
.. module:: snmp
:platform: Unix
:synopsis: A source module for polling SNMP. Requires PySNMP4
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from zope.interface import implementer
from pysnmp.entity import engine, config
from pysnmp.hlapi.twisted import cmdgen
from pysnmp.carrier.twisted import dispatch
from pysnm... |
import pickle
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(suppress=True)
"""
Load recordings
"""
indxs = {}
logged_state_names = [
'time_step', 'episode_id', 'veh_id', 'trace', 'glob_x',
'speed', 'act_long', 'min_delta_x', 'att_real']
index = 0
... |
import random
import time
import gym
import numpy as np
import torch
import torch.nn.functional as F
from fireup.algos.per_dqn import core
from fireup.utils.logx import EpochLogger
from stable_baselines.common.segment_tree import MinSegmentTree, SumSegmentTree
from stable_baselines.deepq.replay_buffer import ReplayBu... |
#coding=utf-8
from __future__ import division
from __future__ import print_function
import os, sys
import argparse
import tensorflow as tf
import numpy as np
import time
from .utils import *
from .minibatch import MinibatchIterator
from .model import DGRec
seed = 123
np.random.seed(seed)
tf.set_random_seed(seed)
... |
from base64 import urlsafe_b64encode
from uuid import uuid4
from typing import List, Optional, Union
import httpx
from lnbits.db import open_ext_db
from lnbits.settings import WALLET
from .models import Products, Orders, Indexers
import re
regex = re.compile(
r"^(?:http|ftp)s?://" # http:// or https://
r"(?:(... |
import functools
import inspect
import six
from doubles.call_count_accumulator import CallCountAccumulator
from doubles.exceptions import MockExpectationError, VerifyingBuiltinDoubleArgumentError
import doubles.lifecycle
from doubles.verification import verify_arguments
_any = object()
def _get_future():
try:
... |
import argparse
import json
import os
import abc
class ArgParser(object):
def __init__(self, model_name):
self.model_name = model_name
parser = argparse.ArgumentParser()
# parser from main args or load defaults
self.parser = self._build_parser(parser)
self.args, self.unknow... |
from typing import Union
import math
import shapely
from shapely.geometry import Polygon, box
from shapely.ops import transform, cascaded_union
import pyproj
import geopandas as gpd
from geopandas import GeoDataFrame as GDF
import pandas as pd
# pylint: disable=chained-comparison
def get_utm_zone_epsg(lon: float, la... |
import unittest
from multiprocessing import current_process
from typing import Iterable, Any
from coba.exceptions import CobaException
from coba.pipes import Filter, ListSink, ListSource
from coba.pipes.core import Pipes, Foreach, SourceFilters, FiltersFilter, FiltersSink
class SingleItemIdentity:
def filter(s... |
#!/usr/bin/env python3
""" Create a proxy of each records, where each nucleotide within the factor = 1, the rest = 0
"""
from Bio import SeqIO
import sys
import os
import numpy as np
import itertools
__author__ = "<NAME>"
__copyright__ = "Copyright 2017 <NAME>"
__license__ = "MIT"
# Wanted factor:
factor = str(sys.a... |
import os
import sys
import pathlib
import argparse
import subprocess
import aff3ct_help_reader as ahr
parser = argparse.ArgumentParser(prog='aff3ct-command-conversion', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--build', action='store', dest='buildPath', type=str, default="build/",... |
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'h... |
# ===============================================================================
# Copyright 2015 <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/LI... |
import random
import numpy as np
from API.WindFlo import simplified_gaussian_wake
from GA_Optimizer.WindForm_GA import Turbine
'''
WIP Module
Code for some PSO aspects were used from:
https://nathanrooy.github.io/posts/2016-08-17/simple-particle-swarm-optimization-with-python/
'''
class Particle: # a particle re... |
import scipy.signal
import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
import re
import math
from numpy.fft import fft, ifft, fft2, ifft2, fftshift
from scipy import optimize
class Spettro1D:
def __init__(self):
# list for wavelenght and flux values
self.wl =... |
from .baseline import *
class SIMPLE_LAYER(MessagePassing):
def __init__(self, feat_in, feat_out,spread=1,bias=False):
super(SIMPLE_LAYER, self).__init__(aggr='mean',flow='target_to_source')
self.L_flag = torch.zeros(1,1).cuda()
self.bias = bias
self.updater = Li... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
import argparse
import os
import pickle
import boto3
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, size, row_number, expr, array_join
from pyspark.sql.types import StructType, StructField, StringType, ArrayType
import pyspark.sql.functions as F
def list_s3_by_prefix(bucket, prefix, filt... |
import os
import sys
import urllib.request
import numpy as np
import pandas as pd
###############################################################################
class ConfigurationFile:
"""Manage common operation with configuration files.
For instance:
[parameters]
metric = mse, lp, mad
... |
# Improved MNIST Architecture based on implementation provided in Genetic CNN Notebook.
import random
import time
import numpy as np
from deap import base, creator, tools, algorithms
from scipy.stats import bernoulli
from dag import DAG, DAGValidationError
# 无法用tf_upgrade_v2直接转成到tensorflow2.0运行,tensorflow1.13.2运行成功
i... |
"""Test linear algebra module"""
import numpy as np
import scipy.sparse
import scipy.sparse.linalg
from qdyn.linalg import banded_to_full, norm, tril, triu
def test_norm():
"""Test calculation of norm for matrix in varying formats"""
A = np.diag([1, 1, 1, 1])
assert abs(norm(A) - 2.0) < 1e-12
assert ... |
import glob
import argparse
import statistics
import os
import time
import pickle
import copy
import numpy as np
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.dummy import DummyClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from metric_lea... |
from os import path
import logging
import collections
import json
import sys
from shapely.geometry import shape
import geojson
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib.patches import Circle, PathPatch
import mpl_toolkits.mplot3d.art3d as art3d
import numpy as np
from... |
import mrofinder_helpers as helpers
import warnings
class Proteome:
def __init__(self):
self.name = ''
self.proteins = {}
self.old2new_names_dict = {}
self.new2old_names_dict = {}
self.proteins_keys = []
# TODO dodac sprawdzanie co bylo zannotowane, zeby inteligentn... |
# -*- coding: utf-8 -*-
"""
Azure Resource Manager (ARM) Container Instance Group State Module
.. versionadded:: 3.0.0
.. versionchanged:: 4.0.0
:maintainer: <<EMAIL>>
:configuration: This module requires Azure Resource Manager credentials to be passed via acct. Note that the
authentication parameters are case s... |
import json
from collections import Counter
from pathlib import Path, WindowsPath
import yattag
from fontTools import unicodedata
from tptq.utils.shaping import Shaper
from data import Character
from data import Mongolian as Mong
from utils import slice_joining_form
NON_HUDUM_CODE_POINTS = "᠆᠈᠉ᡃᡄᡅᡆᡇᡈᡉᡊᡋᡌᡍᡎᡏᡐᡑᡒᡓᡔᡕᡖᡗᡘ... |
# AMZ-Driverless
# Copyright (c) 2018 Authors:
# - <NAME> <<EMAIL>>
#
# Permission == 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, ... |
from typing import Optional, Tuple, Iterable, Callable, Union
import itertools
import numpy as np
from overrides import overrides
from checklist.test_suite import TestSuite
from checklist.test_types import MFT
from checklist.perturb import Perturb
from allennlp.confidence_checks.task_checklists.task_suite import TaskSu... |
import io
from enum import Enum
from functools import lru_cache, singledispatch, wraps
from typing import Any, Iterator, Optional, Type, Union, get_type_hints
from .common import OrderedSet, S, Symbol, LITERAL_TYPES, LITERAL_TYPE_SIG
from .prettier import (
Doc,
QuoteContext,
assg_expr,
get_screen_widt... |
#!/usr/bin/env python3
import argparse
import sys
import os
from itertools import zip_longest
import tempfile
import definitions as defs
sys.path.insert(0, os.path.join(defs.BINARY_DIR_PREFIX, 'lib', 'netlist_paths'))
from py_netlist_paths import RunVerilator, Netlist, Waypoints, Options
DEFAULT_DOT_FILE = 'graph.do... |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Callable scope utility unit tests.**
This submodule unit tests the public API of the private
:mod:`beartype._util.utilfunc.utilf... |
###########################################################
# GE SRTP PLC Low level library
#
# Author: <NAME> - 2020
###########################################################
import os, sys
import re
import struct
import socket
from . import GE_SRTP_Messages
#######################################################... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 4.12
# In conjunction with Tcl version 8.6
# Apr 15, 2018 05:51:30 AM
import sys
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = False
except I... |
import logging
import numpy as np
import pandas as pd
import torch
from collections import Counter, defaultdict
from scipy.special import erfinv
from scipy.stats import rankdata
from ..custom_types import *
from ..utils import *
logger = logging.getLogger(__name__)
# utils
def _most_frequent(x: np.ndarray):
c =... |
import argparse
import time
from multiprocessing import cpu_count
from pprint import PrettyPrinter
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from tqdm import tqdm
import wandb
from datasets import PascalVOCDataset
from model import SSD300, MultiBoxLoss
from quant import cvt2quant... |
"""Collection of functions to apply effects to images."""
from typing import List, Tuple, Union
import cv2
import numpy as np
from PIL import Image
ColorScheme = List[Union[str, Tuple[int]]]
SIX_COLOR_RAINBOW = (
(0xFF, 0x00, 0x00),
(0xFF, 0xFF, 0x00),
(0x00, 0xFF, 0x00),
(0x00, 0xFF, 0xFF),
(0... |
# Copyright 2016-2020 Google LLC
#
# 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... |
# Copyright (c) 2012-2021 Arm Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functiona... |
import numpy as np
import matplotlib.pyplot as plt
from gen_forward_op_parser import gen_forward_op_parser
def check_bounds(pt, pt0, pt1):
"""Checks if the pt is within range of segment (pt0,pt1)"""
return np.logical_and(
np.logical_and(pt[:,0]>=min(pt0[0], pt1[0]), pt[:,0]<=max(pt0[0], pt1[0])),
... |
# -*- coding: utf-8 -*-
"""OpenCTI CrowdStrike indicator importer module."""
from datetime import datetime
from typing import Any, Dict, Generator, List, NamedTuple, Optional, Set
from crowdstrike_client.api.intel import Indicators, Reports
from crowdstrike_client.api.models import Indicator
from pycti.connector.ope... |
'''
This file contains classes and functions that implement the PyPXE TFTP service
'''
import socket
import struct
import os
import select
import time
import logging
import math
from pypxe import helpers
class ParentSocket(socket.socket):
'''Subclassed socket.socket to enable a link-back to the client object.''... |
#!/usr/bin/env python
# coding: utf-8
import sys
yamnet_base = './models/research/audioset/yamnet/'
sys.path.append(yamnet_base)
import os
assert os.path.exists(yamnet_base)
import time
import numpy as np
# audio stuff
import librosa
import soundfile as sf
import resampy
import pyaudio
# yamnet imports
import ... |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
from typing import Any, Dict, Tuple
import torch
from mmf.common.registry import registry
logger = logging.getLogger(__name__)
def is_pl_model_checkpoint(checkpoint):
return "state_dict" in checkpoint
def is_pl_trainer_checkpoint(checkpoint):... |
"""
File: io.py
BSD 3-Clause License
Copyright (c) 2020, AFD Group at UIUC
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 ... |
# Copyright 2021 Google LLC
#
# 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, ... |
from flask import current_app, url_for, g
from app import db, geolocator
from sqlalchemy import event
class Address(db.Model):
__tablename__ = 'address'
id = db.Column(db.Integer, primary_key=True)
line_1 = db.Column(db.String(255))
line_2 = db.Column(db.String(255))
line_3 = db.Column(db.String(25... |
# This script is based on https://github.com/CiscoSecurity/amp-04-sha256-to-network-connections/blob/master/sha256_to_network_connections.py
import sys
import requests
import configparser
import time
import gc
from urllib.parse import urlparse
# Ignore insecure cert warnings (enable only if working with onsite-amp dep... |
import re
import toolbox.database as db
import toolbox.print_result as pr
import copy
# Return capitalized name. Works for single names, names with a space, names with a `-`
def capitalize_name(name: str) -> str:
splitter = str()
result = str()
if '-' in name:
name = name.split('-')
split... |
"""Script to access News article via HTTP using News API https://newsapi.org.
This script access news article via HTTP using trawler_requests and retrieves
JSON response and store in a CSV File in Colossus. Multiple news sources
can be accessed which results in different CSV files being created.
"""
from __future__ i... |
import numpy as np
import random
from utils import *
class S():
s_newline_id : int = ord('\n')
s_vocab_size : int = 0
s_data : list = []
def clip(gradients: dict, maxValue: int) -> dict:
'''
Clips the gradients' values between minimum and maximum.
Arguments:
gradients -- a dictiona... |
from django.shortcuts import render, get_object_or_404,redirect
from django.contrib import messages
from django.http import Http404, HttpResponse
from django.db.models import Q
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Board, Topic, Post
from .forms im... |
try:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, LargeBinary, orm
import sqlalchemy as sql
except ImportError:
sql = None
from .memory import MemorySession, _SentFileType
from .. import utils
from ..crypto import AuthKey
from ..tl.types import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.