text stringlengths 3.07k 12.6k |
|---|
import torch
from allennlp.modules.feedforward import FeedForward
from allennlp.modules.seq2vec_encoders import PytorchSeq2VecWrapper
from higher.patch import monkeypatch as make_functional
class ConditionedParameter(torch.nn.Module):
# 这里应该是5个FFNN的代码
def __init__(self, parameter, condition_dim=1024, hidden_d... |
from flask import redirect, url_for, render_template, request, flash, g
from flask_login import current_user
from application import app, db, login_manager, login_required
from application.songs.models import Song
from application.auth.models import User
from application.authors.models import Author
from application.a... |
"""Everything related to the solution of a structural model."""
import functools
import numpy as np
from respy.interpolate import kw_94_interpolation
from respy.parallelization import parallelize_across_dense_dimensions
from respy.pre_processing.model_processing import process_params_and_options
from respy.shared imp... |
#!/usr/bin/env python
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
import os, sys, shutil, copy
import numpy as np
from ordered_dict import OrderedDict
from ordered_bunch import OrderedBunch
from switch imp... |
"""Converts PASCAL dataset to TFRecords file format."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import io
import os
import sys
import PIL.Image
import tensorflow as tf
from utils import dataset_util
parser = argpar... |
"""Helper functions
"""
from code import interact
import string
from brownie import (
MockV3Aggregator,
MockDAI,
MockWETH,
# VRFCoordinatorMock,
LinkToken,
# AdvancedNFT,
ETH_ADDRESS,
accounts,
network,
interface,
config,
Contract,
)
from brownie.network.contract import ... |
"""
Author: taowen
Date: 2017-11-15
"""
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
def weight_variable(shape):
# initial = tf.random_normal_initializer(0, 0.02)
initial = tf.truncated_normal(shape, stddev=1e-2)
ret... |
"""
Cr"""
import os
import sys
import operator
from datetime import datetime
from click import echo, secho
import boto3
IAM_ROLE = "ec2"
def abort(txt):
secho(txt, fg="red")
sys.exit(1)
try:
DRIFT_CONFIG_URL = os.environ["DRIFT_CONFIG_URL"]
DRIFT_TIER = os.environ["DRIFT_TIER"]
DD_API_KEY = os... |
"""
Implementation testing for hashable parameters function.
"""
# Many imports derived from PyTorch source
import torch
from torch.nn.modules import Module
import torch.nn as nn
from torch.nn import Parameter
from src.resnet import ResNet, ResidualBlock
from torch import Tensor, device, dtype
from collections import O... |
import torch
from typing import Union, Optional
from torch.nn.modules.loss import _Loss
from super_gradients.training.utils.segmentation_utils import to_one_hot
from super_gradients.training.losses.loss_utils import apply_reduce, LossReduction
from super_gradients.common.abstractions.abstract_logger import get_logger
... |
import torch
#import torchvision.transforms as transforms
import numpy as np
import cv2
import torch.nn.functional as F
from fairmot.opts_fairmot import opts
from fairmot.model.model import create_model, load_model
from fairmot.model.decode import mot_decode
from fairmot.model.utils import _tranpose_and_gather_feat
fr... |
from __future__ import annotations
import re
import random
import itertools
from typing import Any, Tuple, Union, Optional, Sequence
from .match import Match
from .types import (
ReplacementType,
DynamicWeightFnType,
ReplacementDictType,
ReplacementCallableType,
ReplacementSequenceType,
)
from .e... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import os
import argparse
from sklearn.neighbors import NearestNeighbors
from s... |
# coding=utf-8
# Copyright 2017 <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... |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
def a_norm(Q, K):
m = th.matmul(Q, K.transpose(2,1).float())
m /= th.sqrt(th.tensor(Q.shape[-1]).float())
return th.softmax(m , -1)
def attention(Q, K, V):
#Attention(Q, K, V) = norm(QK)V
a = a_norm(Q, K) #(batch_size, ... |
from django.shortcuts import render,reverse,redirect,HttpResponse,get_object_or_404
from View.models import Deals,Profile,Mydeals,Request
from django.contrib.auth.models import User
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from djan... |
import numpy as np
import scipy.sparse as sp
import tensorflow as tf
from tensorflow.keras import Model, Input
from tensorflow.keras.layers import Dropout, Concatenate, BatchNormalization
from tensorflow.keras.optimizers import Nadam
from tensorflow.keras import regularizers
from tensorflow.keras.losses import SparseCa... |
import js
from RobotRaconteur.Client import *
import importlib_resources
import traceback
import numpy as np
import base64
from RobotRaconteurCompanion.Util.GeometryUtil import GeometryUtil
class NewImageTemplateDialog:
def __init__(self, new_name, core, device_manager):
self.vue = None
self.core =... |
# Inspired by https://deap.readthedocs.io/en/master/examples/gp_symbreg.html
# That example has extensive explanations.
import sys
import operator
import math
import random
import numpy
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from deap import gp
import prefix2in... |
"""Plotting functions based on plotly."""
from pathlib import Path
from typing import Optional, Union
import mne
import numpy as np
import pandas as pd
import scipy.signal
def plotly_mne(
mne_raw: mne.io.BaseRaw,
file_name: Union[Path, str],
time_slice: tuple = (),
plot_title: Optional[str] = None,
... |
import os
import pickle
import numpy as np
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Dataset
from src.preprocess import zero_padding,target_padding
import pandas as pd
# TODO : Move this to config
HALF_BATCHSIZE_TIME = 800
HALF... |
# -*- coding: utf-8 -*-
"""
This module exposes a single class :class:`ga4gh.dos.client.Client`, which
exposes the HTTP methods of the Data Object Service as named Python functions.
This makes it easy to access resources that are described following these
schemas, and uses bravado to dynamically generate the client fu... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @FileName :base.py
# @Author :Lowell
# @Time :2022/3/29 20:09
import argparse
import os
import sys
from argparse import ArgumentParser, HelpFormatter
from io import TextIOBase
import django
from django.core.management.color import no_style, color_style
ALL_CHECK... |
# bootload a system running the bootloader firmware
import serial
import time
import struct
import crcmod.predefined
crc_16_kermit = crcmod.predefined.mkPredefinedCrcFun("kermit")
from ..gateware.bootloader_fw import (
ROM_INFO_WORDS, BOOTLOADER_VERSION, GATEWARE_VERSION)
class BootloadError(Exception): pass
c... |
import collections
import dataclasses
import enum
import functools
import importlib
import typing
from enum import Enum
from typing import Optional, Dict, Type, Set
import construct
from mercury_engine_data_structures import dread_data
@dataclasses.dataclass(frozen=True)
class BaseType:
name: str
@property
... |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
"""
Plotting library
"""
def plot_framea_as_RGB(frames = (None,None,None)):
"""
"""
from matplotlib import pyplot as plt
from numpy import zeros
img = zeros((3000,4096,3),dtype = 'uint8')
for i in range(3):
img[:,:,i] = frames[i]
fig = plt.figure(figsize=(4, 4))
grid = plt.GridSp... |
from __future__ import print_function
from __future__ import absolute_import
import sys
def string_to_hex(s):
x = [ "%02x" %ord(ch) for ch in s]
return " ".join(x)
# Set container flag for pure containers. Boxes with data and children should be
# handled in their own subclass
class Box(object):
box_names... |
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
from latlong_vrp import append_list_as_row, update_file, makefile, plotgraph,update_fixed
import sys
import pandas as pd
import time
import math
start_time = time.time()
filepa... |
import pandas as pd
import numpy as np
from . import array as dparray
from . import integration as integration
def truncate_data(dataset : pd.DataFrame, before: bool = True) -> pd.DataFrame:
"""
Truncates a dataset before/after the longest block of continuous zeroes.
Given a dataset, truncates the dataset... |
#! /usr/bin/env python
'''
@name: run_ppo.py
@brief: Trained agent is loaded and executed.
@author: <NAME>
@version: 3.5
@date: 2019/04/05
'''
import os
import sys
import rospy
import rospkg
import configparser
import time
import numpy as np
from rl_agent.env_wrapper.ros_env_con... |
import os
import torch
from tqdm import tqdm
import argparse
import multiprocessing as mp
import pandas as pd
from moses.models_storage import ModelsStorage
from moses.metrics.utils import average_agg_tanimoto, fingerprints, fingerprint
from rdkit import DataStructs, Chem
from scipy.spatial.distance import jaccard
impo... |
import json
import ctypes
import urllib
import os
import random
import eel
from src.google_api import GoogleApi
from src.resource_path import resource_path
OPTIONS_PATH = resource_path('storage/options.json')
FAVORITES = 'FAVORITES'
# Helper methods
def find_in_list_by_val(list_, key, val):
return next((d for d ... |
#!/usr/bin/env python3
# Author: <NAME>, 2017
#
# Test suite for the PythonRename unit.
import unittest
import os
import shutil
import sys
sys.path.append('../')
import PythonRename as rename
# Global variables
path = os.getcwd()
test_directory = "TestFiles"
test_file_details = [{'name': 'File-1.png', 'content':... |
import datetime
import pytest
from stactools.ecmwf_forecast import stac
def test_create_collection():
# Write tests for each for the creation of a STAC Collection
# Create the STAC Collection...
collection = stac.create_collection()
collection.set_self_href("")
# Check that it has some required... |
from flask import Blueprint, Flask, request, jsonify
from __init__ import mysql
import MySQLdb.cursors
from hovercolor import getColor
welcome_bp = Blueprint('welcome', __name__)
ALBUM_DATA = (
"SELECT AL.title, AL.id, AL.image, max(A.name) as name "
"FROM Album AL, Making M, Artist A, LikesAlbum Lk "
"WH... |
import numpy as np
import torch
def least_squares(a, b, rcond=None):
"""
A PyTorch implementation of NumPy's "linalg.lstsq" function
Parameters
----------
a : torch.Tensor
(m,n) "Coefficient" matrix
b : torch.Tensor
(m,) or (m,k) "dependent variable" values
rcond : float
... |
from rest_framework import serializers
from .models import Filing, FilingList, Holding, Cik, Cusip
class FilingPeriodSerializer(serializers.ModelSerializer):
quarter_name = serializers.SerializerMethodField()
def get_quarter_name(self, obj):
year = obj.quarter.year
month = obj.quarter.month
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import os
import shutil
import numpy as np
import pandas as pd
import geopandas as gp
from osgeo import gdal, ogr, osr
import argparse
import logging
import matplotlib.pyplot as plt
from quarry_searcher_core import generate_tmp_path
def __reproject_to_img(g... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
import os
class FailedException(Exception):
def __init__(self, result):
self.result = result
class ActionModule(ActionBase):
TRANSFERS_FILES = False
def _run_... |
from pycocotools.coco import COCO
import json
from detectron2.data.datasets import register_coco_instances
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.utils.visualizer import Visualizer
from detectron2.config import get_cfg
from detectron2 import model_zoo
from detectron2.engine import D... |
"""
计算常见机器学习指标的方法
Methods to compute common machine learning metrics
"""
import numpy as np
def _roc_curve(preds, targets, partition, pos_class, neg_class):
"""
ROC curve (for binary classification only)
ROC曲线的作用:
1.较容易地查出任意界限值时的对类别的识别能力
2.选择最佳的诊断界限值。ROC曲线越靠近左上角,试验的准确性就越高。
最靠近左上角的ROC曲线的点是错... |
import numpy as np
import os
from tqdm import tqdm
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from data.dataset import get_train_val_loader, inverse_normalize, get_test_loader
from model import UNet
from utils.Config import opt
from utils.vis_tool impo... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 14 16:02:51 2021
@author: AshwinBalaji
"""
import sys
import random
import math
from fractions import Fraction
def checkPrime():
flag = False
prime = int(input("Prime-Number [GF(prime)] : "))
if prime > 1:
for itr in range(2, prime... |
import os
import argparse
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras import callbacks
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, Ma... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os, sys
##############################################################################################################
##DO NOT change this part.
##../setup.py will update this variable
HTC_package_path = "C:/Users/tyang/Documents/Jupyter_workspace/HTC/python_3"... |
'''rss2sql.py
RSS to SQL toolkit
'''
import logging
import feedparser
import requests
import sqlalchemy
import yaml
LOGGER = logging.getLogger('rss2sql')
META = sqlalchemy.MetaData()
class ToolKit:
@staticmethod
def struct_time_To_datetime(st):
from datetime import datetime
from time import ... |
from flask import Flask, session, redirect, url_for, request
import random
from datetime import datetime
from PIL import Image
app = Flask(__name__, static_url_path='', static_folder='static/')
app.secret_key = '20f75e46-4d3a-452d-ae10-96d1b45d2428'
@app.route('/')
@app.route('/instructions')
def instructions():
... |
"""
Copied from https://gist.github.com/ebenolson/1682625dc9823e27d771
Functions to create network diagrams from a list of Layers.
Examples:
Draw a minimal diagram to a pdf file:
layers = lasagne.layers.get_all_layers(output_layer)
draw_to_file(layers, 'network.pdf', output_shape=False)
Draw... |
import csv
import json
import logging
import os
import re
import time
import jmespath
from jmespath import functions
from jsonschema import validate
import requests
import yaml
LOGGER = logging.getLogger('helpers')
def now():
return int(round(time.time()))
def load_file(path, f_type=None, raw=None, delimiter... |
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.sort
~~~~~~~~~~~~~~~~~
Provides functions for sorting a stream by an item field.
Examples:
basic usage::
>>> from riko.modules.sort import pipe
>>>
>>> items = [{'content': 'b'}, {'content': 'a'}, {'content': 'c'}]
... |
import torch
import torch.nn as nn
from utils import v_wrap, set_init, push_and_pull, record
import torch.nn.functional as F
import torch.multiprocessing as mp
from shared_adam import SharedAdam
import gym
import math, os
import argparse
import matplotlib.pyplot as plt
from simulations.pendulum_sim import Simulation
o... |
from enum import Enum
import re
class Status(Enum):
""" Enumeration of possible solution status. """
OPTIMAL = 'Optimal'
UNKNOWN = 'Unknown'
SUBOPTIMAL = 'Suboptimal'
UNBOUNDED = 'Unbounded'
INFEASIBLE = 'Infeasible'
INF_OR_UNB = 'Infeasible or Unbounded'
def print_values(value_dict, pat... |
from otree.api import *
c = cu
doc = 'Introduction and risk attitude lottery game based on Holt and Laury (2002).'
class Constants(BaseConstants):
name_in_url = 'risk_attitude'
players_per_group = None
num_rounds = 1
payoff_red_A = 40
payoff_white_A = 32
payoff_red_B = 77
payoff_white_B = ... |
import re
from collections import defaultdict
from datetime import datetime, timedelta
from typing import List, DefaultDict, Optional, Set
from nonebot import NLPSession, IntentCommand, CommandSession
from nalomu.commands import BaseCommand, method_command
from nalomu.commands.functions import method_nlp
RegexType =... |
"""Module to implement the evaluation metrics"""
import math
import functools
from typing import List
from scipy import stats
import numpy as np
_METRICS = []
_CMETRICS = []
def raw_wrapper(func, true_set: List, predicted_set: List, *args):
try:
result = func(true_set, predicted_set, *args)
except:
... |
import itertools
import numpy
import random
import grimagents.common as common
import grimagents.constants as const
class InvalidTrainerConfig(Exception):
"""The trainer config yaml file is invalid."""
pass
class InvalidGridSearchIndex(Exception):
"""An attempt to access an invalid GridSearch index wa... |
import MainDarkLogic.darklogic as DarkLogic
from Database.database import Database
from enum import Enum
import multiprocessing
from threading import Thread, Condition, Lock
import time
from AI.event import Event
from AI.ai import AI
class TestEnum(Enum):
HumanIdentity = 1
HumanDoubleNot = 2
HumanExcluded... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import boto3
import botocore
import os
import logging
import os.path
from datetime import datetime
import dateutil.tz
import uuid
def start_etl_job_run(execution_id, p_stp_fn_time, sfn_arn, sfn_name... |
# perform auto training loop
import psutil
import time
import datetime
import os
import random
# num of processes to launch
# need to clear games folder when modifying its value
n_proc=32
cpuFreeThreshold=1.0
bigr,Nbgr=0,100
smlr,Nslr=0,1
start_time = time.time()
for ddir in ["./weights","./games","./eval"]:
i... |
"""tests.hash.test_hashentry.py
Copyright <NAME>, LLC.
Licensed under MIT (https://github.com/tektronix/syphon/blob/master/LICENSE)
"""
import hashlib
import os
import pathlib
from typing import List, Optional
import pytest
from py._path.local import LocalPath
from syphon.errors import MalformedLineError
from... |
'''
adapted from https://github.com/jaywalnut310/glow-tts/blob/master/commons.py
Copyright (c) 2020 <NAME>
MIT License
https://opensource.org/licenses/mit-license.php
'''
import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
@torch.jit.script
def fused_add_tanh_sigmoid... |
import math
import numpy as np
from scipy.stats import zscore
from typing import Optional, Dict, List, Tuple
from numpy import logaddexp
def _round_up(x: float) -> int:
"""Custom rounding method for benchmarking with previous versions"""
if (float(x) % 1) >= 0.5:
return math.ceil(x)
else:
... |
"""Support for consolidation of datasets based on equivalence between parts ."""
version = '18th June 2021'
import logging
log = logging.getLogger(__name__)
log.debug('consolidation.py version ' + version)
import resqpy.crs as rqc
import resqpy.olio.uuid as bu
import resqpy.olio.xml_et as rqet
import resqpy.organiz... |
import os
import PIL
import numpy as np
import torchvision.transforms as transforms
from copy import deepcopy
from .all_pairs.grid_loader import GridDataLoader
from .class_sampler import ClassSampler
from .cifar import CIFAR10Loader
from .fashion_mnist import FashionMNISTLoader
from .mnist_cluttered import ClutteredMN... |
import numpy as np
import scipy.sparse as sp
import warnings
#import pdb
# Matrix-vector product wrapper
# A is a numpy 2d array or matrix, or a scipy matrix or sparse matrix.
# x is a numpy vector only.
# Compute A.dot(x) if t is False,
# A.transpose().dot(x) otherwise.
def mult(A,x,t=False):
if(sp.isspars... |
import logging
from datetime import datetime
from os.path import join
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from hdx.data.dataset import Dataset
from hdx.utilities.downloader import Download
from hdx.utilities.path import temp_dir
from jsonpath_ng import parse
from olefile import olefile... |
import math
import tqdm
import os
import pickle
import tensorflow_hub as hub
import tensorflow as tf
import numpy as np
import re
EMPTY = '\t'
getnettemps = lambda p, t: np.where(p.argsort()[::-1]==t)
def load(filename, python2=False, **kargs):
if python2:
kargs.update(encoding='latin1')
with open(f... |
import os
import time
import tempfile
import unittest
import json
import uuid
import threading
from subprocess import Popen
import psutil
import requests
import kafka
import pandas as pd
MINDSDB_HOST = os.getenv("MINDSDB_HOST")
MINDSDB_URL = f"http://{MINDSDB_HOST}:47334"
HTTP_API_ROOT = f"{MINDSDB_URL}/api"
INTEG... |
"""
Módulo que contém os serializers para os modelos Destinatario, ModoEnvio e Mensagem
definidos em models.py
Os serializers definidos aqui serão utilizados nas ModelViewSets definidas em views.py
"""
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from .models import De... |
"""
Drag and drop this file into your viewport to run the mGear installer.
1. Default Install:
Will install in the users documents folder where Maya is installed, a
restart will not be required.
2. Custom Install:
Will install in the user specified directory, this method will write the
correct modul... |
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribution and at:
#
# http:... |
import logging
import math
import time
from .objects import Pod
from .exceptions import KubernetesError
logger = logging.getLogger(__name__)
class RollingUpdater(object):
def __init__(self, api, old_rc, new_rc, **kwargs):
self.api = api
self.old_rc = old_rc
self.new_rc = new_rc
... |
import spacy
import os
import pytextrank
import networkx as nx
import math
import operator
import nltk
import pickle
root = os.path.dirname(os.path.abspath(__file__))
download_dir = os.path.join(root, 'my_nltk_dir')
nltk.data.path.append(download_dir)
from nltk.tokenize import sent_tokenize, word_tokenize
nlp=spacy.... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2021 <NAME>, https://github.com/tywtyw2002, https://github.com/treedust, and <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
#
# ... |
'Python library for connection to the Cisco Telepresence XAPI over WebSockets.'
import asyncio
import inspect
import aiohttp
from .version import __version__
class XoWSError(Exception):
"Parent exception class for all XoWS errors."
class ConnectionClosed(XoWSError):
"Connection closed unexpectedly."
cl... |
import copy
import datetime
import gzip
import os
import random
import re
import sys
import urllib.request
from typing import List
# a source to use when generating a list of correct words:
# using Simple English Wikipedia
WORDS_SOURCE_URL: str = 'https://dumps.wikimedia.org/simplewiki/latest/simplewiki-latest-all-ti... |
#!/usr/bin/env python3
import requests
import json
import os
import os.path
import argparse
import sys
from collections import OrderedDict
ATTACHMENTS_DIRECTORY = "attachments/"
PROFILES_DIRECTORY = "profiles/"
MESSAGES_FILE = "messages.json"
VERBOSE = False
DEBUG = False
BASEURL = "https://api.groupme.com/v3"
def... |
"""
Data preparation file
"""
import numpy as np
import pandas as pd
def clean_string(string):
return ''.join(e for e in string if e.isalnum())
def reverse_dict(d):
new_d = {}
for k,i in d.items():
new_d[i] = k
return new_d
def mapping(files):
"""
Creates a unique index for ever enti... |
import shutil
import tempfile
import pytest
from mock import MagicMock
from scanpointgenerator import LineGenerator, CompoundGenerator, \
StaticPointGenerator, SquashingExcluder
from malcolm.core import Context, Process, Part, PartRegistrar, \
StringMeta, NumberMeta
from malcolm.modules.ADPandABlocks.blocks ... |
# -*- coding: utf-8 -*-
"""
Check testing environment.
"""
import pytest
from tests.conftest import perform_once
@pytest.mark.hwtst
def test_versions_matches(accelize_drm):
"""
Checks that the C/C++ library and the Python libraries versions matches.
"""
api_version = accelize_drm.get_api_version()
... |
import numpy as np
def rshift_zero_padded(val, n):
"""Zero-padded right shift"""
return (val % 0x100000000) >> n
def _mix(a, b, c):
"""
mix 3 32-bit values reversibly.
For every delta with one or two bit set, and the deltas of all three
high bits or all three low bits, whether the original v... |
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
#!/usr/bin/python
from collections import defaultdict
import os
import json
import sys
import xml.parsers
from xml.dom import minidom
def get_int(e):
return int(e.childNodes[0].nodeValue)
def get_float(e):
return float(e.childNodes[0].nodeValue)
def load_elements(from_dir):
elements = {}
for filena... |
import matplotlib.pyplot as plt
import numpy as np
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import networkx as nx
from tqdm import tqdm
import os
import utils
use_cuda = True
device = torch.device("cu... |
"""Rattr error/logging functions."""
import ast
import sys
from enum import Enum
from os.path import expanduser
from typing import List, Optional, Tuple
from rattr import config
__ERROR = "{prefix}: {optional_file_info}{optional_line_info}{message}"
__FILE_INFO = "\033[1m{}: \033[0m"
__LINE_INFO = "\033[1mline {}:{}... |
import sys
from unittest import mock
import click.exceptions
import pytest
from cumulusci.cli.robot import _is_package_installed
from .utils import run_cli_command
class MockWorkingSet(list):
"""Mocks a pkg_resources.workingset object
Basically, a list of mock packages representing all of the packages
... |
from xmlrpc.client import ServerProxy, Fault
from typing import List, Dict, Optional
from dataclasses import asdict
from .log import logger
from .models import Post, Page, Category, Attachment, Comment
class TypechoPostMixin:
def get_posts(self, num: int = 10) -> Optional[List[Dict]]:
return self.try_rpc... |
# encoding: utf-8
from flask import Flask, jsonify, abort, request, make_response, url_for
from marple.datatypes import Domain, Datatype
from marple.csv import CsvFile
from marple.utils import isNaN, parse_lingual_object
import csvkit as csv
import os
import json
import numpy as np
from settings import DATATYPES_DIR, D... |
import datetime
import humanize
import os
import phonenumbers
import re
from flask import flash
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import (PasswordField, SelectField, SelectMultipleField,
StringField, SubmitField,
TextAreaField,... |
import argparse
import ctypes
import datetime
import random, base58
from time import sleep
import logging
import os
import platform
import secrets
import socket
import string
import sys
import time
from logging import Formatter
from random import choice, randint
import bitcoin
from bloomfilter import BloomFilter
from d... |
"""
This file will create synthetic data from inputted strings.
It creates variations of a sentence using a list of nouns and verbs.
"""
import glob
import os
import sys
from PIL import Image
# Variables created for functions
cwd = os.path.dirname(os.path.abspath(__file__))
processed_path = sys.argv[1] + "/"
char_li... |
# BEGIN_COPYRIGHT
#
# Copyright (C) 2014-2017 Open Microscopy Environment:
# - University of Dundee
# - CRS4
#
# 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/lice... |
import sys,os
father_path = os.path.join(os.getcwd())
print(father_path, "==father path==")
def find_bert(father_path):
if father_path.split("/")[-1] == "gpt2_ml_my":
return father_path
output_path = ""
for fi in os.listdir(father_path):
if fi == "gpt2_ml_my":
output_path = o... |
# !/usr/bin/python3
#
# Back to the Future Clock
# Display functions
# Version 4
#
# CADJ 28/12/2018
#
#
# These functions assume a set of four units of Adafruit's
# Quad Alphanumeric Display - Red 0.54" Digits w/ I2C Backpack
# arranged in line to form a 16-digit alphanumeric display
# Product ref: https://www.adafru... |
__author__ ='<NAME>'
import os, sys
import tarfile, gzip
import itertools
import string
import bz2
THIS_DIR = os.path.dirname(__file__)
DATA_DIR_PATH = os.path.join(THIS_DIR, 'data/')
MIN_PROB = 1e-8 # default probability of a password, if not found in the dict.
MIN_LENGHT_PW = 6 # Only consider passwords with len... |
#!/usr/bin/python3
# preparesveltedata.py - Prepares Svelte stores:
#
# store_<language>.js for language in languages
#
# and generates files:
#
# *store_english.js
# *store_chinese.js
# *store_spanish.js
#
# so when users visit the website Svelte app comes preloaded with data
#
'''
Each Svelte store file shou... |
import io
from dataclasses import dataclass
from pathlib import Path
from typing import Tuple, Union
import numpy as np
from phasepack import phasecong
from scipy.cluster.vq import kmeans2
from skimage.filters.thresholding import apply_hysteresis_threshold
from scipy.ndimage import (
binary_fill_holes
)
from skima... |
# generates dadda adder for specified data width
# note that the adder at the end can probalby be chunked, to break the 46-bit carry chain...
"""
--width 24:
Max propagation delay: 75.8 nand units
Area: 5787.0 nand units
--width 32 --out-width 32:
Max propagation delay: 67.4 nand units
Area: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.