text stringlengths 3.07k 22.1k |
|---|
# -*- encoding: utf-8 -*-
#
# Copyright © 2014-2015 eNovance
#
# 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 applica... |
"""
tasks.py
This file holds all of the tasks that can be run.
2020 <NAME> and <NAME>
Santa Clara University
"""
# Standard library imports
from urllib.parse import urlparse
from hashlib import sha1
import logging
import json
from uuid import uuid4
from time import sleep
from datetime import datetime
# Local import... |
from . import lateral_net as network
from lib.utils.net_tools import *
from lib.models.image_transfer import *
from lib.core.config import cfg
import torch
import torch.nn.functional
class RelDepthModel(nn.Module):
def __init__(self):
super(RelDepthModel, self).__init__()
self.loss_name... |
import os
from typing import List, Tuple
import click
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
t_list = ['0.2', '0.3', '0.4', '0.5']
def visualize_shapenet_results(path_to_results: str, path_to_plots: str, files: List[str], train_data_name: str, substr_to_find: str):
dfs = []
... |
import inspect
class Empty(object):
def __repr__(self):
return 'Empty'
EMPTY = Empty()
class AnyType(object):
def __repr__(self):
return 'AnyType'
ANY_TYPE = AnyType()
class NoTypeSpecified(object):
def __repr__(self):
return 'NoTypeSpecified'
NO_TYPE_SPECIFIED = NoTypeSp... |
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
# This code is under the BSD 2-clause license
#
# Code inspired by https://github.com/abdesslem/CTF (Copyright (c) 2015 <NAME>)
#
from flask import Flask, render_template, redirect, url_for, flash, session, abort, request
from flask_security import Security
from flask_login impo... |
#!/usr/bin/python
import smbus
import os
import time
import math
twowire = smbus.SMBus(1)
cal0 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
cal1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
dig_T = [0,0,0,0,0,0,0,0,0]
dig_P = [0,0,0,0,0,0,0,0,0,0]
dig_H = [0,0,0,0,0,0,0,0,0]
raw_data = [0,0,0,0,0,0,0,0]
raw_value... |
# coding=utf-8
# Copyright 2021 TUNiB Inc.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE.apache-2.0 file in the root directory of this source tree.
import os
import struct
from itertools import accumulate
from typing import Union
impor... |
import os
import sys
import pickle
import re
import subprocess
from consensx import thirdparty
import consensx.graph as graph
from .measure import correlation, q_value, rmsd
shortcodes = {
"ALA": "A",
"ASP": "D",
"ASN": "N",
"ARG": "R",
"CYS": "C",
"GLY": "G",
"GLU": "E",
"GLN": "Q",
... |
import re
from os.path import abspath
from shutil import copytree, rmtree
from music_downloading import LastFM
from .case_non_sensitive_dict import CaseNonSensitiveDict
from functools import wraps
from itertools import chain, groupby
from pathlib import Path
from pickle import dump
from deflacue.deflacue import CuePars... |
from collections import defaultdict, namedtuple
from collections.abc import MutableMapping
import difflib
import itertools
import logging
import os
import re
import shlex
from subprocess import Popen, PIPE
log = logging.getLogger(__name__)
ShellTest = namedtuple('ShellTest', ('command', 'expected_output', 'source',... |
# face_recog.py
import face_recognition
import cv2
import camera
import os
import numpy as np
import argparse
from utils.anchor_generator import generate_anchors
from utils.anchor_decode import decode_bbox
from utils.nms import single_class_non_max_suppression
from PIL import Image, ImageDraw, ImageFont
# anchor con... |
"""
generate dataset
"""
import os
import json
import torch
import random
import numpy as np
from PIL import Image
from fuzzywuzzy import fuzz
from torch.utils.data import Dataset
from transformers import BertModel, BertTokenizer
import torchvision.transforms as transforms
def get_transforms():
return transforms.C... |
#!/usr/bin/env python
# encoding: utf-8
"""
data.py
Created by <NAME> on 2012-03-26.
Copyright (c) 2012 Moonbot Studios. All rights reserved.
"""
from audio import AudioRecording
import copy
import logging
import os
LOG = logging.getLogger('storyTime.data')
FPS_OPTIONS = {
24:'Film (24 fps)',
25:'PAL (25 f... |
import xmltodict
import logging
from typing import List, Dict
from dataclasses import dataclass, field
from .models import OperatingSystem
from .models import HostMachine
logger = logging.getLogger(__name__)
@dataclass
class KvmXmlCore():
memory: int
cpu_count: int
efi_boot: bool = False
chipset:... |
# -*- coding=UTF-8 -*-
#import numpy as np
import pickle, code, re, collections,sys
from stanfordcorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP(r'path_to/stanford-corenlp-full-2018-10-05/', lang='zh')
import random
import csv
ctx_num = int(sys.argv[2])
def replace_abbreviations(text):
new_text = text
new_... |
__author__ = 'JoeJoe'
import proto.Block_pb2 as Block_pb2
import proto.Map_pb2 as Map_pb2
import proto.Material_pb2 as Material_pb2
import proto.Plant_pb2 as Plant_pb2
import proto.Tile_pb2 as Tile_pb2
from Tile import Tile
from Terrain import TerrainType
from Terrain import Terrain
import zlib
import bpy
import bmesh... |
import threading
from typing import TYPE_CHECKING
import oslo_db
import sqlalchemy as sa
from oslo_db import api as oslo_db_api
from oslo_db import exception as db_exc
from oslo_db.sqlalchemy import enginefacade
from oslo_db.sqlalchemy import utils as db_utils
from oslo_log import log
from oslo_utils import uuidutils
... |
import os
import re
from collections import defaultdict
import numpy as np
from .rules import *
def generate_guards(templates, temp_fname, guard_fname="gen_guards.txt"):
guards = defaultdict(list)
temp_fname = os.path.splitext(os.path.basename(temp_fname))[0]
negate = False
for i, temp in enumerate(... |
import secrets
from pathlib import Path
from bs4 import BeautifulSoup
from django.template.context import make_context
from django.template.exceptions import TemplateDoesNotExist
from template_engines import settings as app_settings
from template_engines.utils import get_content_url, get_extension_picture, modify_con... |
from itertools import combinations
import pickle
import os
### KENN CONSTRAINTS ###
# mode in ['bottom_up','top_down','hybrid','hybrid_in','hybrid_out','bottom_up_skip', 'top_down_skip']
def generate_constraints(tree, mode, filepath = None, weight='_'):
# generate predicate list
predicates = generate_predicate... |
import ctypes
import os
import re
import struct
import sys
from keystone import Ks, KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN
PATCH_DIR = "patches"
PATCH_EXTENSION = ".slpatch"
NSO_HEADER_LEN = 0x100
IPS_OUT_DIR_NAME = "ips_patches"
IPS_FORMAT = ".ips"
IPS_HEADER_MAGIC = b"IPS32"
IPS_EOF_MAGIC = b"EEOF"
# globals
sl_ma... |
import ila
import riscv_csr as CSR
XLEN = 32
class Encoding:
OPIMM = 0x13
LUI = 0x37
AUIPC = 0x17
OP = 0x33
BRANCH = 0x63
JAL = 0x6f; JALR = 0x67
LOAD = 0x03;
STORE = 0x23;
SYSTEM = 0b1110011
#funct3 for OPIMM
ADDI = 0x0
SLTI = 0x2
SLTIU = 0x3
ANDI = 0x... |
import asyncio
import collections
import re
from pychess.System.Log import log
from pychess.ic import BLOCK_START, BLOCK_SEPARATOR, BLOCK_END, BLKCMD_PASSWORD
from pychess.ic.icc import UNIT_START, UNIT_END, DTGR_START, MY_ICC_PREFIX
class ConsoleHandler:
def __init__(self, callback):
self.callback = cal... |
# -*- coding:utf-8 -*-
import json
import os
import numpy as np
from tensorflow import TensorShape
from tensorflow.keras import Input, Model, Sequential
from tensorflow.keras import backend as K
from tensorflow.keras import constraints, initializers, regularizers
from tensorflow.keras.callbacks import EarlyStopping,... |
import numpy as np
from enum import Enum
import copy
import math
from ner_lib.command_builder import SpatialType
from database_handler.database_handler import DatabaseHandler
class StatusEnum(Enum):
SUCCESS = "SUCCESS"
NO_VALID_OBJECTS = "ERROR_TWO_REF"
ERROR_CANT_FIND = "ERROR_CANT_FIND"
ERROR_CANT_F... |
import re
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.colorchooser import askcolor
from Components.db import Database
from Operations.operation import Operation
from Components.patter_menu import PatternMenu
from Components.status_bar import StatusBar
from Components.custom_text import CustomText
cla... |
"""
Tests for :mod:`otter.log.intents`
"""
from effect import (
ComposedDispatcher,
Constant,
Effect,
base_dispatcher,
raise_,
sync_perform)
from effect.testing import perform_sequence
import mock
from twisted.internet.task import Clock
from twisted.trial.unittest import SynchronousTestCase
... |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... |
import numpy as np
import pandas as pd
import re
import os, sys
import string
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
from tweepy import Cursor
from datetime import datetime, date, time, timedelta
import sys
import nltk... |
import itertools
def Sieve_127():#18407904
SIEVE_RANGE=120000
sieve_visited=[0]*SIEVE_RANGE
rad=[1]*SIEVE_RANGE
sieve_visited[0]=True
sieve_visited[1]=True
for i in range(2,SIEVE_RANGE):
if not sieve_visited[i]:
rad[i]=rad[i]*i
for j in range(i+i,SIEVE_R... |
#!/usr/bin/env python
# Copyright 2016 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
"""Collection of tests focused on the `detect` module."""
from collections import namedtuple
from unittest.mock import Mock
import math
import sys
import dlib
import numpy as np
import pytest
import pychubby.detect
from pychubby.detect import LANDMARK_NAMES, LandmarkFace, LandmarkFaces, face_rectangle, landmarks_68
... |
#!/usr/bin/env python
# ===============================================================================
# Copyright (c) 2014 Geoscience Australia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... |
import numpy as np
import mne
from mne.channels import read_montage
from joblib import Memory
mem = Memory(cachedir='cachedir')
def scorer(evoked_gt, epochs_test, good_epochs_idx=None):
""" Returns the error percentage. """
import numpy as np
if good_epochs_idx is None:
evoked_test = epochs_tes... |
'''
Collection of functions that are quite far from headerutil.
'''
from warnings import warn
import numpy as np
from astropy import units as u
from astropy.io import fits
from astropy.nddata import CCDData, Cutout2D, StdDevUncertainty
from astropy.wcs import WCS
from .misc import binning
__all__ = ["cutccd", "bin_c... |
#!/usr/bin/python3
import sqlite3
import datetime
import argparse
import ast
import otx
import botvrij
import plain
sources = { # plain text sources, one IP per line
"Cisco Talos Bad IP List":"https://talosintelligence.com/documents/ip-blacklist",
"AlienVault IP Reputation":"https://reputation.alienvault.com/rep... |
# A python implementation of Ailey's matlab tensor code.
import os
import numpy as np
import math
import SimpleITK as sitk
from scipy import ndimage
import nibabel as nib
from PIL import Image
import scipy.misc
from scipy import signal
import warnings
warnings.filterwarnings("ignore")
def doggen(sigma):
"""
... |
#!/usr/bin/env python
import fitbit
import configparser
import datetime
import os
import time
import json
from fitbit.exceptions import HTTPTooManyRequests
from fitbit.exceptions import HTTPUnauthorized
import argparse
import sys
DUMP_DIR = 'data'
def mkdate(datestr):
try:
fulltime = time.strptime(datest... |
import bpy
import math
import random
import json
import datetime
import sys
import re
import subprocess
import os
def x_of_sticker(net_id):
face_id = net_id // 9
face_local_id = net_id % 9
lx = face_local_id % 3
ly = face_local_id // 3
x, y, z = [
(lx, 2, ly),
(0, 2-ly, lx),
... |
# Adapted from https://github.com/huggingface/transformers/blob/v2.3.0/transformers/data/processors/glue.py
#
# Additional license and copyright information for this source code are available at:
# https://github.com/huggingface/transformers/blob/master/LICENSE
""" FEVER processors and helpers """
import csv
import lo... |
from esper.prelude import *
from rekall.interval_list import IntervalList, Interval
from rekall.logical_predicates import not_pred, or_pred
from rekall.temporal_predicates import overlaps, equal, before, after
import pysrt
"""
All thresholds
"""
TRANSCRIPT_DELAY = 6
MIN_TRANSCRIPT = 0.3
MIN_BLACKFRAME = 0.99
MIN_BLA... |
#!/usr/bin/python3
__author__ = '<NAME>'
__copyright__ = 'Copyright © 2019, <NAME>'
__license__ = 'MIT'
import pandas as pd
import os
import os.path
import xlrd # Used to handle inproperly formatted .xls(x) files
from pyfiglet import Figlet
# More font styles @ https://github.com/pwaller/pyfiglet/tree/master/pyfiglet... |
import numpy as np
import pytest
from numba import njit
import respy as rp
from respy._numba import array_to_tuple
from respy.config import EXAMPLE_MODELS
from respy.config import KEANE_WOLPIN_1994_MODELS
from respy.config import KEANE_WOLPIN_1997_MODELS
from respy.pre_processing.model_checking import check_model_solu... |
"""This module simulates trajectories of interacting particles in 3D space.\n
Particles are called "Walkers", in reference to the fact at each iteration each
particle is "walking" towards or away from others. Various mathematical
interaction laws and relationship generation rules are provided, yielding very
different s... |
from typing import List, Union
import os
import logging
import re
import shutil
import collections
from tensorflow.keras.models import Model as KerasModel
from tensorflow.keras.models import load_model as load_keras_model
from mltk import __version__ as mltk_version_str
from mltk import MLTK_ROOT_DIR
from mltk impor... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
try:
import unzip_requirements
except ImportError:
pass
import asyncio
from asyncio.subprocess import PIPE
from asyncio import create_subprocess_exec
import json, os, sys, subprocess
from time import monotonic
from functools import wraps
from tempfile import mkdtemp
from azure.storage.blob import BlobServiceCli... |
# Don't absolutely need gevent here, but the web application uses gevent, and
# the Python coverage package doesn't support both threads and gevent
from gevent import (
monkey,
)
monkey.patch_all()
import ecs_logging
from base64 import (
b64encode,
)
import csv
from functools import (
partial,
)
import it... |
import os
from os import path
import tempfile
import apache_beam as beam
from apache_beam.testing import test_pipeline
from apache_beam.testing import util
import tensorflow as tf
import tensorflow_gnn as tfgnn
from tensorflow_gnn.data import unigraph
from tensorflow_gnn.utils import test_utils
class TestUnigraph(tf... |
import base64
import json
import logging
import math
from argparse import ArgumentParser
from copy import deepcopy
from geoalchemy2 import shape
from shapely import wkt, geometry
from shapely.ops import linemerge
from sqlalchemy import create_engine, and_
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool im... |
import sys
import time
import serial
import requests
from datetime import datetime
from configparser import ConfigParser
serRead = ""
response = ""
timer = None
backupFileName = ""
hostname = ""
sessionId = ""
config = ConfigParser()
try:
config.read("config.ini")
serPort = config.get("Serial", "Port")
de... |
import torch
from torch import nn
from torch.nn import functional as F
class TorchSTFT(nn.Module):
def __init__(self, n_fft, hop_length, win_length, window='hann_window'):
""" Torch based STFT operation """
super(TorchSTFT, self).__init__()
self.n_fft = n_fft
self.hop_length = hop... |
# -*- coding: utf-8 -*-
# ToMaTo (Topology management software)
# Copyright (C) 2012 Integrated Communication Systems Lab, University of Kaiserslautern
#
# This file is part of the ToMaTo project
#
# ToMaTo is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... |
import tensorflow as tf
import numpy as np
def leaky_relu(x, alpha=0.01):
return tf.maximum(alpha * x, x)
def create_cell(dim, n_layers, dropout):
"""
Creates a GRU cell RNN with dropout and stacks it into a multilayer RNN if more than 1 layers are required
:param dim: dimension of the input state
... |
# set up environment
# define command line parameters
# define location of input data
# create output directories
# start the class FeatureCorrelations
import argparse
import os
#import matplotlib
#matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import csv
import pathlib
import numpy... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 22 10:45:42 2019
@author: bieZY (<EMAIL>)
Method: velocityWise, displacementWise
Modules: numpy, imageio, medImgProc, motionSegmentation
History:
Date Programmer SAR# - Description
---------- ---------- ----------------------------
Author: <EMAIL> 15... |
#!/usr/bin/env python3.7
import argparse
from collections import defaultdict
import copy
import itertools
import json
import re
import subprocess
import sys
import xml.etree.ElementTree as ET
ALTO_STRING = "{http://www.loc.gov/standards/alto/ns-v3#}String"
ALTO_SPACE = "{http://www.loc.gov/standards/alto/ns-v3#}SP"
... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
"""
import pytest
import os
import json
import cli.nuttercli as nuttercli
from cli.nuttercli import NutterCLI
from common.apiclientresults import ExecuteNotebookResult
import mock
from common.testresult import TestResults, TestResult
from cli.rep... |
def detect_number(line, rigorous=False):
'''
Takes an array of words and returns the indices of numbers.
If rigorous True, words that include numbers will be divided. Ex. abc20xyz --> abc, 20, xyz
Returns the new line and indices of numbers
'''
indices = []
new_line = []
offset = 0
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 11:13:59 2019
@author: george
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
from pathlib import Path
from pandas.plotting import parallel_coordinates
from sklearn.preprocess... |
""" Prepare AAOmega data for The Cannon """
import glob
import numpy as np
from astropy.table import Table
from astropy import stats
import pyfits
DATA_DIR = "/Users/annaho/Data/AAOmega/Run_13_July"
def weighted_std(values, weights):
""" Calculate standard deviation weighted by errors """
average = np.avera... |
from imports import *
from vision import vision_api
from preprocess import pad_img, detect_horizontal_line, correct_line
def ext_ocr_details(img):
# ------ connected components ---- ###
edge_image = cv2.Canny(img, 50, 150)
cv_img_bkp = np.copy(img)
kernel = np.ones((2, 7), np.uint8) # <-- Optimizer
img_dilation... |
import varint
from . import exceptions
from .codecs import codec_by_name
__all__ = ("Protocol", "PROTOCOLS", "REGISTRY")
# source of protocols https://github.com/multiformats/multicodec/blob/master/table.csv#L382
# replicating table here to:
# 1. avoid parsing the csv
# 2. ensuring errors in the csv don't screw up ... |
# -- coding: utf-8 --
# MIT License
#
# Copyright (c) 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... |
from random import shuffle, seed as random_seed, randrange
import sys
class _SudokuSolver:
def __init__(self, sudoku):
self.width = sudoku.width
self.height = sudoku.height
self.size = sudoku.size
self.sudoku = sudoku
def _solve(self):
blanks = self.__get_blanks()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# makeEDTFDates
import csv
import re
import requests
import shutil
from tempfile import NamedTemporaryFile
_FILES = [
"letters"
]
_ONLYADD = False
def getISODate(datestring):
''' Try to detect/transform date strings to ISO dates using pdr webservice
Dat... |
from abc import ABC
from tensorflow.python.keras.layers import *
from transformers import add_start_docstrings
from transformers.file_utils import add_start_docstrings_to_callable
from transformers.modeling_tf_bert import BERT_START_DOCSTRING, TFBertPreTrainedModel, BERT_INPUTS_DOCSTRING, \
TFBertMainLayer
from tr... |
from asyncio import TimeoutError, iscoroutine, wait_for
from functools import partial
from logging import DEBUG
from operator import contains
from typing import List, Optional
from pytest import fixture, mark
from sanic import Sanic
from sanic.websocket import WebSocketProtocol
from ujson import dumps, loads
from san... |
import sys
from collections import defaultdict, OrderedDict
from importlib import import_module
import argparse
import joblib
import numpy as np
import pickle, h5py
from contrib.rnn.util import get_base_env
def _copy_mujoco_state(env):
m = env.model.data
d = OrderedDict()
d['time'] = m.time
d['qpos'] ... |
#******************************************Rolling Funcs ******************************************
import numpy as np
def exp_2_avg(x):
x = x[::-1]
weights = np.array([2**(len(x) - 1 - y) /(2**(len(x))-1) for y in range(len(x))])
average = np.dot(np.array(x),weights)
return average
def exp_e_avg(x): ... |
#################################################################################
#### Package
#################################################################################
import datetime
import time
import sys
####
from tensorflow import keras
from keras.utils import np_utils
from keras.models import Sequentia... |
# By: <NAME> (TQ Tezos)
# Released under BSD 3-clause license
# Type checked with Pyright (non-strict due to missing type stubs from aiohttp and graphviz)
# Formatted with Black
from __future__ import annotations
import argparse
import asyncio
import itertools
from pathlib import Path
from typing import (
Any,
... |
# Course: Course ID
# Name: XXXXXXXX
# Student number: 0000000
# File: SmallTrain.py
# This program creates a graphical window, displays a message. After a click,
# a tractor-trailer emerges from behind the right edge of the window and moves
# from right to left. As it moves, it slowly gets smaller. It will dis... |
# Copyright (c) 2021 PaddlePaddle Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# Copyright (c) 2018, <NAME>. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 940... |
import re
from pathlib import Path
from typing import Union
KJ_TO_KCAL = 4.184
RE_EDA_FRAGMENT_ENERGY = re.compile(r"\d{1,}\s*(-\d{1,}\.\d{10})")
DASHES = "--------------------"
re_number_basic_eda_quantities = re.compile(r"=\s(-?\d+\.\d+)")
re_number_str = r"(-?[0-9]*\.[0-9]*)"
re_number = re.compile(re_number_str)
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2020 Mag. <NAME>. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.c-tanzer.at/license/b... |
#!/usr/bin/env python3
"""
* python_mkeros1_node
*
* Copyright (c) 2020-2021, Magik-Eye Inc.
* author: <NAME>, <EMAIL>
"""
# ============================================================================
# ROS
import rospy
from sensor_msgs.msg import PointCloud2, PointField
from std_srvs.srv import Trigger, TriggerResp... |
from flask import Flask, render_template, redirect, request
from binascii import hexlify, unhexlify
from markdown2 import markdown
from glob import glob
from binascii import hexlify, unhexlify
societies = {
"res": "Research Society",
"spo": "Sports Society",
"lit": "Literary Society",
"tec": "Techni... |
""" Tests for package storage backends """
import time
from cStringIO import StringIO
from datetime import datetime
import shutil
import tempfile
from mock import MagicMock, patch
from moto import mock_s3
from urlparse import urlparse, parse_qs
import boto
import os
import pypicloud
import re
from boto.s3.key import ... |
import os.path, sys
from modules.windows_jumplist.consts import *
from ctypes import *
from modules.windows_jumplist.lib.delphi import *
from modules.windows_jumplist.lib.yjSysUtils import *
from modules.windows_jumplist.lib.yjDateTime import *
from modules.windows_jumplist.LNKFileParser import TLNKFileParser
from mod... |
""" Get the list of fields selected with a GraphQL query """
import graphql
from collections import abc
from typing import Union, Any, Optional
# TODO: when this solution is tested & published, post a link here:
# https://github.com/graphql-python/graphene/issues/57
# TODO: in most cases, `runtime_type` can be ... |
'''
Copyright 2020 Xilinx Inc.
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... |
import os
import os.path
import sys
from sys import platform
import numpy as np
from sklearn.utils.validation import check_array
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.metrics.cluster import normalized_mutual_info_score
from sklearn.metrics.cluster import adjusted_mutual_info_sco... |
from django.contrib.gis.db import models
import projects.models
from .ontologies import LAETOLI_AREAS, LAETOLI_UNITS
class TaxonRank(projects.models.TaxonRank):
class Meta:
verbose_name = "Laetoli Taxon Rank"
verbose_name_plural = "Laetoli Taxon Ranks"
class Taxon(projects.models.Taxon):
par... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# file tests/test_nearly_equal.py
#
#############################################################################
# Copyright (c) 2014 by <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted pro... |
import asyncio
import os
import aiohttp
from prometheus_client import (
CollectorRegistry,
generate_latest,
)
from .app_outgoing_elasticsearch import (
ESMetricsUnavailable,
es_bulk_ingest,
es_feed_activities_total,
es_searchable_total,
es_nonsearchable_total,
create_activities_index,
... |
import numpy as np
import torch
import ubelt as ub
def bboxes_iou_light(boxes1, boxes2):
import itertools as it
results = []
for box1, box2 in it.product(boxes1, boxes2):
result = bbox_iou_light(box1, box2)
results.append(result)
return results
def bbox_iou_light(box1, box2):
"""... |
import tqdm
import datetime
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
import tensorflow as tf
from skimage import io
from model.transformer import Transformer
from model.utils import create_target_masks
from tokenizers import ByteLevelBPETokenizer
@st.cache(allow_output_mutation=True... |
import numpy as np
import os
import json
import h5py
from tqdm import tqdm
from torchmeta.utils.data import Dataset, ClassDataset, CombinationMetaDataset
from torchmeta.datasets.utils import get_asset
class Letter(CombinationMetaDataset):
"""The Letter Image Recognition Dataset """
def __init__(self, root, n... |
# Created byMartin.cz
# Copyright (c) <NAME>. All rights reserved.
import sys
import os.path
from PIL import ImageFont
from .. enums import *
class FontManager(object):
"""
Font manager holds information about all supported fonts currently
available. This is mainly used to speed up text size calculatio... |
# -*- coding: utf-8 -*-
# @Date : 2021/4/14
# @Author : mingming.xu
# @Email : <EMAIL>
# @File : classification_tnews_rezero_pretrain_fintuning.py
"""
环境:tf1.X + tf.keras
"""
import os
os.environ['TF_KERAS'] = '1' # 必须使用tf.keras
import json
from tqdm import tqdm
import numpy as np
import jieba
from toolki... |
from logging import getLogger
from os.path import join, dirname
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from typing import Dict, List, Tuple, Optional
from asfault.tests import RoadTest
from lxml.etree import _Element
ENV_SIZE: float = 100
TEMPLATE_PATH = join(dirname(__file__), "..... |
import sys
assert sys.version_info >= (3, 5)
import sklearn
assert sklearn.__version__ >= "0.20"
import numpy as np
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from m... |
import subprocess
import time
import sys
import json
from datetime import datetime
import requests
# Set to either client or server
from nr_wg_mtu_finder.sync_server import run_sync_server
from nr_wg_mtu_finder.plot import plot_log
class ReturncodeError(Exception):
pass
class MTUFinder(object):
def __init_... |
# Copyright 2021 <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,... |
import torch
import torch.nn as nn
import collections
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
from ..utils import getOperation
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9... |
import torch
import torch.nn as nn
from torch.distributions import Categorical
import torch.nn.functional as F
from statistics import mean, stdev
import time
import pandas as pd
import numpy as np
def pretrain(params, net, optimizer, env, state_net, optimizer_state):
df = pd.DataFrame(columns = ["time", "reward_me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.