text
stringlengths
3.07k
12.6k
import os.path from step_project.base_step import Step, StepCollection from common_utils.exceptions import ZCItoolsValueError from common_utils.file_utils import read_fasta_identifiers, write_lines_in_file from common_utils.misc import sets_equal from common_utils.terminal_layout import TableByColumns from ..utils.impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # FSRobo-R Package BSDL # --------- # Copyright (C) 2019 FUJISOFT. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code...
import json import unittest from unittest.mock import patch, Mock from backend.corpora.common.corpora_orm import CollectionVisibility from tests.unit.backend.corpora.api_server.base_api_test import BaseAuthAPITest from tests.unit.backend.corpora.api_server.mock_auth import make_token class TestAuthToken(BaseAuthAPIT...
# A2C algorithm on CartPole env import os import gym import numpy as np import torch as T import torch.nn.functional as F from torch import nn from torch import optim from torch import distributions from utils import models_dir, eps, DenseLayer, try_load_agent, save_agent class Net(nn.Module): ''' Simple...
# How to handle bibliography? BBL, BIB, in-line? import sys import os import re import glob import itertools import argparse import json from jinja2 import Template from termcolor import colored from functools import reduce from TexSoup import TexSoup from collections import OrderedDict, Counter, defaultdict from nltk....
import discord from discord.ext import commands import os import random import re import requests import signal import traceback import urllib.parse import warnings warnings.filterwarnings("ignore") from io import BytesIO from PIL import Image from sympy.solvers import solve as compute from sympy import latex, symbol...
#!/usr/bin/python3 import csv import datetime import matplotlib.pyplot as plt import sys import re args = sys.argv[1:] def iso_to_date(iso): y, m, d = re.match(r'(\d+)-(\d+)-(\d+)', iso).groups() return datetime.date(int(y), int(m), int(d)) def moving_median(v, window=5): e = (window - 1) / 2 mm ...
""" This module handles authentication by the local Django user database, using an interface roughly following the style of Google's oauth2client. In due course, we may be able to use the same flow API to handle diverse forms of third party authentication. """ from __future__ import unicode_literals from __future__ i...
# Copyright (c): <NAME> 2017-2019. # Author: <NAME> # Email: <EMAIL> # Update Date: 2019/4/3 下午5:10 import logging import torch import torch.nn as nn import torch.nn.functional as F from .Model import SuperResolution from .Ops.Blocks import EasyConv2d from .Ops.Motion import CoarseFineFlownet, STN from ..Framewo...
from structfmt import structfmt import unittest class StructFormatTests(unittest.TestCase): def test_without_params(self): fmt = (structfmt.struct_format() .bool() .byte() .bytes() .double() .float() .int8() ...
import tkinter from tkinter import filedialog import math, time import serial import pynmea2 from i2clibraries import i2c_hmc5883l class ROBOT(): def __init__(self): self.lat = 0.0 self.lng = 0.0 self.headingDeg = 0 self.headingMin = 0 port="/dev/serial0" self.ser...
""" Clocks to be used with :class:`aiomas.agent.Container`. All clocks should subclass :class:`BaseClock`. Currently available clock types are: - :class:`AsyncioClock`: a real-time clock synchronized with the :mod:`asyncio` event loop. - :class:`ExternalClock`: a clock that can be set by external tasks / processe...
import logging from typing import Callable, Optional, Sequence, Tuple, Type, Union logger = logging.getLogger(__name__) T_Choices = Union[Type[str], Type[int], Type[float]] T_Validation = Tuple[Callable[[str], bool], str] # (lambda s: True, 'err') class CommandArgument: """Represents one expected argument in ...
from flask import Blueprint, current_app, request from sqlalchemy import desc from standup import csrf, OrderedDict from standup.apps.api.decorators import api_key_required from standup.apps.status.models import Project, Status from standup.apps.users.models import User from standup.database import get_session from sta...
import pandas as pd import datetime import googleapiclient.discovery import pymongo def time_to_time(x): x = datetime.datetime.strptime(x,"%Y-%m-%dT%H:%M:%SZ") new_format = "%Y-%m-%d" x = x.strftime(new_format) return x def youtube_api_connector(dev_key): api_se...
from ctypes import * import numpy as np from OpenGL import GL,GLU def computeFacesAndNormals(v, faceList): # Compute normals faces = np.asarray([v[i] for i in faceList]) va = faces[:,0] vb = faces[:,1] vc = faces[:,2] diffB = vb - va diffC = vc - va vn = np.asarray([np.cross(db,dc) for...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Description: Evaluate & plot time series of (global) forces # Author: <EMAIL> # Created: 2018-01-06 # Execution: Import functions / collections (from cfdPostProcessing.forces import util) # ...
from datamodel.advisory import AdvisoryRecord from datamodel.commit import Commit from ranking.rulescommit.feature_extractor import extract_references_vuln_id from stats.execution import Counter, execution_statistics """ QUICK GUIDE: HOW TO IMPLEMENT A NEW RULE 1. Start by adding an entry to the RULES dictionary in t...
import SimpleITK as sitk import os import numpy as np import re import multiprocessing as mpi from tqdm import * import random import argparse import pandas as pd from typing import Optional, Union import multiprocessing as mpi __all__ = ['recursive_list_dir'] def recursive_list_dir(searchDepth, rootdir): r""" ...
from collections import OrderedDict import numpy as np from scipy.optimize import fsolve # using 23.5 as a default d18o assuming no fractionation # during combustion; actual combustion produces values # lower than this. See Schumacher et al 2008 Atm Chem & Phys Dis def delta13c_constants(): """ Constants for...
# coding:utf-8 from __future__ import absolute_import, unicode_literals, annotations from collections import OrderedDict import graphene import sqlalchemy from flask_sqlalchemy.model import DefaultMeta from graphene import relay from graphene.types.generic import GenericScalar from graphene.types.objecttype import Ob...
#!/usr/bin/python import RPi.GPIO as GPIO import socket import time from rns import ResearchController import timeit import sys import signal import datetime import multiprocessing PUPIL_LED_GPIO = 38 EXTERNAL_MAGNET_GPIO = 40 pupil_led = 0 external_magnet_led = 0 STORE_MSG = b'r' STIM...
import cv2 import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import common as C # Monkey-patch because I trained with a newer version. # This can be removed once PyTorch 0.4.x is out. import torch._utils try: torch._utils._rebuild_tensor_v2 OLD_TORCH = False except At...
import openpyxl, datetime import pandas as pd import PySimpleGUI as sg import numpy as np ## function to return the threshold for an OTU dataframe, returns No Match for No Matches ## also returns a level to group by for later use def get_threshold(df): threshold = df['Similarity'][0] if threshold ==...
import os, warnings import cv2 from PIL import Image # import matplotlib # matplotlib.use('Agg') import matplotlib.pyplot as plt # plt = matplotlib.pyplot import numpy as np def VisualizeImageGrayscale(image_3d, percentile=99, cmap=None): r"""Returns a 3D tensor as a grayscale 2D tensor. This me...
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from itertools import product, count from matplotlib.colors import LinearSegmentedColormap # it produce more vectors pointing diagonally than vectors pointing along # an axis # # generate uniform unit vectors # def generate_unit_vectors(n)...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
""" functions for generating current flow betweenness data from network matrices """ import copy import numpy as np import scipy as sp import pandas as pd import scipy.sparse import time import gc def matLap(mat): if mat.shape[0]>mat.shape[1]: Lmat=copy.deepcopy(-mat.T).astype(float) else: Lmat...
"""Unit tests for the ReplyBuffer class.""" import os import numpy as np from unittest import TestCase from ..prioritized_replay_queue import PrioritizedReplayQueue # the name of the directory housing this module DIR = os.path.dirname(os.path.realpath(__file__)) def ones() -> tuple: """Return an arbitrary state...
from django.contrib import admin from results.models.athletes import Athlete, AthleteInformation from results.models.categories import Category, CategoryForCompetitionType, Division from results.models.competitions import Competition, CompetitionLevel, CompetitionResultType, CompetitionType from results.models.competi...
from typing import TYPE_CHECKING, Optional, Union import os import uuid import abc import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import date2num from pandas.plotting import register_matplotlib_converters import seaborn as sns if TYPE_CHECKING: from .simulator import Simulator, Quantile...
import gym import random import math import time import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Normal from multiprocessing_env import SubprocVecEnv def make_env(): def _thunk(): env = gym.make(env_name) ...
# -*- coding: utf-8 -*- ''' split long seq into small sub_seq, feed sub_seq to lstm ''' from __future__ import division, print_function, absolute_import import tflearn import tflearn.data_utils as du import numpy as np import ReadData import tensorflow as tf from tensorflow.contrib import learn from tensorflow.con...
import sys from os import path from typing import Any, Callable, Dict, List, Tuple, Union from markupsafe import Markup # type: ignore from neutemplates import course from yasss import util def add_prof(name: str, img: str, email: str, web: str, phone: str, oh: str, resources: List[Union[str, Tuple[str, Callable[[s...
from ..pycompiler import Item from ..automata import State from ..utils import ContainerSet def compute_local_first(firsts, alpha): first_alpha = ContainerSet() try: alpha_is_epsilon = alpha.IsEpsilon except: alpha_is_epsilon = False if alpha_is_epsilon: first_alpha.set_epsilo...
""" common stuff for gluing things together and hiding unnecessary complexity """ import random import itertools from collections import deque """ This is a wrapper around osmnx nodes so we can query a single node with questions like that without having to deal with networkx dictionaries: * how did...
"""Backbone networks implementation""" import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from visualdet3d.networks.lib.common import conv1x1, conv3x3, conv7x7 class BasicBlock(layers.Layer): """Pre-activation version of the Basic Block.""" expansion = 1 def __init_...
"""Main class based logic for client app.""" import sys import zlib import json import hashlib import logging from threading import Thread from socket import socket from datetime import datetime from PyQt5.QtWidgets import ( QApplication, QMainWindow, QDesktopWidget, QTextEdit, QPushButton, QVBoxLayout, QHBoxL...
from fpdf import FPDF import time class PDF(FPDF): # Author and Title of every page def nameTitle(self, title, name): self.name = name self.title = title # Page header def header(self): # Logo or logo_path (if needed) self.image('logo.png', 10, 5, 45) # Arial b...
#!/usr/bin/env python3 import json, requests, time, math, argparse debug = False groupName = "Graveyard" offlineLimit = 30 # days def debugDump(label, data): if not debug: return print(label, json.dumps(data, sort_keys=True, indent=4)) class rsHost: _ip = '127.0.0.1' _port = '9092' _auth = ('test', 'tset') ...
""" substitute_finder app views module """ from itertools import chain import logging from django.conf import settings from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator fr...
import io from functools import lru_cache from io import BytesIO from PIL import Image from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.lib.pagesizes import A4 from reportlab.lib.units import mm from reportlab.lib.utils import ImageReader, simpleSplit from reportlab.pdfbase import pdfmetrics from reportl...
#!/usr/bin/python3 import logging import os import sys from PyQt5.QtCore import QSettings, Qt, QTimer, QVariant, QFile from PyQt5.QtGui import QKeySequence from PyQt5.QtWidgets import ( QAction, QApplication, QFileDialog, QFrame, QLabel, QMainWindow, QProgressDialog, ) from analyze.media.sound import SoundFro...
import datetime from watchmen_boot.guid.snowflake import get_surrogate_key from watchmen.pipeline.core.dependency.denpendence_new import Graph, add_edge from watchmen.pipeline.core.dependency.graph.property import Property from watchmen.pipeline.core.dependency.graph.relationship import Relationship from watchmen.pipe...
import argparse import os.path import pickle import random import sys import time from pprint import pprint import oursweeper import ourplayers SEP = ',' min_game_p = 1. def here_comes_a_new_challenger(player_str): if os.path.isfile(f'./Pickles/{player_str}_player.pickle'): pickle_in = open(f'./Pickles/...
import os import logging import json from typing import Union, Dict, Any, List, Set import pandas as pd from dgraphpandas.types import find_dgraph_type, default_dgraph_type from dgraphpandas.config import get_from_config logger = logging.getLogger(__name__) def _strip_id(original: Set[str]) -> Set[str]: temp_c...
from typing import NamedTuple from collections import deque VERBOSE = False with open("../input/day15.txt", 'r') as inputFile: data = inputFile.readlines() class Point(NamedTuple('Point', [('x', int), ('y', int)])): def __add__(self, other): return type(self)(self.x + other.x, self.y + other.y) ...
#################################################################################################### # Copyright (c) 2019. <NAME>, <NAME>, <NAME> # # # # Use of this source code is governed by a BS...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # """ This module is used to download metadata from `grada.cz`. """ # Imports ===================================================================== import httpkie import dhtmlparser from utils import handle_encodnig, get_first_content, ...
from textwrap import dedent import time import random max_field_count = -1 class Game: def __init__(self): self.state = [ [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0]] def copy(self): copie...
#!/Users/bernardroesler/anaconda3/envs/insight/bin/python3 #============================================================================== # File: sorting_algos.py # Created: 07/05/2018, 17:14 # Author: <NAME> # """ Description: Sorting algorithms """ #==========================================================...
#Checkpoint no. 3 #Ablen,Avila,Jamora #So this is our 90% of our project. This Checklists help be more efficient, and save time. #This in turn allows us to focus on more creative activities. It helps us be more specific of what equipment to be used of what type of Hazard may occur in your Workplace. #To complete this...
import argparse import json import pathlib class LoadConfig: @staticmethod def init_config(config_path: str = "/root/data/config.json"): if not pathlib.Path(config_path).is_file(): raise Exception(f"Configuration file not exist: {pathlib.Path(config_path).absolute().resolve()}") wi...
# -*- coding: utf-8 -*- import logging import allel import numpy as np import os from enum import Enum logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class Zygosity(Enum): UNDEFINED = 1 HOM = 2 # HOMOZYGOUS HET = 3 # HETEROZYGOUS class HaplotypeWrapper(object): ...
# Copyright 2020 Kyoto University (<NAME>) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Utility functions for data loader.""" import codecs import random def count_vocab_size(dict_path): vocab_count = 1 # for <blank> with codecs.open(dict_path, 'r', encoding='utf-8') as f: for lin...
import csv from datetime import datetime import re from beancount.core.amount import Amount from beancount.core import data from beancount.core.number import Decimal from beancount.ingest import importer BANKS = ('ING', 'ING-DiBa') FIELDS = ( 'Buchung', 'Valuta', 'Auftraggeber/Empfänger', 'Buchungst...
""" I started writing climacros in Python first but I hit a deadend due to Qt and its inability to let me really intercept the text. I stopped this project and switched to writing it in C++ (c) <NAME> <<EMAIL>> """ import time, os, re import idaapi import idc from ida_kernwin import Choose LOCK_FILENAME = 'cli_...
import logging import warnings import os import pandas as pd from config import startdir, BLACKLIST, bkf_table from xlsparser import GpXlsConfig, GpXlsParser from progressbar import printProgressBar import MySQLdb from db import open_db, close_db logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelnam...
# Copyright 2017 British Broadcasting Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# ---------------------------------------------------------------------------- # # TITLE - util.py # AUTHOR - <NAME> # CONTENTS - IMF functions, Xi <-> r conversion, metallicity conversions # # ---------------------------------------------------------------------------- import numpy as np import scipy.integrate from g...
#!/usr/bin/env python # # CVE notifier - Sends an email alert when new exploits are posted for a given product # For full details, see the included README # import requests import sendgrid import sys import os.path import json import jinja2 class Data(): """ Maintains a JSON list of CVEs which we've heard abo...
import numpy as np import torch from torch import nn from termcolor import cprint def split_data(x, y, rand_seed, ratio): """ split data into two portions. :param x: numpy arr. data, the 1st dimension is number of data. :param y: numpy arr. labels of data x. Could be None for unlabeled data :param...
import os.path from util.helpers import path_to_containers, get_persisted_config_yml_path import yaml # XXX this is weird and should be cleaned up def get_persisted_config(): p_conf = {} if not os.path.isfile(get_persisted_config_yml_path()): return {} with open(get_persisted_config_yml_path(), "...
import cv2 import numpy as np import torch from PIL import Image from collections import OrderedDict import glob from os.path import realpath, join def smooth_l1_loss(bbox_pred, bbox_targets, sigma=3.0): sigma_2 = sigma ** 2 in_box_diff = bbox_pred - bbox_targets abs_in_box_diff = torch.abs(in_box_diff) ...
import hashlib import datetime import json import nacl.signing import nacl.encoding from pyld import jsonld from pyld.jsonld import JsonLdProcessor from jsonpath_ng import jsonpath from jsonpath_ng.ext import parse def issue(credential, signing_key, documentloader=None): """ It signs a credential using Ed25519Si...
import sys import inspect import textwrap from collections import OrderedDict from .collections import AttrDict from ._validation import ( is_int_like, is_float_like, is_list_like ) class ConfigTemplate: """ For help on ConfigTemplate, use ConfigTemplate(help=True) """ def __init__(self, help=Fa...
# Huffman Encoding # Tree-Node Type class Node: def __init__(self, freq): self.left = None self.right = None self.father = None self.freq = freq def isLeft(self): return self.father.left == self # create nodes def createNodes(freqs): return [Node...
import random import numpy as np import torch def get_range_val(value, rnd_type="uniform"): if isinstance(value, (list, tuple, np.ndarray)): if len(value) == 2: if value[0] == value[1]: n_val = value[0] else: orig_type = type(value[0]) ...
import itertools as itt import numpy as np def ndarray_dprime(array0, array1, axis, flip=None, keepdims=False): """ general function to calculate the d prime between two arrays with the same shape. the d prime is calculated in a dimension wise manner but for the specified axis, which is treated a...
""" test maf_transform """ import pytest import transform.mc3.mc3_maf_transform as mc3_maf_transform from bmeg.ioutils import reader import os import contextlib import shutil import json @pytest.fixture def maf_file(request): """ get the full path of the test fixture """ return os.path.join(request.fspat...
# Copyright (C) 2019-2022, <NAME>. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. from typing import Dict, List, Optional, Tuple import torch from torch import Tensor from torchvision.ops.boxes import b...
from PIL import Image, ImageDraw import re import os import shutil from pathlib import Path import sys IMAGE_SIZES = [16, 32, 64, 128, 256] export_path = os.path.join(os.getcwd(), "export") def read_gpl_file(filepath): if os.path.exists(export_path): shutil.rmtree(export_path) os.makedirs(export_path)...
""" OpenMM Interface for Stochastic Normalizing Flows """ import pickle import warnings from ..base import Flow try: from openmmtools.integrators import ThermostatedIntegrator except ImportError: class ThermostatedIntegrator: def __init__(self, *args, **kwargs): raise ImportError("openmm...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
import sqlite3 import re from datetime import datetime global connection, cursor def offer(email,connection, cursor): while 1: try: date = str(input("Provide a date yyyy-mm-dd")) if check_valid("date", date) == True : break except: print("Invali...
from metaflow import conda_base, FlowSpec, IncludeFile, Parameter, step, S3 def plot_prc(precisions, recalls, thresholds): import matplotlib.pyplot as plt plt.plot(thresholds, precisions[:-1], "b--", label="Precision") plt.plot(thresholds, recalls[:-1], "g-", label="Recall") plt.xlabel("Thresholds") ...
import random import json from cyaron import Graph AVAILABLE_CHARS = [chr(ord('a')+i) for i in range(26) ] AVAILABLE_CHARS.extend([chr(ord('A')+i) for i in range(26)]) RANDOM_SEED = 50 N_SMALL_SAMPLE = 15 N_LARGE_SAMPLE = 9 L_SMALL = 100 L_LARGE = 1000 L_BOUDERY = 100000 class Solution: def f...
from cProfile import run from cgitb import grey import imp import math from random import random from time import sleep from turtle import Screen, width from xml.dom.minidom import Element import pygame import random from tic import * #if the game is tie #check it def tie_game( board): for i in range(3): ...
from unittest.mock import patch import pytest from smalld.ratelimit import * class ControllableTime: def __init__(self): self.time = 0 def __call__(self): return self.time def set_to(self, time): self.time = time def make_ratelimit_headers( bucket="default", limit=10, rema...
import cv2 import os from pathlib import Path import argparse ap = argparse.ArgumentParser() ap.add_argument("-i", "--input_folder", type=str, required=True, help="folder to clean similar images") ap.add_argument("-o", "--output_folder", type=str, required=True, help="folder to move si...
""" Created on Thu Nov 9 14:56:02 2017 @author: tomas """ import os import torch import numpy as np import misc.box_utils as box_utils from PIL import Image, ImageDraw from misc.boxIoU import bbox_overlaps np.errstate(divide='ignore', invalid='ignore') def extract_features(model, loader, args): outputs = [] ...
import cv2 as cv import numpy as np from matplotlib import pyplot as plt import math import yaml from pathlib import Path from models.utils import plot_matches, plot_image_pair def read(pathname: str): ''' Read intrinsics from yaml file d = intrinsics dictionary K = intrinsic camera matrix distC...
# -*- coding: utf-8 -*- from typing import Union, List import logging import subprocess import torch import numpy import matplotlib logger = logging.getLogger(__name__) class LRLambda(object): @staticmethod def constant_lr(): return lambda step: 1.0 @staticmethod def constant_lr_with...
#!/usr/bin/env python3 import glob import hashlib import multiprocessing import os import shutil import subprocess import zipfile from pathlib import Path from string import Template import yaml def compute_sig(s): return hashlib.sha256(s.encode("utf-8")).hexdigest() EXPERIMENTAL_ON = os.environ.get("EXPERIME...
import torch import torch.nn.functional as F from torch import nn class _PAMBlock(nn.Module): ''' The basic implementation for self-attention block/non-local block Input/Output: N * C * H * (2*W) Parameters: in_channels : the dimension of the input feature map key_cha...
from __future__ import annotations import enum import struct from spacepackets.cfdp.pdu.header import ( PduHeader, PduType, SegmentMetadataFlag, HasPduHeader, ) from spacepackets.cfdp.definitions import FileSize from spacepackets.cfdp.conf import check_packet_length, PduConfig from spacepackets.log imp...
from storage import db from config import TELEGRAM_API_KEY from memory import Memory, User from functions import get_keyboard, get_group_id, get_inline_keyboard, get_default_inline_keyboard from datetime import datetime, timedelta import asyncio import httpx memory = Memory() async def handle_update(update): data...
#!/usr/bin/env python # coding: utf-8 """ Tests for threaded pipeline """ import itertools as _itertools import logging as _logging import unittest as _unittest import signal as _signal import sys as _sys from paipa import threaded as _threaded from paipa import iterables as _iterables _logging.basicConfig(format='%...
from __future__ import unicode_literals import re from django.core.validators import EMPTY_VALUES from rest_framework.fields import CharField as RestCharField from rest_framework.fields import ChoiceField as RestChoiceField from rest_framework.fields import DateField as RestDateField from rest_framework.fields import...
import copy import re from django.core.mail import EmailMultiAlternatives from django.template import loader from django.template.loader import render_to_string from django.conf import settings from django.utils import translation, timezone from django.utils.module_loading import import_string from django.utils.transla...
import io import os import json import jinja2 from PIL import Image from rdkit.Chem import AllChem, Draw path = os.path.join(os.path.dirname(__file__), "template") def reaction(reactants, products, save_file=None, figure_size=(3, 3), atom_map=False): """ Visualize a chemical reaction. Parameters: ...
# In this script, we will create some basic nlp features. import time notebookstart= time.time() import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os import gc print("Data:\n",os.listdir("../input")) # Models Packages from sklearn import metrics from skl...
# divided work due to time constraints. this uses stand alone functions for the BLS but # they are the same as the BLS methods used in LCAnalysis...we just ran out of time to # format them into a class and THEN run the BLS. So we created both .py files simultaneously import matplotlib.pyplot as plt import numpy as ...
"""Core IO abstractions - reading & writing JSON Lines (https://jsonlines.org/). This module provides `JsonLinesIO`, a simplified stream reader/writer for JSON lines, which also adds support for serializing/deserializing numpy arrays. """ import functools as ft import gzip as gzip_ import json import os import typing...
import os import torch import importlib from pathlib import Path from collections import OrderedDict from lib.config.config import update_config from lib.utils.cmd import parse_args from lib.utils.system import system_setup from lib.utils.utils import create_logger, get_tensorboard from lib.networks.build_...
from ifcb.io.dir import YearsDir, DayDir from ifcb.io.file import newBin from ifcb.io import ADC_EXT import ifcb import re import os.path from cache import cache_obj import calendar import math from ifcb.io.pids import parse_id """Resolution of IFCB global identifiers to local filesystem paths""" class Resolver: ...
import os import re import datetime as DT from typing import List from aiogram import types from dispatcher import bot from config import ( DATE, FILE_EXTENSION, STATIC_FILES ) from models import Note def set_title_category(title: str) -> str: return title.strip().lower() def set_complete_date_note(data: dict...
from datetime import datetime import numpy import tensorflow as tf import time from tensorflow.contrib import slim from tensorflow.python.training.basic_session_run_hooks import CheckpointSaverHook from bayesian_inception import wrap_func from nets import inception_resnet_v2_bayes from preprocessing import preproce...
import os from zipfile import ZipFile import numpy as np import pandas as pd dir_ = os.path.realpath(__file__) dir_ = "/".join(dir_.split("/")[:-1]) def read_responses(contest, duplicates=None): """ Read an experiment response. Parameters ---------- contest : str The filename of a *.csv....
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import re import codecs # import thulac import sys # import jieba def iter_xml(filepath): f = open(filepath, 'r') xml_text = [] for line in f: line = line.rstrip() line = re.sub('<BR/>', "", line) line = re.sub('<BR>', "", line...