text stringlengths 3.07k 22.1k |
|---|
from __future__ import division, print_function
import os, sys
import ROOT
from PhysicsTools.NanoAODTools.postprocessing.framework.postprocessor import PostProcessor
from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection, Object
from PhysicsTools.NanoAODTools.postprocessing.framework.event... |
from __future__ import division
import logging
import sys
import os
import math
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import xml.etree.ElementTree as ET
from collections import OrderedDict
import numpy as NP
from scipy.constants import mu_0
from scipy.io import savemat
from scipy.interpol... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/11/25 上午11:11
# @Author : zkw
# @File : BarPlotMaker.py
import functools
from bokeh.plotting import Figure, figure
from data.Event import Event
from plot.BaseMaker import BaseMaker
from plot.PlotInfo import PlotInfo
from utils.ColorUtils import get_... |
# 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... |
from urllib.request import urlretrieve
import numpy as np
import random
import os
import gzip
# A function to load the MNIST data
def download(filename, source='http://yann.lecun.com/exdb/mnist/'):
print("Downloading %s" % filename)
urlretrieve(source + filename, filename)
# We then define functions for... |
"""Application support library for using information exported by nameq."""
from __future__ import absolute_import
__all__ = [
"DEFAULT_STATEDIR",
"Feature",
"FeatureMonitor",
"log",
"remove_feature",
"set_feature",
]
import errno
import fcntl
import json
import logging
import os
import select... |
"""Functions for working with reflection coefficients."""
from __future__ import annotations
import numpy as np
from edges_io import io
from typing import List, Tuple, Union
from . import types as tp
def impedance2gamma(
z: float | np.ndarray,
z0: float | np.ndarray,
) -> float | np.ndarray:
"""Convert ... |
import numpy as np
from scipy.stats import t
def outliers_iqr(x, ret='filtered', coef = 1.5):
"""
Simple detection of potential outliers based on interquartile range (IQR).
Data that lie within the lower and upper limits are considered
non-outliers. The lower limit is the number that lies 1.5 IQRs be... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: confio/proofs.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import List
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
class HashOp(betterproto.Enum):
# NO_HASH is the default if n... |
# This Python file uses the following encoding: utf-8
import sys
from pathlib import Path
from PySide6.QtCore import QObject, Slot, Signal
from PySide6.QtGui import QGuiApplication, QImage
from PySide6.QtQml import QQmlApplicationEngine, QmlElement
import depthai as dai
# To be used on the @QmlElement decorator
# (QML... |
from collections import OrderedDict
from ftplib import FTP
from pathlib import Path
from typing import List
import nmm
from Bio import Entrez, SeqIO
from Bio.Data import IUPACData
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from deprecated import deprecated
from iseq.codon_table import CodonTable
from ... |
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple, Callable, List
from alliance import get_alliance_color
from cargo import Cargo
from math import sqrt
from random import random
from field import Hub
if TYPE_CHECKING:
from field import Field
from alliance import Alliance
from graphi... |
from contextlib import ExitStack
import json
from unittest.mock import patch
from django.apps import apps
from django.test import SimpleTestCase, TestCase
from gcp_pilot.exceptions import DeletedRecently
from gcp_pilot.mocker import patch_auth
from django_cloud_tasks import exceptions
from django_cloud_tasks.tests imp... |
# std
import copy
import unittest
import shutil
import tempfile
import pathlib
# 3rd
import pandas as pd
# ours
from ankipandas.raw import (
load_db,
get_db_version,
close_db,
get_deck_info,
get_did2deck,
get_model_info,
get_mid2model,
set_table,
set_info,
get_info,
get_tab... |
import argparse
import logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=logging.INFO,
)
logger = logging.getLogger("Main")
import torch
import numpy as np
import random
from modeling import BertClassifier
from transformers impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 13:51:51 2018
@author: ivar
"""
import os
from execute import run_shell_command
# Splitting NIFTI files along time axis and moving to destination for correction
def extract_first_temporary_window_and_save(output_directory, \
... |
import os
import numpy as np
import pandas as pd
import plotly.express as px
from .app_dashboard_functions import discrete_background_color_bins
from ..utils.pickle import open_dic
from .styles_dash import color_mapping
Column_Storage = [
"Equipe",
"Joueur",
"Tour",
"Fleche numero",
"Valeur",
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 mjirik <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""
"""
import numpy as np
from loguru import logger
# logger = logging.getLogger()
import argparse
from scipy import ndimage
from . import qmisc
class ShapeModel():... |
#import pygtk
#pygtk.require('2.0')
import gtk, socket, select, thread, sys, helper, pango, gobject
from random import random
#gtk.gdk.threads_init()
gobject.threads_init()
def broadcast_data (sock, message):
for socket in CONNECTION_LIST:
if socket != server and socket != sock :
try:
socket.send(message)
... |
#
# Valuation of European Call Options in BSM Model
# Comparison of Analytical, int_valueegral and FFT Approach
# 11_cal/BSM_option_valuation_FOU.py
#
# (c) Dr. <NAME>
# Derivatives Analytics with Python
#
import numpy as np
from numpy.fft import fft
from scipy.integrate import quad
from scipy import stats
import matpl... |
from pandashacks import *
import pandas as pd
import numpy as np
from pymssa2 import MSSA
from multiprocessing import Pool
from numpy.random import randint
from sklearn.metrics import r2_score
def doforecast(df, cols, howmany, start=None, end=None, winsize=None, indices=None):
newdf = df[cols]
if start is None... |
#<NAME>
#Dags. 21/2/2019
import random
#Def
#1:
def prentaTuple(tup):
for x in tup:#Fer í gegnum tuple
print(x, end=" ")#og prentar innihaldið(x) með bili á milli
def paraRod(tup1, tup2):
for x in range(len(tup1)):#Keyrir í gegnum tuple eins og oft og len af því er
print(tup1[x],"og",tup2[x]) #P... |
import matplotlib.pyplot as plt
import numpy as np
import torch
import cv2
import PIL.Image
import skimage.io
import skimage.color
from typing import Union, Dict
def show_box_pred_simple(image, boxes):
c = ['nul','r','b','y','w']
# x1, y1, x2, y2
plt.imshow(image)
plt.tight_layout()
for i, b... |
import os
from dwave.cloud import Client
from dwave.system.samplers import DWaveSampler
from dimod import SimulatedAnnealingSampler
import neal
import dimod
import networkx as nx
import dwave_networkx as dnx
from dwave.system.composites import FixedEmbeddingComposite, LazyFixedEmbeddingComposite
import matplotlib.pyplo... |
#
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
#
import sys
import time
import os
import math
import csv
import argparse
import numpy as np
import logging
from models import *
from distributed_ferplus import *
... |
'''
Board class for the game of Quatro.
Default board size is 4x4.
Board data:
16 pieces = 10000,10001,10010,10011,10100,10101,10110,10111,11000,11001,11010,11011,11100,11101,11110,11111
0=empty
the format is binary
color(black/white) ,height(tall/short), shape(round/square), surface(holed/smooth)
first dim i... |
import torch
import shapely.geometry as s_geo
import shapely.ops as s_ops
from ..domain import Domain, BoundaryDomain
from .parallelogram import Parallelogram
from ...spaces import Points
class ShapelyPolygon(Domain):
"""Class for polygons. Uses the shapely-package.
Parameters
----------
space : Spac... |
import json
from tkinter import *
import numpy as np
import time
import math
from random import randint
import random
from cell import Cell
from food import Food
class SimulationConfig:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def generate_blob_coordinate(config, r):
'''
Generat... |
import random
import math
import numpy as np
from craam import crobust
import Utils
### Construct uncertainty set
def compute_bayesian_threshold(points, nominal_point, confidence_level):
"""
Computes an empirical thresholds from samples from a posterior distriL1 threshold'bution
Must adjust the confidence... |
import torch
import torch.nn as nn
import torch.nn.functional as F
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class GaussianEncoder(nn.Module):
"""Gaussian encoder module for VAE"""
def __init__(self, latent_dim, dataset):
"""
Constructor for the GaussianEncoder cl... |
# Copyright 2018 Elasticsearch BV
# Copyright 2020, 2021 Curtin University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
"""
Copyright (c) 2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
'''
Read and parse commandline arguments
'''
import argparse
import os
import re
import socket
import sys
from sshpubkeys import SSHKey, InvalidKeyError
from typing import Optional, List
from urllib.request import urlopen
from lansync.settings import SECURE_OPTIONS, AUTHORIZED_KEYS_PATH
def log(msg, level=0) -> None:... |
import math
from dataclasses import dataclass
from typing import Any, List, Optional, Tuple
import cairo
import PIL
from io import BytesIO
import cairosvg
from chalk.bounding_box import BoundingBox
from chalk.point import Point, Vector, ORIGIN
from chalk import transform as tx
import xml.etree.ElementTree as ET
from... |
"Methods for scraping comic book covers and metadata from htpps://www.comics.org"
import datetime
import random
import re
import urllib.request
from contextlib import closing
from functools import reduce
from os import path
from re import search
from time import sleep
from typing import List, Optional, Union
import j... |
# -*- coding: utf-8 -*-
""" Module summary description.
More detailed description.
"""
import math
import os
import pyproj
import numpy as np
import warnings
import geopandas as gpd
from cpc.geogrids import Geogrid
from osgeo import gdal
from rtree import index
from gistools.projections import crs_from_raster
fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : 陈坤泽
# @Email : <EMAIL>
# @Date : 2020/05/30 21:14
"""
百度人工智能API接口
"""
from pyxllib.prog.pupil import check_install_package
check_install_package('aip', 'baidu-aip')
import aip
import base64
import cv2
from pyxllib.prog.pupil import is_url
from pyxllib.p... |
from django.contrib import admin
from django.db.models import TextField, ForeignKey
from django.forms.widgets import TextInput
from django_select2.forms import Select2Widget
from .models import Monster, Skill, SkillEffectDetail, MonsterCraftCost, Dungeon, Level, MonsterGuide, \
HomunculusSkillCraftCost, Homunculus... |
"""Provides a mechanism for NFA state machine construction and visualizing.
State is a circle with a number as name.
Path is a line links two states with direction, from start point to end point
via a label, which means the input letter.
Graph contains States and Path, which forms the state map. It transfers the map... |
"""
Utility functions to convert time in/to various formats and track execution time
of a code.
"""
import datetime
import time
from typing import Any, Callable, TypeVar
import dlpt
# FORMATTERS:
# datetime:
# https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-behavior
# time:
# https://docs.... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import numpy as np
import os
import torch
from PIL import Image
from data.augmentations import *
from data.base_dataset import BaseDataset
from data.randaugment import RandAugmentMC
def recursive_glob(rootdir=".", suffix=""):
"""Performs r... |
from datetime import datetime as dt
import aiogoogletrans
import aiowiki
import async_cse
import discord
from discord.ext import commands, flags
from CyberTron5000.utils import paginator, cyberformat, converter, lists
# ≫
def fetch_rtfs(res):
items = []
for item in res:
item.pop("module")
i... |
import random
import math
print(f"-----===== Start =====-----\n")
# Problem 1.
# A crack team of love scientists from JeUp (a hot new dating site) have devised a way to represent dating profiles as rectangles on a two-dimensional plane.
# They need help writing an algorithm to find the intersection of two users' love... |
import os
import torch
import torch.nn as nn
import types
from typing import Optional
import jax
import jax.numpy as jnp
import haiku as hk
import numpy as np
from icecream import ic
ic.configureOutput(includeContext=True)
from scale_attention import ScaledAttention
from multihead_attention import S... |
"""
Utilities for the hera-py system.
Author: <NAME> (<EMAIL>)
Version: February 2019
"""
import sys
from .data import HERAError, Location, Messages, Settings, Token
def to_u16(n: int) -> int:
"""
Reinterpret the signed integer `n` as a 16-bit unsigned integer.
If `n` is too large for 16 bits, a HERAE... |
"""Functions to read the spatial relations dataset.
(http://spatialrelations.cs.uni-freiburg.de/#dataset).
Author: <NAME>, 2018
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import random
import SpatialRelationCNN.data_io.data_loaders as l... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from enzynet.PDB import PDB_backbone
from enzynet.volume import adjust_size, coords_to_volume, coords_center_to_zero, weights_to_volume
import argparse
import pandas as pd
import rdkit
import rdkit.Chem
import rdkit.... |
from datetime import datetime, timedelta
from .. import db
def asdict(obj):
"""
Creates a dictionary representation from an object
"""
if hasattr(obj, '__jdict__'):
return obj.__jdict__()
elif (not type(obj) is dict) and hasattr(obj, '__iter__'):
return [asdict(o) for o in obj]
... |
import re
import numpy as np
import pandas.compat as compat
import pandas as pd
from pandas.compat import u
from pandas.core.base import FrozenList, FrozenNDArray
from pandas.util.testing import assertRaisesRegexp, assert_isinstance
from pandas import Series, Index, DatetimeIndex, PeriodIndex
from pandas import _np_ver... |
"""
This is essentially wrapper arround HiYaPyCo project with streamlined and extended API and couple of work-arrounds.
This module depends on some 3-rd party dependencies, in order to use it, you should have installed first. To do it
run `python3 -m pip install alex-ber-utils[yml]`.
This module doesn't use any packa... |
import pkgutil
import importlib
import os
from collections import defaultdict
import re
import yaml
import traceback
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
class Anonymizer(object):
def __init__(self, reader, writer, config, anonymization_job=None, logger_manager=None):
self._logger = log... |
#!/usr/bin/env python3
import openslide # to get required slide metadata
import csv # to read csv
import sys # for csv limit
import os # for os and filepath utils
import argparse # to read arguments
import json # for json in and out
import requests # for api and pathdb in and out
import hashlib
# for large csv fields... |
# from urllib import request
from fastapi import FastAPI, APIRouter, Body, HTTPException, status, Depends, Header
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.encoders import jsonable_encoder
from typing import List, Optional
from starlette.responses import RedirectResponse
from rdflib imp... |
import re
import base64
import requests
from requests import ReadTimeout, ConnectTimeout, HTTPError, Timeout, ConnectionError
from time import sleep
verbose = False
noip_error_messages = {
# In the event that it allowed us to change our ip
'good': lambda new_ip, hostname, response, duc=None:
'[noip-response] "{}... |
import base64
import os
from kahoot import client
import threading
from threading import *
import requests
screen_lock = Semaphore(value=1)
import colorama
from colorama import Fore
from dhooks import Webhook
from itertools import cycle
import ctypes
import termcolor
from termcolor import colored
os.system('color')
bu... |
# Copyright 2020 <NAME> <<EMAIL>>
#
# 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... |
"""Plot utils."""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d # pylint: disable=unused-import
from mpl_toolkits.mplot3d import Axes3D # pylint: disable=unused-import
from ipywidgets import interact, widgets
import pyvista as pv
COLORS = ['r', 'b', 'm', 'g']
def show_cube_stati... |
from pathlib import Path
from datetime import datetime
import re
import csv
import sys
import os
import argparse
import pandas as pd
from pandas import ExcelWriter
from chartline import *
linesInsertDelta = []
linesFinishInsert = []
finalLines = []
xfiles = []
def readFile(filename):
if filename == '.':
f... |
# -*- coding: utf-8 -*-
import datetime, logging, os, pprint, sys, time, unittest
parent_working_dir = os.path.abspath( os.path.join(os.getcwd(), os.pardir) )
sys.path.append( parent_working_dir )
from annex_eod_project import settings
from annex_eod_project.DatePrepper import DatePrepper
from annex_eod_project.Emai... |
# -*- coding: utf-8 -*-
import collections
from xml.sax.xmlreader import AttributesImpl
from xml.sax.saxutils import XMLGenerator
from ecoxipy import _python2, _unicode
from ecoxipy.string_output import StringOutput
from ecoxipy import _helpers
_string_repr = lambda value: 'None' if value is None else "'{}'".forma... |
import string
import os, sys
from enum import Enum
from typing import List, Union
from dotenv import load_dotenv
from src.utils import *
from src.constants import *
import math
from dateutil.relativedelta import relativedelta
import numpy as np
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
ANN_T... |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
from actor_critic import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
import matplotlib.pyplot as plt
from tqdm import tq... |
"""
This module contains general helper methods. None of these methods have dependencies on other scrapenhl2 modules.
"""
import functools
import logging
import os
import os.path
import pickle
import re
import time
import requests
import numpy as np
import pandas as pd
from fuzzywuzzy import fuzz
__SESSION__ = None
... |
import six
import time
from flask import current_app
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client
from zeep.transports import Transport
from zeep.xsd.types.builtins import check_no_collection, DateTime
from pprint import pprint as pp
from lxml import etree
@ch... |
# 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
# distribu... |
import inspect
from collections import OrderedDict
from typing import ( # noqa: F401
Callable, Dict, Any, Union, NamedTuple, TypeVar, Type, List, cast, Optional)
from autobahn.wamp.types import SubscribeOptions, RegisterOptions
from typeguard import check_argument_types
__all__ = ('Procedure', 'Subscriber', 'WAM... |
import torch
from torchvision import transforms
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from utils.utils import *
import json
import numpy as np
import os
from tool.darknet2pytorch import *
from infer import infer
from tqdm import tqdm
from skimage import measure
def fgsm_attack(image, epsilo... |
#!/usr/bin/env python
from collections import defaultdict
from jinja2 import Template
import json
import os
import requests
from le_utils.constants import content_kinds, exercises, file_types, licenses
from le_utils.constants.languages import getlang
from ricecooker.chefs import JsonTreeChef
from ricecooker.config imp... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import AlteryxPythonSDK as Sdk
import xml.etree.ElementTree as Et
import requests
import json
import time
import parse_read_operation
class AyxPlugin:
def __init__(self, n_tool_id: int, alteryx_engine: object, output_anchor_mgr: object):
# Default properties
self.n_tool_id: int = n_tool_id
... |
import numpy as np
import re
import itertools
from collections import Counter
from sklearn import preprocessing
import codecs
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
... |
import scrapy
class MangakuSpider(scrapy.Spider):
name = 'mangaku'
start_urls = ['http://mangaku.web.id/daftar-komik-bahasa-indonesia/']
def parse(self, response):
manga_list = response.css("div.series_alpha")
for x in manga_list:
lists = x.css("ul.series_alpha li")
for y in lists:
link = y.css("a::... |
"""
autoprogramm
~~~~~~~~~~~~
``autoprogram-modified`` (hence the two "m"s at the end of the name.)
Documenting CLI programs.
Adapted & simplified from https://github.com/sphinx-contrib/autoprogram
Besides the name change, here is a summary of the changes:
* Remove six; this is now Pytho... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import time
import json
import logging
import obd
from wrapt import synchronized
from obd import OBDStatus
from .commands import ext_commands
from iotconnect.monitor import Monitor
class OBDIIConnectionError(Exception):
pass
class CanError(Exception):
pass
class IoniqEVMonitor(Monitor):
"""
Class... |
from colors_database import html_colors_dict
from colors_database import html_colors_list
from functools import reduce
from typing import List, Dict
import cherrypy
import math
# config
frequency_round_digits = 4
thumbnail_size = 16, 16
max_colors = 256
def compute_top_colors_of_image(image, number_of_colors: int = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
API to get FX prices from TrueFX
http://www.truefx.com/
http://www.truefx.com/?page=download&description=api
http://www.truefx.com/dev/data/TrueFX_MarketDataWebAPI_DeveloperGuide.pdf
"""
import logging
logger = logging.getLogger(__name__)
import click
import os
imp... |
##imports
from __future__ import division
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import cv2
from util import predict_transform
import warnings
warnings.filterwarnings('ignore')
def get_test_img(file_path):
img = cv2.imre... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 11:35:49 2021
@author: engs2242
"""
from time import time
from threading import Thread
import numpy as np
import msgpack
import zmq
class LightStamper(Thread):
'''Detect and time-stamp light onsets using the Pupil Core World Camera.
Curr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created with YooLiang Technology (侑良科技).
# Author: <NAME> (温啓良)
# Web: http://www.yooliang.com/
# Date: 2016/11/9
from optparse import OptionParser
import os
import json
import sys
import datetime
path_join = os.path.join
os_input = raw_input
if input:
os_input = in... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modified by <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
#
# Unles... |
import requests
import sys
import json
import time
import logging
import yaml
import os
from logging.handlers import TimedRotatingFileHandler
requests.packages.urllib3.disable_warnings()
from requests.packages.urllib3.exceptions import InsecureRequestWarning
def get_logger(logfile, level):
'''
Create a logge... |
import os
from pathlib import Path
import xml.etree.ElementTree as ET
from loguru import logger
import cv2
import numpy as np
import random
from .datasets_wrapper import Dataset
from .voc import AnnotationTransform
from yolox.evaluators.voc_eval import voc_eval, det_image_visualization
def write_filesnames(filenam... |
"""
This is a straightforward Python implementation of a generative adversarial network.
The code is drawn directly from the O'Reilly interactive tutorial on GANs
(https://www.oreilly.com/learning/generative-adversarial-networks-for-beginners).
A version of this model with explanatory notes is also available on GitHub... |
from __future__ import print_function
import time
from sr.robot import *
##
# \file assignment1.py
# \brief This file contains one possible solution to the first RT1 assignment
# \author <NAME>
# \version 0.1
# \date 5/11/2021
#
# \details This assignment aim is to guide the robot shown in the simulation through the ... |
import json
import random
from utils import convert_string, perm_x
class GenericPlayer:
def __init__(self, name, position):
self.name = name.lower()
self.position = position
def get_name(self):
return self.name
def generate_play(self, grid):
pass
def win(self):
... |
import pytest
import os
from pathlib import Path
import shutil
import datetime as dt
from wrftamer.plotting.load_and_prepare import load_obs_data, load_mod_data
from wrftamer.main import project
@pytest.fixture
def base_test_env():
"""
Creates a directory for testing purposes. This directory is removed aftet ... |
import copy
import os
import pickle
import time
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
from direct.stdpy import threading
import config
import utils.pcd_utils as pcdu
import utils.run_utils as ru
from localenv import envloader as el
class ForceRecorder(object):
def __... |
from abc import ABC
from conveyors import product_conveyor, tray_conveyor
from handler import handler_for_cv
from meta import *
from robot import robot
class decorate_object(visual_object, ABC):
def __init__(self, obj: visual_object, init_point: tuple = None, center_point: tuple = None,
border=F... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import numpy as np
import datetime as dt
import plotly.express as px
import plotly
import plotly.graph_objs as go
df_long = pd.read_csv('top20_NetEnergy_DashboardData.csv'... |
#!/usr/bin/env python3
"""
Train and evaluate a SMILESRNN language model.
See `main()`, `HYPERPARAMETERS`, and `CONFIG` for model, sampler, optimizer, and callback
choices.
Run ```python3 run.py --help``` to print help message.
"""
__author__ = '<NAME>'
import argparse
import pathlib
import mxnet as mx
from sklea... |
# File: VGG.py
# Author: <NAME> <<EMAIL>>
import numpy as np
import tensorflow as tf
from tensorcv.models.layers import *
from tensorcv.models.base import BaseModel
import config
VGG_MEAN = [103.939, 116.779, 123.68]
class BaseVGG(BaseModel):
""" base of VGG class """
def __init__(self, num_... |
#!/usr/bin/env python3
"""
pipeline -- Command-line tool for uploading releases to GitHub
References:
* https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/
* https://developer.github.com/v3/repos/releases/
"""
import base64
import datetime
import json
import logging
import os
... |
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
from matplotlib import ticker
import torch
import math
k = 20 # num of selected clients in each round
K = 100 # num of total activated clients
T = 2500 # num of total rounds
def classA(size... |
import h5py
import pandas as pd
from tqdm import tqdm
import os
from ..utils import sort
from ..utils import misc
class nbody_snapshot:
def __init__(self, path, load=True):
self.path = path
self.__init_sequence__(load, reset=True)
def __init_sequence__(self, load, reset=False):
if re... |
from utils import cprint_header, cprint_question, cprint_answer
from utils import bytes_to_int, bytes_to_bin, bytes_to_binlist
from utils import binlist_to_int, binlist_to_bytes
from utils import int_to_bytes, int_to_binlist
def parse_domain(bmsg: bytes, cur: int):
qname = []
while True:
if bmsg[cur] ... |
from functools import partial
import numpy as np
from scipy.interpolate import BSpline
import torch
from itertools import product
class AbstractBasis(object):
def __init__(self):
self.basis_functions = []
self.is_setup = False
def get_basis_functions(self):
if not self.is_setup:
... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os.path
import sys
import pytest
import spack.config
import spack.environment as ev
import spack.main
import spack... |
#!/bin/env python3
"""
Helper for processing and uploading dataset (text collection).
"""
from typing import Set, Tuple, List, Dict, Any
import argparse
import asyncio
import collections
import itertools
import json
import os
import re
import sys
import time
import aiobotocore
import aiofiles
import nltk
import textr... |
# Search Algorithms:
# used to call various search APIs
import requests
# used to shuffle lists
import random
from .static_values import *
# General functions
def search_song(title = "", interpreter = "", country_code = "", service = "", instance = None):
if service == "spotify":
return search_song_spotif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.