text stringlengths 3.07k 12.6k |
|---|
"""
This module provides functions for building and sampling from the posteriors
of Bayesian neural networks of varying widths, depths, and output types
(e.g. regression or classification).
"""
import pymc3 as pm
import numpy as np
import theano
import theano.tensor as tt
from .utils import format_trace
from . import... |
"""BDD100K tracking evaluation with CLEAR MOT metrics."""
import os
from typing import Callable, List, Tuple
import motmetrics as mm
import numpy as np
from PIL import Image
MAX_DET = 100
Files = List[str]
FilesList = List[Files]
FilesFunc = Callable[[Files, Files, float, float], List[mm.MOTAccumulator]]
def parse... |
#!/usr/bin/python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
__all__ = ["LogRecord"]
import re
import textwrap
import typing as t
from pylogview import datefinder
from pylogview.common import (
DELIMETER_PATTERNS,
LOG_BG,
LOG_FG,
LOG_FG_DARK,
LOG_LEVEL,
)
if t.TYPE_CHECKING:
from pylogview.window import Window
class Line:
__slots__ = ["_text", "_... |
import subprocess
import json
import os, shutil
from glob import glob
import argparse
artifacts_file = 'artifacts.json'
working_path = '/tmp/forensics/'
memdump_path = working_path + 'memdump/'
packed_evidence_filename = 'forensics_complete.tar.gz' # Default value if parameter is missing
print("""
//////////////////... |
import statistics
import json
import sys
import os
TEXTTYPES = ['text', 'notes', 'all']
DATASETS = ['train', 'dev', 'test']
MODELS = ['bertje', 'robbert', 'mbert', 'xlmr']
SEEDS = ['seed1', 'seed10', 'seed100']
LABELS = ['LOC', 'LOCderiv', 'ORG', 'PER', 'RELderiv', 'SHP', 'overall']
def init_stats():
stats = {}... |
import os
import sys
import asyncio
import discord
import cool_utils
from cool_utils import Terminal
from discord.ext import commands
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
def env(variable: str):
env = os.getenv(variable)
if env == None:
Terminal.error(f"Environmental variable \"... |
import os
import pathlib
import shutil
import yaml
from mkdocs import config as mkconfig
from mkdocs.commands import build
from typing import List, Dict
def clean_old_files(items_to_delete: List[str], built_docs_path: str, plugin_config: Dict[str, str]) -> None:
"""
Remove the built version selector document... |
""" Data selections for EO Tasks
"""
from collections import OrderedDict
__all__ = ["EoDataSelection"]
class EoDataSelection:
""" Specifies data for an EO Task
Parameters
----------
queryString : `str`
The string used in the 'pipetask' -d query
selectionFunction : `function(expandedData... |
def gen_cmake_command(config):
"""
Generate CMake command.
"""
from autocmake.extract import extract_list
s = []
s.append("\n\ndef gen_cmake_command(options, arguments):")
s.append(' """')
s.append(" Generate CMake command based on options and arguments.")
s.append(' """')
... |
import streamlit as st
import tempfile
import os
from os.path import join
import random
import torch
import numpy as np
import cv2
from model import all_models, get_model
from vector_cv_tools.utils import VideoReader
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu... |
# Copyright 2015 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 django.db import models
from cloudinary.models import CloudinaryField
from django.contrib.auth.models import User
from django.utils import timezone
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator, MaxValueValidator
from django... |
import argparse
import os
from ast import literal_eval
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
import pommerman
from evaluation import constants
from pommerman.dqn import utils
home_directory = os.path.expanduser('~')
result_path = os.path.join(home_directory, 'dev... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.core.display import display, HTML
from scipy.sparse import csr_matrix as sparse_matrix
from sklearn.neighbors import NearestNeighbors
from sklearn.decomposition import TruncatedSVD
def create_X(ratings, n, d, user_key="user", item_k... |
"""
[2015-04-20] Challenge #211 [Easy] The Name Game
Description
If computer programmers had a "patron musician" (if such a thing even exists), it would
surely be the great <NAME>. It is my opinion that in the history of music, not song
has ever come closer to replicating the experience of programming as her 1964 nov... |
import pandas as pd
import numpy as np
import logging
import joblib
import cv2
import argparse
import sys
import os
from typing import Tuple
from termcolor import colored
# Log to file and print to stdout simulteneously
logging.basicConfig(filename='tensor.log',level=logging.DEBUG)
logging.basicConfig(format='%(asct... |
# codewars
# https://www.codewars.com/kata/insert-dashes
'''
Write a function insertDash(num)/InsertDash(int num) that will insert dashes ('-') between each
two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count
zero as an odd number.
insert_dash(454793) ->'4547-9-3'
def l... |
import shutil
import sys
import traceback
from pathlib import Path
from typing import Any, List, NoReturn, Optional, Tuple
import click
import typer
from . import __version__, builder, formatter, generator, logger, parser, updater
from .exceptions import Ops2debError
from .fetcher import DEFAULT_CACHE_DIRECTORY, set_... |
import threading
import time
import ptvsd.daemon
from tests.helpers import socket
from tests.helpers.threading import acquire_with_timeout
class PTVSD(ptvsd.daemon.Daemon):
"""A wrapper around a running "instance" of PTVSD.
"client" and "server" are the two ends of socket that PTVSD uses
to communicate ... |
import numpy as np
## Channel: EEPR4 memory channel and AWGN
class Channel_vit(object):
def __init__(self, channel_machine, dummy_list, ini_state):
self.channel_machine = channel_machine
self.dummy_list = dummy_list
self.ini_state = ini_state
self.len_dummy = self.dummy_lis... |
# Copyright (c) Facebook, Inc. and its affiliates.
from factor_learning.keypoint_prediction.train_utils import _flatten_, _unflatten_, switch_majors, load_checkpoint
from factor_learning.keypoint_prediction.keypoint_detector import KeypointDetector
from factor_learning.dataio.DigitImageTfDataset import DigitImageTfDat... |
from hw_nas_bench_api import HWNASBenchAPI as HWAPI
from hw_nas_bench_api.fbnet_models import FBNet_Infer, OPS, ConvNorm, PRIMITIVES
import argparse
import torch as torch
import numpy as np
import time
import torch.nn as nn
from tqdm import tqdm
import utils
np.random.seed(42)
def get_rand_arch():
return np.rando... |
from PIL import Image
import os
import pickle
import librosa
import librosa.display
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
classes = {
0: "blues",
1: "classical",
2: "country",
3: "disco",
4: "hiphop",
5: "jazz",
6: "metal",
7: "po... |
import naive
import improved
import precise
from tkinter import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def naiveF(saturation, size, root):
global flag
flag = 0
naive.call(saturation, size)
canvas = FigureCanvasTkAgg(n... |
# Algorithms for computer algebra
def eea_lift(a, b, p, l, R):
import Structures.Polynomial
import Structures.IntegersModuleP
IMP = Structures.IntegersModuleP.IntegersModuleP(p)
ZPX = Structures.Polynomial.Polynomial(IMP, 'x')
ZPXtv = ZPX.get_true_value()
Rtv = R.get_true_value()
amodp = ... |
import unittest
from ..base import ScaleException
from ..note import Note
from ..scale import ScaleBase, Scale, MajorScale, MinorScale, DiatonicScale
class TestScaleBase(unittest.TestCase):
def test_has_pitch(self):
sb = ScaleBase('C')
scale_notes = ['C', 'D', 'E', 'F', 'G', 'A', 'B']
n... |
import os, cv2, random
import numpy as np
from keras.models import Sequential
from keras.layers import Input, Dropout, Flatten, Conv2D, MaxPooling2D, Dense, Activation
from keras.optimizers import RMSprop
from keras.callbacks import TensorBoard, Callback, EarlyStopping
import tensorflow as tf
from moxing.framework imp... |
import os
import sys
import click
import shutil
import version
import zipfile
import requests
import tempfile
from pathlib import Path
def setup_deployments(path):
Path(path).mkdir(exist_ok=False, parents=True)
if path.exists():
click.echo(f"\tcreated '{path}'")
else:
click.echo(click.styl... |
import os
import re
import random
import math
import nltk
import pickle
from datetime import datetime as dt
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
'''
Helper functions
'''
# Timestamp
def time():
return '[' + dt.now().strftime("%Y-%m-%d... |
"""
Copyright (c) Hathor Labs and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import hashlib
import re
import struct
from typing import Any, Tuple
import base58
from cryptography.hazmat.primitives.asymmetric import ec
from... |
# Echo client program
import argparse
import glob
# from sample_agents import MyAgent
# from sample_agents import RandomAgent
import os
import random
import socket
import subprocess
import sys
from time import sleep
import matplotlib.pyplot as plt
import numpy as np
from sample_agents import RLAgent
class AgentHand... |
import struct
import random
import posixpath
from typing import Dict, Optional
from contextlib import asynccontextmanager
import trio
import ujson
from trio_websocket import open_websocket_url, WebSocketConnection
from trio_binance import AsyncClient
class StreamName:
def __init__(self, **kwargs):
self.... |
import numpy as np
import scipy as sp
from scipy.sparse.linalg import arpack
############################################################################################################################################
# Defining the function to fit residual covariance and model covariance following van Bergen et al.... |
import numpy as np
import pandas as pd
import tensorflow as tf
import os
import random
import pickle
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential, load_model
from tenso... |
import inspect
import os
import shutil
import tempfile
from pathlib import PurePath
from typing import Optional
import duckdb
import pyarrow as pa
from datasets import Dataset, DatasetInfo, Features
from datasets.arrow_writer import ArrowWriter
from datasets.fingerprint import Hasher, is_caching_enabled
from datasets.... |
#!/usr/bin/env python3
#Coded By GnosticPlayers
import os
import sys
import time
import json
import requests
def clear():
responce = os.system("clear")
def welcome_banner():
print('''
_____ _ _
/ ____| | | |
| | | | _____ ___ __ ___ _... |
from collections import defaultdict
from enum import Enum
from functools import partial
from typing import Any, Callable, DefaultDict, Dict, Iterable, List, Tuple, Type
from click import Command, Context, Option, Parameter
from pydantic import BaseModel, BaseSettings
from pydantic.fields import ModelField
from pydanti... |
import asyncio
import aiounittest
from contextlib import asynccontextmanager
from rsp1570serial.connection import SharedRotelAmpConn, RotelAmpConnConnectionError
from rsp1570serial.emulator import (
make_message_handler,
create_device,
INITIAL_SOURCE,
INITIAL_VOLUME,
)
from serial import SerialException... |
"""Console script for Savify."""
import sys
import re
import datetime
import click
import logging
from . import __version__, __author__
from .types import *
from .utils import PathHolder
from .savify import Savify
from .logger import Logger
from .exceptions import FFmpegNotInstalledError, SpotifyApiCredentialsNotSetEr... |
import matplotlib
# matplotlib.use('Agg')
import hydra
import os
from data.leptin_dset import LeptinValDset
from data.spg_dset import SpgDset
import torch
from torch.utils.data import DataLoader
from unet3d.model import UNet2D
from utils import soft_update_params, pca_project, get_angles, set_seed_everywhere, get_edge_... |
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left # Node
self.right = right # Node
def __eq__(self, other):
"""On redéfinit la fonction d'égalité pour prendre en compte les arbres correctement."""
return (
sel... |
#!/usr/bin/env python3
"""
Run benchmark.yml samples by submitting them to the czid-dev SFN-WDL backend. The invoking session
must have (i) AWS_PROFILE set to an appropriate role to access czid-dev, and (ii) an SSH key able
to clone chanzuckerberg/idseq.
The SFN-WDL runs will use the full databases and the latest -rel... |
import torch
from torch import nn
from einops.layers.torch import Reduce
from .utils import pair
class PreNormResidual(nn.Module):
def __init__(self, dim, fn):
super().__init__()
self.fn = fn
self.norm = nn.LayerNorm(dim)
def forward(self, x):
return self.fn(self.norm(x)) + x
... |
import rdkit as rd
from rdkit import Chem
#from rdkit.Chem import AllChem
#import numpy as np
from collections import Counter
from gensim.models import word2vec
from mol2vec_utils import *
# File to generate numerical features from smiles data and replace
# interaction labels by numerical ones
#
def smiles_to_ECFP(... |
import click
import json
import logging
from pathlib import Path
from tomviz import executor
from .load_data_source import create_read_options, extract_data_path
from .data_source_dependencies import load_dependencies
logger = logging.getLogger('tomviz')
def _create_data_source_options(data_sources):
ids = [x[... |
#!/usr/bin/python
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from mydesign import Ui_MainWindow
from form import Ui_Form
from experiment import Ui_Experiment
from debrief import Ui_Debrief
import random
import csv
import os.path
# data to collect
data = {"age": "",
"gender": "",
"level": ""... |
#!/usr/bin/python
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import warnings
warnings.filterwarnings('ignore')
from pathlib import Path
import argparse
import time
from PIL import ImageDraw
import matplotlib
import matplotlib.pyplot as plt
import tensorflow as tf
from my_net import VggCnnPolicy, VggCnnLstmPo... |
# -*- coding: utf-8 -*-
"""
Preprocessors.
"""
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.externals import joblib
from keras.utils.np_utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
from seqeval.metrics.sequence_labeling import get_entitie... |
from __future__ import print_function
import random
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
... |
#!/usr/bin/env python
#
# Copyright 2010 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 require... |
import numpy as np
import tensorflow as tf
import wave
class SilenceDetector(object):
def __init__(self, threshold=20, bits_per_sample=16):
self.cur_SPL = 0
self.threshold = threshold
self.bits_per_sample = bits_per_sample
self.normal = 2.0 ** (bits_per_sample - 1)
def is_silenc... |
class LLNode:
def __init__(self, value, after=None):
self.value = value
self.after = after
class LinkedList:
def __init__(self, head):
self.head = head
def append(self, value):
if self.head == None:
self.head = LLNode(value)
else:
head = self.head
while head.after != None:
head = head.after
... |
# %% [markdown]
# # Training a binary classifier to identify accounts that are likely
# commercial business vs those that are likely real human users
#
# The goal of this file is to be able to identify which of the followers that I
# selected are commercial followers or otherwise small businesses. This
# corrupts m... |
"""Module dedicated to framework testing."""
import pytest
import typing as t
import numpy as np
from pymfe import _internal
from pymfe.mfe import MFE
from tests.utils import load_xy
GNAME = "framework-testing"
class MFETestClass:
"""Some generic methods for testing the MFE Framework."""
@classmethod
... |
from __future__ import annotations
import pprint
from dataclasses import dataclass
from enum import Enum, auto
from copy import copy
from src.tokenizer import TokenType, Token
class ExprType(Enum):
INVALID = auto()
ANY = auto()
VOID = auto()
NULL = auto()
BOOLEAN = aut... |
import sys
import pytest
from ptera.selfless import (
ABSENT,
ConflictError,
Override,
choose,
default,
override,
selfless,
)
from .common import one_test_per_assert
@selfless
def iceberg(
# The parameter x
x: float,
# The parameter y
y,
):
# The great
# zee
... |
#!/usr/bin/env python3
'''
attachments
===========
Dump all the notes in an ENEX file inside the CDATA sections.
'''
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source co... |
import time
import os
import random
import sqlite3
from sqlite3 import Connection
from typing import List
V100_DB_PATH = "../SQLiteDBs/A4v100.db"
V1K_DB_PATH = "../SQLiteDBs/A4v1k.db"
V10K_DB_PATH = "../SQLiteDBs/A4v10k.db"
V100K_DB_PATH = "../SQLiteDBs/A4v100k.db"
V1M_DB_PATH = "../SQLiteDBs/A4v1M.db"
# Q1: Given a ... |
from django.views.generic import View
from django.http import HttpResponse
from django.http import HttpResponseForbidden
from django.shortcuts import render
from picmodels.models import CPSStaff
from picmodels.forms import CPSStaffImageUploadForm
from picbackend.views.utils import validate_get_request_parameters
from p... |
import csv
import multiprocessing
import sys
import time
from functools import partial
from fuzzywuzzy import fuzz, process
from kbs import KnowledgeBase
from utils import retrieve_annotations
sys.path.append("./")
def find_best_candidate(kb_data, annotation):
"""Find best candidate in KB for given annotation ba... |
#!/usr/bin/env python3.6
from controller import Robot, Motor, PositionSensor, Keyboard, Lidar, Display
import numpy as np
#PLOTTING FUNCTIONS
class Grapher:
def __init__(self, display):
'''
display: The display you wish to use with this.
'''
self.display = display
self.wid... |
from isscloudtools.initialize import get_dropbox_service, get_slack_service
from isscloudtools.dropbox import *
from isscloudtools.slack import slack_upload_image
from xas.file_io import load_binned_df_from_file
from xas.xasproject import XASDataSet
from xas.file_io import load_binned_df_from_file
import numpy as np
fr... |
import os
import re
import yaml
from os import path
_question_type_map = {
"string": "text",
"password": "password",
"boolean": "checkbox",
"int": "number",
"enum": "select",
"service": "text",
"multiline": "textarea"
}
class CatalogTemplate(object):
"""
Represents a template in... |
import uuid
from datetime import timedelta
import pytest
from protoactor.actor.actor import Actor
from protoactor.actor.actor_context import RootContext, AbstractContext
from protoactor.actor.props import Props
from protoactor.router.messages import AbstractHashable, AddRoutee, RemoveRoutee, GetRoutees, BroadcastMess... |
#!/usr/bin/env python
try:
from shlex import quote
except ImportError:
from pipes import quote
import subprocess
import shlex
import datetime
from time import sleep
# import virtkey
import os
def run_cmd(cmd, cwd=None, timeout=None, shell=False):
if shell:
ccmd = cmd
else:
ccm... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from libs.list_of_basestring import ListOfBasestring
from libs.structured_object import StructuredObject
from libs.structured_object import TypedList
class... |
# encoding: utf-8
import sys
import codecs
import traceback
from time import time
class ProgramResult(object):
def __init__(self, retcode, out, err):
self.retcode = retcode
self.out = out
self.err = err
class TestCase(object):
def __init__(self, description, program, check):
... |
"""Converters for batch nomalization layers in Keras
"""
import onnx as O
import numpy as np
import logging
from .base_layer import Layer
from .exceptions import FeatureNotImplemented, OnnxNotSupport
from . import helper
# Logger options and flags
logger = logging.getLogger("onnx-caffe")
logger.setLevel(logging.DEBU... |
# %%
import json
import sys
import os
from datasets import load_dataset
_PATH = '/home/adityasv/multidoc2dial/'
sys.path.append(os.path.join(_PATH)) # noqa: E402 # isort:skip
# %%
val_data = json.load(open(_PATH + 'data/multidoc2dial/multidoc2dial_dial_validation.json','r'))
docs = json.load(open(_PATH + 'data/multi... |
#!/usr/bin/env python
# coding:utf-8
import sys
import os
import re
import time
#patch for ArchLinux: CERTIFICATE_VERIFY_FAILED
try:
import ssl
if hasattr(ssl, "_create_unverified_context") and hasattr(ssl, "_create_default_https_context"):
ssl._create_default_https_context = ssl._create_unverified_co... |
# pylint: disable=R0801
import datetime
from pathlib import Path
from cv19srv.utils import logger
from cv19srv.utils.helper import DateTimeHelper, DatabaseContext
from .base import DataType, Exporter, Location
log = logger.get_logger('history')
class HistoryData(Exporter):
def __init__(self, output_dir: Path):
... |
from __future__ import print_function
import argparse
import math
import os
import random
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torch.nn.functional as F
import numpy as np
import time
import math
from models import *
import cv2
from PIL import Image
import matplotlib.pypl... |
import os
import sys
import time
import numpy as np
import torch
# torch.autograd.set_detect_anomaly(True)
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import OneCycleLR
import torchvision
import torchvision.transforms as transforms
from absolute_pooli... |
"""Create plots for option learning."""
import os
from functools import partial
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from predicators.scripts.analyze_results_directory import create_dataframes, \
get_df_for_entry
pd.options.mode.chained_assignment = None # default='warn'
# plt.... |
# -*- coding: utf-8 -*-
# @File : image_caption/caption_generator.py
# @Info : @ TSMC-SIGGRAPH, 2018/8/27
# @Desc : refer to google/im2txt
# -.-.. - ... -- -.-. .-.. .- -... .---. -.-- ..- .-.. --- -. --. ..-. .- -.
import heapq
import math
import numpy as np
from inference_wrapper import InferenceWrap... |
#!/usr/bin/env python
import os
import random
import logging
import datetime
import flask
from flask import Flask, render_template, request, abort, flash, redirect, url_for
from demotrack.model import Subject, ExpCondition, ensure_tables
from demotrack.utils import random_string, create_random_seed_data
# Note tha... |
import itertools
import re
import typing
from .. import _tl
from .._misc import helpers, utils
from ..types import _custom
from ..types._custom.inputmessage import InputMessage
if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient
async def _replace_with_mention(self: "TelegramClient", entities, i... |
"""
Author: <NAME>
Date: 30th December 2020
Description: Various utils for MUNIT
"""
# TODO: Put scales into loss functions
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_addons as tfa
import shutil
import os
from pathlib import Path
import matplotlib.pyplot ... |
# Copyright 2019 Google LLC. 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... |
#!/usr/bin/env python
# coding: utf-8
# # Part 1:
# In[1]:
import numpy as np
from matplotlib import pylab
import matplotlib.pyplot as plt
# In[2]:
data = 'hygdata_v3.csv'
ID = np.genfromtxt(data, usecols=0, unpack=True, delimiter=',',dtype=int,skip_header=1)
RA, dec, lumen, dist = np.genfromtxt(data, usecols=(... |
import logging
import re
import math
import pandas as pd
import spacy
from nltk.stem import WordNetLemmatizer
from spacy import displacy
from text_to_num import alpha2digit
NUMBER = re.compile(r'-?[\d]+([\.,][\d]+)?([eE][+-]?\d+)?')
ENTITY = re.compile(r'[a-zA-Z_]+[a-zA-Z0-9_\-]*')
URL = re.compile(r"((http|https)\:\... |
__testdata__ = {
"type":1, # 0 for boolean, 1 for numericla, 2 for categorical
"value":[1,2,3],
"name":"sample_ftr",
}
from sklearn.base import TransformerMixin
import pandas as pd
import numpy as np
import seq2ftr.feature_calculators as fc
import logging
class SequenceTransformer(TransformerMixin):
... |
import pytest
from mc10 import c10
import conftest
def test_c10data():
filename = b'HELLO'
start = 0x1234
load = 0x4321
data = bytes([0x11, 0x12, 0x13])
filetype = 0x25
binary_mode = 0x23
continuous_gap_flag = 0x24
c10data = c10.C10Data(filename, start, load, data, filetype, binary_mo... |
#!/usr/bin/python
import os, sys, getpass
# Make sure the script is being run as root
whoami = getpass.getuser()
if whoami != 'root':
print('This script must be run as root')
sys.exit()
else:
print('Running as root... OK')
#
# Config
#
# min/max user ids
UID_MIN = 1500
UID_MAX = 1600
# min/max grou... |
import random
import numpy as np
import pickle
from mynetworks import Deep4Net_origin, ConvClfNet, FcClfNet, EEGNet_v2, ShallowNet_dense
from trte import *
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import Dataset, ConcatDataset, IterableDataset
class BcicDataset_window(Dataset,):
... |
from path import Path
from PIL import Image
import argparse
import os
from multiprocessing.dummy import Pool
def resize_from_obj(img, dest, target_size, keep_aspect_ratio=True,
add_padding=False, resample='BILINEAR', jpg_quality=95):
"""
resizes PIL image object img with resample as resamp... |
#!/usr/bin/env python3
import argparse
from concurrent.futures import ThreadPoolExecutor
import queue as _queue
import logging
import os
from pathlib import Path
import signal
from subprocess import (Popen, PIPE)
import threading
import time
from git import Repo
shutdown_event = threading.Event()
pause_event = thre... |
import json
import random
from operator import itemgetter
# absolutePath = '/home/noidea91/flask_app/'
absolutePath = ''
def randomize(inArray, randomSeed = None, count = None):
tempList = inArray[:]
result = []
if count == None:
count = len(tempList) + 1
for i in range(1, count):
if randomSeed == None:
ra... |
"""
Another module for converting bamtofastq, defaults to writing gzfiles
Accepts only one input file
Includes class for converting paired-end sequencing files to two fastq pipes
Supports SAM, BAM
"""
from argparse import ArgumentParser
from gzip import GzipFile
from os import mkfifo, getcwd, devnull
import os
from o... |
import abc
import numpy as np
import tensorflow as tf
from elasticdl.python.common.constants import DistributionStrategy
from elasticdl.python.common.log_utils import default_logger as logger
from elasticdl.python.common.model_utils import (
restore_model_params_from_checkpoint,
)
from elasticdl.python.elasticdl.... |
import re
import argparse
from glob import glob
import os.path
import pandas as pd
def strip_reaction(reaction):
rx = re.sub(r"2(s\d)", r"\1 + \1", reaction)
strip_s = re.sub(r"s(\d)", r"\1", rx)
strip_r = re.sub(r" ->{r\d} ", "", strip_s)
strip_p = strip_r.replace(" + ", "")
return strip_p
def ... |
import re
import pprint
import html
import random
from . import context
try:
import pygments
import pygments.lexers
import pygments.formatters
except ImportError:
pygments = None
# Dictionary of registered filter functions.
filtermap = {}
# Decorator function for registering filters. A filter fun... |
#!/bin/env python
'''script to produce well-ordered directories of sequence data'''
from __future__ import print_function
import os
import sys
import shutil
import re
# modify this regex to match your files
# group1 should be the condition identifier
# group2 should be the lane identifer
# group3 should be the read
ma... |
# Lint as: python3
"""Callbacks for visualizing input images and predictions of loudness model."""
from typing import List
import tensorflow.compat.v2 as tf
class StepIncrementingCallback(tf.keras.callbacks.Callback):
def on_train_batch_end(self, batch, logs=None):
self.model.step.assign_add(1)
class ImageW... |
#!/usr/bin/env python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
"""
This module acts as an interface between the database storgae for AddOnTraffic
infromation and it... |
"""Collections classes with additional functionality."""
__all__ = ["FrozenDict", "ObservableList", "ObservableDict"]
from collections.abc import Mapping, MutableSequence, MutableMapping
import functools
import operator
class _CollectionWrapper:
"""A class wrapping a collection."""
def __init__(self, data)... |
import argparse
import logging
import os
import re
import time
import zlib
import urllib.request as urllib_request
from contextlib import closing
from multiprocessing import Process, get_logger
from Bio import Entrez
from bs4 import BeautifulSoup
import pandas as pd
import requests
SPECIES_CSV = 'data/bac_dive/speci... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import argparse, ast
DICT, TEXT = 0, 1
parser = argparse.ArgumentParser(description='Trabalho SR | <NAME>')
parser.add_argument('filepaths', nargs=3, help='Inserir entradas na ordem: ratings.jsonl content.jsonl targets.csv')
arg... |
from tensorflow.keras import layers, models
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""
The identity block is the block that has no conv layer at shortcut.
"""
filters1, filters2, filters3 = filters
bn_axis = 3
conv_name_base = 'res' + str(stage) + block + '_branc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.