text stringlengths 6.04k 39.5k |
|---|
#!/usr/bin/python
"""
Helper script to create location and data separation
Usage:
docker run --rm -it -v $PWD:/working eurodatacube/jupyter-user:0.19.6 /opt/conda/envs/eurodatacube-0.19.6/bin/python3 /working/generate_files.py
If issues with write permission you might have to add a user as parameter
with the same use... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.utils.linear_assignment_ import linear_assignment
def f1(p_num, p_den, r_num, r_den, beta=1):
p = 0 if p_den == 0 else p... |
#!/usr/bin/env python3
import json
import math
import socket
import struct
import sys
import threading
import time
from typing import Tuple, Dict
import skia
from main_loop import main_loop
class Actions:
UPDATE_SCENE = 0
HANDLER_REPLY = 1
SET_VAR = 2
WATCH_ACK = 3
class Protocol:
def __init__... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2020 - <NAME>
"""
from app.main import blueprint
from flask import render_template, redirect, url_for, request, Response
from flask_login import login_required, current_user
from app import login_manager, db, celery
import pandas as pd
import io
from app.main.m... |
import pandas as pd
from itertools import chain
from pgmpy.models import BayesianModel
from pgmpy.models import DynamicBayesianNetwork as DBN
from pgmpy.inference import DBNInference
from pgmpy.estimators import ParameterEstimator
from pgmpy.factors.discrete import TabularCPD
from sklearn.preprocessing import KBinsDisc... |
import time
import serial
import binascii
from collections import namedtuple
import logging
from .socket import UDPSocket
logger = logging.getLogger(__name__)
Stats = namedtuple("Stats", "type name value")
class CMEError(Exception):
"""CME ERROR on Module"""
class ATError(Exception):
"""AT Command Error"... |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
import logging
logger = logging.getLogger(__name__)
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from contextlib import contextmanager
from mvc.ad... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import os
import numpy as np
import json
import matplotlib.pyplot as plt
labels = {
'102': 0,
'103': 1,
'104': 2,
'105': 3,
'106': 4,
'107': 5,
'108': 6,
'109': 7,
'110': 8,
'111': 9,
'112': 10,
'201': 11,
'202': 12,
... |
import subprocess
from typing import Tuple, List, Optional, Union, Dict
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
import tensorrt as trt
import torch
import os
import onnxruntime
from common_keys import *
from tqdm import tqdm
from pytorch_quantization import nn as quant_nn
from pytorch_qua... |
#
# Copyright (c) 2018, Salesforce, Inc.
# The Board of Trustees of the Leland Stanford Junior University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions ... |
#**************************************************************
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to y... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME>
"""
The ``exmaralda`` module converts a ``DiscourseDocumentGraph`` (possibly
containing multiple annotation layers) into an Exmaralda ``*.exb`` file
and vice versa.
"""
import os
import sys
from collections import defaultdict
from lxml import etree
from l... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
*************
Parset reader
*************
"""
__author__ = '<NAME>'
__copyright__ = 'Copyright 2020, nenupy'
__credits__ = ['<NAME>']
__maintainer__ = 'Alan'
__email__ = '<EMAIL>'
__status__ = 'Production'
__all__ = [
'_ParsetProperty',
'Parset',
... |
#!/usr/bin/env python
"""
Copyright 2009 <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,... |
"""Defines the Lamina class for use with brokkr.
TODO:
-----
* [ ] add a property for the compliance matrix Sk in Lamina
* [ ] move stiffness matrix Q to Lamina
* [ ] add failure indices
"""
from numpy import zeros, cos, sin, ndarray
from numpy.linalg import inv
from brokkr.mech_math import ms, out_of_bounds
from br... |
#!/usr/bin/env python
import functools
import subprocess
import re
import shutil
import os
import git
import pathlib
from copy import deepcopy
from cached_property import cached_property
from packaging.version import Version, InvalidVersion
from packaging.specifiers import SpecifierSet
from astropy.table import Table... |
#!/usr/bin/env python3
#
# enumsheets.py
#
# Counts total number of dxf files specified on the command line. Writes sheet
# number and total number of sheets to every dxf files' title block. Optionally
# rewrites date, scale, and address fields. Extracts each sheet title and saves
# contents into Excel table.
#
# This ... |
import warnings
warnings.filterwarnings("ignore")
import os
import argparse
import IPython
import subprocess
import matplotlib.pyplot as plt
import numpy as np
from pyquaternion import Quaternion
from PIL import Image
from numpy import mean, sqrt, square, arange
from math import pi, sqrt, sin, cos, atan2
from config... |
#!/usr/bin/env python
"""
#########################################################
Survival Package Kaplan-Meier Distribution Work Book View
#########################################################
"""
# -*- coding: utf-8 -*-
#
# rtk.survival.gui.gtk.Kaplan-Meier.py is part of The RTK Project
#
# All rights re... |
import math
import os
import pathlib
from glob import iglob
from multiprocessing import Pool
from os.path import exists, join
from typing import List, Optional, Tuple, cast
from urllib.request import urlopen
import cv2
import numpy as np
import PIL
from sklearn.metrics.pairwise import paired_distances
from facenet_sa... |
# Dependencies
import warnings
warnings.filterwarnings("ignore")
import random
random.seed(9999)
import argparse
import pickle
import numpy as np
import pandas
import sys
import itertools
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.ensemble import RandomForestClassifier
from skl... |
#!/usr/bin/python3
import signal
import argparse
import sys
import csv
import re
from pkg_resources import get_distribution
from bedparse import bedline
from bedparse import gtf2bed
from bedparse import BEDexception
# This allows using the program in a pipe
# The program is killed when it receives a sigpipe
signal.sign... |
#!/usr/bin/env python3
from asist_nsf_2018.experiments import experiments
from asist.wave_probe import read_wave_probe_csv
from asist.utility import running_mean
from asist.pressure import read_pressure_from_netcdf
import matplotlib.pyplot as plt
from matplotlib.dates import num2date, date2num
import numpy as np
impor... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Workflow object and WorkflowState mixins.
This contains the basic Workflow object and a mixin for determining the state
of the Objects that are mapped to any cycle tasks.
"""
import calendar
import itert... |
import os
# import os.path as pat
import h5py
import numpy as np
import scipy as sp
import pandas as pd
import soundfile as sf
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.optimize import minimize, minimize_scalar
from dechorate.dataset import DechorateDataset, SyntheticDataset
from dechorate.cadz... |
import numpy as np
#import pandas as pd
import matplotlib
# import seaborn as sns
import matplotlib.pyplot as plt
names = "LR SVM CNN LSTM BERT".split(" ")
colors = ['tab:gray', 'tab:green','tab:orange', 'tab:red', 'tab:blue', 'orange' ]
patterns = ('--', '\\', '////', '\\\\', '\\\\', '\\\\', '.', '*')... |
import ast
import json
from datetime import datetime, timedelta
from operator import itemgetter
from random import randint
import requests
from administer import context_processors
from administer.helper import helper
from administer.models import Nodes, Clusters
from django.contrib import messages
from django.db impo... |
import numpy as np
import open3d as o3d
from transformations import *
import os,sys,yaml,copy,pickle,time,cv2,socket,argparse,inspect,trimesh,operator,gzip,re,random,torch
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))
from scipy.spatial... |
import ida_funcs
import ida_bytes
import idc
import ida_search
import idaapi
import ida_xref
import ida_segment
import ida_offset
import ida_kernwin
from idaapi import BADADDR
from ida_search import SEARCH_DOWN, SEARCH_UP
import ida_auto
import IDAPatternSearch_utils.ida_common as ida_common
import sys
import os
impo... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import asyncio
import inspect
import logging
import os
import io
import sys
import threading
import time
import traceback
import uuid
import weakref
from collections import OrderedDict
from werkzeug.local import Local
from .utils import (
dotdict,
format_traceback,
ReferenceStore,
FuturePromise,
M... |
import os
import app
import evaluation
import logger
import time
from torchtext import data
import torch
from model_attn import Attention
from model_qac import FastDynamic
from baseline import SM
print(os.getpid())
class Args(app.ArgParser):
def __init__(self):
super(Args, self).__init__(description="Twi... |
# FIXME beet and 1.19 changes
import json
import logging
from collections import defaultdict
from dataclasses import dataclass, field
from pathlib import Path, PurePath
from typing import Annotated, Any, ClassVar, Iterable, Literal, TypeVar
from beet import Cache, Context, DataPack, Structure
from nbtlib import Compo... |
import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.datasets as datasets
im... |
import sys,os,re
from xlsxwriter import *
from xlrd import open_workbook
from tkinter import *
import DoorsTCToTemplate_GUI
from tkinter import messagebox
userActionIsRequired = []
systemInput = []
systemOutput = []
systemCal = []
global inputRowCount
global outputRowCount
global calRowCount
def writeHeaderIntoTemp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------
# Copyright (c) 2010-2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file ostap/fitting/simfit.py
# Helper classes to simplify simultaneous fit
# @see RooSimultaneous
# @author <NAME> <EMAIL>
# @date 2018-11-23
# =========================================... |
#!/usr/bin/python3
"""
Compare two gedcom trees.
Arguments: tree1file person1xref tree2file person2xref
A person (child,partnermparent) which gets added in tree2 is not deteched,
in order to do that run the program again reversing the order of the trees.
This code is released under the MIT License: https://opens... |
"""Miscellaneous internal PyJanitor helper functions."""
import functools
import os
import sys
import warnings
from typing import Callable, Dict, List, Union
import numpy as np
import pandas as pd
from .errors import JanitorError
def check(varname: str, value, expected_types: list):
"""
One-liner syntactic... |
import numpy as np
import itertools
import raam
import pickle
from raam import features
from scipy import cluster
from warnings import warn
def degradation(fun,charge,discharge):
"""
Constructs a capacity degradation function from given parameters.
The functions are D- and D+: the anti-derivatives. Se... |
# Copyright 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test external display with optional audio playback test.
Description
-----------
Verify the external display is functional.
The test is defined by a ... |
#! /usr/bin/env python
""" Top-level script for evaluating models """
import numpy as np
import logging
import sys
import torch
import configargparse
import copy
import tempfile
import os
import random
sys.path.append("/storage/homefs/ch19g182/anaconda3/lib/python3.8/site-packages/pytorch-fid-master/src/pytorch_fid"... |
########################################################################################
# Copyright 2019-2021 <NAME> #
# #
# Licensed under the Apache License, Version 2.0 (the "License"... |
#!/usr/bin/python
import argparse
import datetime
import numpy as np
import pickle
import os
import CLS_Clouds as CLS
import scipy.stats
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--date', type=str, help='date on which the algorithm should be run')
parser.add_argument(... |
import copy
import json
import logging
import os
import pickle
import random
import statistics
import sys
import time
import numpy as np
import torch
import yaml
from inclearn.lib import factory
from inclearn.lib import metrics, utils, results_utils
from inclearn.lib.network import FeatureGenerator
from inclearn.lib.... |
# Copyright 2017 The TensorFlow 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... |
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
"""
Helper file storing all information that the different ASEBA forms require.
Data shared between forms is defined in the top-level FormASEBA class, as are
the data structures and function me... |
import os
import shutil
import stat
import time
import shlex
from subprocess import Popen, check_output, PIPE, CalledProcessError
from threading import Timer
from ...utils.security import switch_to_site_user
from .models import Site
from ..users.models import User, Group
from django.conf import settings
from django.... |
import sys
import os.path
import random
import time
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
# This will allow us to place ships, etc
import board
import utils
import ships
import animations
class Player:
def __init__(self, **kwargs):
self.board = board.Board(player=... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from Commands.Keys import Button, Direction, Hat
from Commands.PythonCommandBase import PythonCommand
# import numpy as np
from scipy.sparse.csgraph import shortest_path # , floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix
se... |
from __future__ import print_function
import random
import math
import numpy as np
import torch
import torchnet as tnt
class FewShotDataloader:
def __init__(
self,
dataset,
nKnovel=5,
nKbase=-1,
nExemplars=1,
nTestNovel=15*5,
nTestBase=15*5,
batch_... |
import argparse
from datetime import datetime
import numpy as np
import random
import tensorflow as tf
import socket
import os
import sys
import h5py
import struct
BASE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR) # model
sys.path.append(os.path.join(BASE_DIR... |
"""
Pre-training Bidirectional Encoder Representations from Transformers
=========================================================================================
This example shows how to pre-train a BERT model with Gluon NLP Toolkit.
@article{devlin2018bert,
title={BERT: Pre-training of Deep Bidirectional Transform... |
import json, os, traceback as tb, numpy as np
class UnsupportedCommandException(Exception):
'''
Used to indicate that the given command is unsupported
'''
def __init__(self,msg):
self.message = msg
super().__init__(self.message)
class UnknownCommandException(Exception):
'''
... |
# -*- coding: utf-8 -*-
# Copyright 2018 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Python module to draw heat map for Chrome
heat map is a histogram used to analyze the locality of function layout.
This modul... |
# starch: framework glue for selecting ISA-specific code at runtime
# Copyright (c) 2020, FlightAware LLC.
# All rights reserved.
# See the LICENSE file for licensing terms.
import sys
import re
import os
import mako.lookup
from functools import total_ordering
from typing import Optional, Union, Iterable, Sequence, ... |
import numpy as np
import pytest
import nept
toy_array = np.array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
def test_find_nearest_idx():
assert nept.find_nearest_idx(toy_array, 13) == 3
assert nept.find_nearest_idx(toy_array, 11.49) == 1
assert nept.find_nearest_idx(toy_array, 11.51) == 2
assert... |
# this program contains the following functions:
# 1. find the mapping relationship between ctrl and drives.
# 2. check each device by command sg_inq
# 3. use FIO to write/read data
# 4. check the PHY counter by GEM command
# when should we run this program:
# 1. sometimes, one drive goes wrong but we ge... |
import socket, unittest, os, pickle, datetime
from testlib import testutil, PygrTestProgram, SkipTest
from pygr import seqdb, cnestedlist, metabase, mapping, logger, sqlgraph
from pygr.downloader import SourceURL, GenericBuilder, uncompress_file, \
do_unzip, do_gunzip
try:
set
except NameError:
from sets ... |
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from mmcv.runner import auto_fp16
import numpy as np
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from ..builder import NECKS
class AdaptiveAngleConv(nn.Module): # def... |
# -*- coding: utf-8 -*- äöü vim: ts=8 sts=4 sw=4 si et tw=79
"""
thebops.svnurls: Split / unsplit Subversion URLs
Supports the Subversion standard layout::
^/
...
|- my.project
| |- trunk
| |- branches
| | |- feature1
| | `- v1_0
| `- tags
| `- v1.0
:
Tags ... |
import datetime
import typing
from uuid import UUID
import attr
from dbnd._core.constants import (
DbndTargetOperationStatus,
DbndTargetOperationType,
RunState,
TaskRunState,
UpdateSource,
)
from dbnd._core.tracking.airflow_dag_inplace_tracking import AirflowTaskContext
from dbnd._core.tracking.s... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.10.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
import math
import os
impo... |
import tensorflow as tf
import tensorflow.keras.layers as layers
from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, Flatten, Dropout
from tensorflow.keras import Model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
class Sampling(layers.Layer):
def call(self, inputs):
z_mean, z_sig... |
import sys
from PyQt5.QtWidgets import (QWidget, QToolButton, QApplication,
QDesktopWidget, QGridLayout, QSplitter,
QTreeWidget, QTreeWidgetItem, QMenu, QAction,
QLineEdit, QInputDialog, QMessageBox,
QRad... |
import numpy as np
import torch
import dolfin as df
from utils.conversions import Convert_ScipySparse_PyTorchSparse
from fawkes.utils import AssembleBasisFunctionMatrix
from bottleneck.utils import UnitGaussianKullbackLeiblerDivergence, relative_error
from lamp.neuralnets import FeedforwardNeuralNetwork
from bottlene... |
import psycopg2
import psycopg2.extras
import md5
def getOperator(conn,prefix=None,website=None):
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
if website is None:
website = 'http://www.example.com'
if prefix is None:
prefix = 'DINO'
cur.execute("""
SELECT DISTINCT O... |
##
# .cluster - PostgreSQL cluster management
##
"""
Create, control, and destroy PostgreSQL clusters.
postgresql.cluster provides a programmer's interface to controlling a PostgreSQL
cluster. It provides direct access to proper signalling interfaces.
"""
import sys
import os
import errno
import time
import subprocess... |
# coding=utf-8
# Copyright 2021 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... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2018, SLAC / 8minutenergy / Kisensum.
#
# 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://... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2018 Zuse Institute Berlin, www.zib.de
Permissions are granted as stated in the license file you have obtained
with this software. If you find the library useful for your purpose,
please refer to README.md for how to cite IPET.
@author: <NAME>
"""
impor... |
# -*- coding: utf-8 -*-
from __future__ import division
import pickle
import time
from matplotlib.legend_handler import HandlerLine2D
from classifier import CNNClassifier
from ops import *
from utils import *
class WGAN_GP(object):
model_name = "WGAN_GP" # name for checkpoint
def __init__(self, sess, epoch, ba... |
#!/usr/bin/env python3
from __future__ import print_function
import sys
import time
import argparse
import threading
try:
import readline
except:
pass
import mufsim.stackitems as si
import mufsim.gamedb as db
import mufsim.utils as util
from mufsim.logger import log, warnlog, set_output_command
from mufsim.... |
from __future__ import unicode_literals
from datetime import datetime
from erpnext.controllers.accounts_controller import get_taxes_and_charges
from frappe.model.mapper import get_mapped_doc
from frappe.utils import add_days, today, date_diff, getdate, add_months
from property.lease_invoice import getDueDate
import cal... |
from netCDF4 import Dataset
import numpy as np
import matplotlib as mpl
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import math
degreesToRadians = math.pi / 180.0
#--------------------... |
from difflib import get_close_matches
import re
import requests
def regex_group(search, num, default=None):
try:
return search.group(num)
except (AttributeError, IndexError):
return default
def regex_match(findall, num, default=None):
try:
return findall[num]
except (TypeError... |
#!/usr/bin/env python3
#
# SPDX-License-Identifier: MIT
#
# This file is formatted with Python Black
import click
import logging
import logging.config
import os
import re
import sys
import yaml
from typing import Optional
try:
from gi.repository import GLib
except ImportError:
print(
"GObject introsp... |
from subprocess import call, PIPE, Popen
from sys import stdin, stdout, platform, version_info
from os import system
from termios import tcgetattr, tcsetattr, TCSADRAIN
from time import sleep
from tty import setcbreak
from dialog import Dialog
d = Dialog(dialog="dialog")
d.set_background_title("036 Creative Studios")
... |
import os
import pandas
import math
import ntpath
from BirdRoostLocation.ReadData import Labels
import numpy as np
from BirdRoostLocation import utils
from BirdRoostLocation.PrepareData import NexradUtils
from BirdRoostLocation import LoadSettings as settings
from BirdRoostLocation.BuildModels.CNN import model as shall... |
from pynput.keyboard import Key, Listener
import pygame.midi
import turtle
import threading
# print is not allowed since when java call this file, print statement will break the keyboard listener
def _pre_pre_process_key(key):
key = str(key).lower()
key = key.strip()
if key == "'''":
return "'"
... |
import serial
from serial.serialutil import SerialException
import sys
import time
import logging
import traceback
import odrive
from odrive.enums import *
from odrive.utils import start_liveplotter, dump_errors
import fibre
default_logger = logging.getLogger(__name__)
default_logger.setLevel(logging.DEBUG)
# crea... |
# -*- coding: utf-8 -*-
"""
http://www.sphinx-doc.org/en/stable/ext/doctest.html
https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/doctest.py
* TODO
** CLEANUP: use the sphinx directive parser from the sphinx project
"""
import doctest
import enum
import re
import sys
import textwrap
import traceback
impor... |
# -*- coding: UTF-8 -*-
"""
Created by louis at 2021/11/13
Description: Packed Padded Sequences, Masking, Inference and BLEU
"""
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator
impor... |
#!/usr/bin/env python3
from random import randint
import argparse, sys
sbox = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0... |
import numpy as np
from scipy.stats import sem
from uncertainties import ufloat
import uncertainties.unumpy as unp
import matplotlib.pyplot as plt
import scipy.constants as sc
from scipy.optimize import curve_fit
#from pint import UnitRegistry
import operator
#u = UnitRegistry()
#Q_ = u.Quantity
Time_ges = 81591 #Bs... |
from __future__ import division
#kivy modules
from kivy.app import App
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.base import EventLoop
from kivy.core.window import Window
from kivy.core.image import Image
from kivy.graphics.instructions import RenderContext
from kivy.graphics import... |
#!/usr/bin/env python3
"""vanguard_pdf_to_txns extracts transactions from Vanguard history web pages
saved to PDF. Vanguard provides structured CSV and OFX files for only the last
year. This provides structured data for the longer length of time that Vanguard
provides history via web pages, in 10 year time intervals. ... |
# bot.py
import asyncio
import concurrent.futures
from concurrent.futures import CancelledError
from typing import Optional
import discord
import logging
import traceback
import peewee
from core.AbstractFrontend import AbstractFrontend, FrontendUserInfo
from core.AbstractRadioEmitter import AbstractRadioEmitter
fro... |
#!/usr/bin/env python3
import gzip
import io
import pickle
import os
import sys
from argparse import ArgumentParser
try:
from .version import SalmID_version
except ImportError:
SalmID_version = "version unknown"
def reverse_complement(sequence):
"""return the reverse complement of a nucleotide (includi... |
from enum import Enum, auto
import torch
from torch import Tensor
from ..utils import parametrize
from ..modules import Module
from .. import functional as F
from typing import Optional
def _is_orthogonal(Q, eps=None):
n, k = Q.size(-2), Q.size(-1)
Id = torch.eye(k, dtype=Q.dtype, device=Q.device)
# A r... |
import hashlib
import json
import os
import shutil
import time
from collections import Counter
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union
import numpy as np
import pandas as pd
from fire import Fire
from pydantic import BaseModel
from pydantic.main import Extra
from tqdm import... |
import copy
import warnings
import weakref
import pandas as pd
from woodwork.accessor_utils import (
_check_column_schema,
_is_dataframe,
_is_series,
init_series,
)
from woodwork.column_schema import ColumnSchema
from woodwork.exceptions import ParametersIgnoredWarning, TypingInfoMismatchWarning
from ... |
r"""Main module that computes the optimal policy.
"""
import numpy as np
from adapt_hypo_test.two_states import util
from adapt_hypo_test.two_states.util import (nx_to_log_odds, m_to_r, pq_to_m, x_grid, lp_grid, log_p_log_q_to_m)
from scipy.special import logsumexp
def nop_reward(log_cond_reward, m, lp):
r"""Co... |
#!/usr/bin/env python3
#
# 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 requir... |
#!/usr/bin/env python
import argparse
import os
import re
import sys
import readchar
BOLD = "\033[1m"
NORMAL = "\033[0m"
UNDERLINE = "\033[4m"
PURPLE = "\033[95m"
CYAN = "\033[96m"
DARKCYAN = "\033[36m"
BLUE = "\033[94m"
GREEN = "\033[92m"
def _token_to_str(token):
if isinstance(token, str):
return tok... |
# -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2017, ColoredInsaneAsylums
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the... |
#!/usr/bin/python
#################################################################################
#
# Copyright (c) 2009, <NAME>, All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistrib... |
import csv
import itertools
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import FieldError
from django.core.exceptions import ObjectDoesNotExist
from ... |
import os
import stat
import re
import pdb
from pathlib import Path
import getpass
import numpy as np
import h5py as h5
import pandas as pd
import subprocess
from glob import glob
from tqdm import tqdm
from .dataset import _submit_slurm_job
import shutil
import yaml
import threading
import time
from datetime import t... |
import socket
import struct
import pickle
import numpy as np
import json
import torch
import torch.nn as nn
from torch.optim import Adam, SGD, AdamW
from threading import Thread
import torch.nn.functional as F
import time
from torch.autograd import Variable
import random
import sys
from sklearn.preprocessing import Min... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.