text stringlengths 3.07k 22.1k |
|---|
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
"""
ANDS link checker.
The link checker supports checking a variety of link types.
Currently supported are links in:
* DOIs
* Registry objects
"""
"""
Control flow is:
main()
process_args()
process_ini_file()
open_db_connection()
do_link_checking()
"""
# Version number. Printed out as part of HELP_TEXT.
V... |
from tdw.controller import Controller
from tdw.tdw_utils import TDWUtils
from tdw.py_impact import PyImpact
from tdw.librarian import ModelLibrarian
from typing import List, Dict
from pathlib import Path
import json
from argparse import ArgumentParser
"""
Create a "Rube Goldberg machine" from a set of object... |
from __future__ import absolute_import
from __future__ import print_function
import os
import argparse
import numpy as np
from datetime import datetime
import pandas as pd
import yaml
import random
random.seed(49297)
from tqdm import tqdm
def process_partition(args, definitions, code_to_group, id_to_group, group_to_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
author: R.Iselin
#add license
This script reads .csv files from a folder, one by one, and stores the X and Y values as pandas series object.
With each file and its set of values, it fits a gaussian onto the data.
The data is artificially made more granular by adding ... |
from ctypes import *
import platform
BME680_SPI_INTF = 0
BME680_I2C_INTF = 1
class bme680_calib_data(Structure):
_fields_ = [
("par_h1", c_uint16),
("par_h2", c_uint16),
("par_h3", c_uint8),
("par_h4", c_uint8),
("par_h5", c_uint8),
("par_h6", c_uint8),
("... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import argparse
import sys
import numpy as np
import os
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import collections
from importlib import reload
reload(sys)
# sys.setdefaultencoding("... |
"""
Utilities
==============
Rate limiter classes.
These are basically callables that when called register that a request was
issued. Depending on how they are configured that may cause a pause or exception
if a rate limit has been exceeded. Obviously it is up to the calling code to ensure
that these callables are i... |
"""This module contains Model implementations that utilize the MPNN model as
their underlying model"""
from argparse import Namespace
from functools import partial
from typing import Iterable, List, NoReturn, Optional, Sequence, Tuple, TypeVar
import numpy as np
from numpy import ndarray
from tqdm import tqdm
import... |
from __future__ import annotations
import re
from collections import abc
from itertools import cycle
from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterable, List,
Optional, Sequence, Tuple)
import matplotlib.pyplot as plt
import numpy as np
from .._doc import copy_func, doc
if TYPE_CHE... |
# Copyright (c) 2020-2021 impersonator.org authors (<NAME> and <NAME>). All rights reserved.
import cv2
import numpy as np
import os
import os.path as osp
from typing import Union, List, Tuple
import platform
import shutil
from iPERCore.tools.utils.filesio.persistence import mkdir
from iPERCore.tools.utils.multimedia... |
"""
Copyright 2019 Google 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 in writing, software
di... |
import cv2
import numpy as np
from win32 import win32gui
import win32ui, win32con, win32api
from directkeys import PressKey, ReleaseKey, MoveMouse, W, A, S, D
Tolerance = 37;
InvalidInt = -100;
def grab_screen(region=None):
hwin = win32gui.GetDesktopWindow()
if region:
left,top... |
import os
import numpy as np
import pandas as pd
#print("Hello from tb_lite")
# https://github.com/tensorflow/tensorboard/
# blob/master/tensorboard/backend/event_processing/event_file_loader.py
import tensorboard.backend.event_processing.event_file_loader as event_file_loader
def pytorch_summary(model):
si... |
"""
Keras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.
The current version maybe only works for TensorFlow backend. Actually it will be straightforward to re-write to TF code.
Adopting to other backends should be easy, but I have not tested this.
Usage:
python capsnet/twodigitc... |
import os
import bpy
import sys
import argparse
import logging
import multiprocessing
import subprocess
import math
import tempfile
from typing import NamedTuple, List
from collections import namedtuple
import time
import json
import traceback
__version__ = '0.0.1'
RenderingOptions = namedtuple(
'RenderingOptions... |
"""
Usage Record parser to convert Usage Records in XML format into Python
dictionaries, which are easier to work with.
Author: <NAME> <<EMAIL>>
Copyright: Nordic Data Grid Facility (2010)
"""
import time
from twisted.python import log
from bart.ext import isodate
from bart.usagerecord import urelements as ur
# d... |
import warnings
from collections.abc import Iterable
from typing import Tuple
import numpy as np
from cadquery import *
from cadquery.occ_impl.shapes import Shape
def get_brep_part_properties(filename: str):
"""Imports a Brep CAD file and returns the contents as a CadQuery Shape
object
Args:
fil... |
"""
Hidden Shift Benchmark Program - Qiskit
"""
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = [ "_common", "_common/qiskit" ]
sys.path[1:1] = [ "../../_common", "../../_common/qiskit" ]
import execute as ex
import metrics as metrics
n... |
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want wi... |
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is referred and derived from project NetworkX,
#
# https://github.com/networkx/networkx/blob/master/networkx/readwrite/adjlist.py
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <N... |
"""Sphinx extension for injecting an unreleased changelog into docs."""
import subprocess # noqa: S404
import sys
from contextlib import suppress as suppress_exceptions
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union
from sphinx.application import ... |
from escnn.gspaces import *
from escnn.nn import FieldType
from escnn.nn import GeometricTensor
from ..equivariant_module import EquivariantModule
import torch.nn.functional as F
import torch
from typing import List, Tuple, Any, Union
import math
__all__ = ["PointwiseAvgPool", "PointwiseAvgPoolAntialiased"]
cl... |
from django.db import models
from market.models import Price
from olympia import amo
tiers = {
'0.00': {'CO': {'currency': 'COP', 'price': '0.00', 'region': 9},
'ES': {'currency': 'EUR', 'price': '0.00', 'region': 8},
'PL': {'currency': 'PLN', 'operator': 1, 'price': '0.00',
... |
import filecmp
import os
import platform
import subprocess
import sys
import time
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as tkmb
import tkinter.scrolledtext as tkst
import PIL.Image
import PIL.ImageTk
from frontend.mod.constants import *
class TestC2E2(tk.Tk):
def __init__(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from argument_BERT.preprocessing import feature_extractor
import numpy as np
import pandas as pd
from nltk.tokenize import sent_tokenize
def add_features(data, has_2=True, bert_emb=None):
"""Extract features from the data.
Input:
has_2: True if arg2 used
... |
import numpy as np
from scipy import io
import pickle
def convert_matlab_training_dataset():
"""
Convert the simulation files from Matlab into a 'standard' form that are used throughout the process,
here specifically the 40 trajectories for training. The function is very specific to the training_d... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 8 19:38:45 2021
@author: <NAME>
"""
import os
import re
import string
from nltk.corpus import stopwords
from sklearn import metrics
import numpy as np
class GlobalDict:
def __init__(self, labels):
self.stop_words = stopwords.words('engli... |
from packaging.version import Version
import pytest
try:
import altair as alt
altair_version = Version(alt.__version__)
except Exception:
alt = None
altair_available = pytest.mark.skipif(alt is None, reason="requires altair")
import numpy as np
from panel.models.vega import VegaPlot
from panel.pane im... |
import math
import torch
import torch.nn as nn
from torch.hub import load_state_dict_from_url
__all__ = [ 'ninasr_b0', 'ninasr_b1', 'ninasr_b2' ]
url = {
'r10f16x2': 'https://github.com/Coloquinte/torchSR/releases/download/v1.0.3/ninasr_b0_x2.pt',
'r10f16x3': 'https://github.com/Coloquinte/torchSR/releases/d... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines
from matplotlib.font_manager import FontProperties
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib
def draw_bars(out_value, features, feature_type, width_separators, width_bar):
"""Draw the ... |
import gym
import numpy as np
import torch
import time
import random
from gym.wrappers import Monitor
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal
import torch.optim as optim
import math
import copy
import warnings
import pybulletgym
from trpo_agent import TRP... |
import time
import uuid
from pathlib import Path
import torch
import numpy as np
import pandas as pd
import sklearn.metrics
from tqdm import tqdm
import libs.commons as commons
import libs.models as models
class EarlyStop:
'''Early stopping monitor for loss minimization'''
def __init__(self, patience=8, to... |
from abc import abstractmethod
import datetime
import logging
from pathlib import Path
from typing import (
Any,
cast,
FrozenSet,
Iterable,
Optional,
Set,
Type,
Tuple,
)
from sqlalchemy.orm import (
relationship,
Session as BaseSession,
)
from sqlalchemy import (
Column,
... |
# Modified from @github: https://github.com/shu-hai/two-stage-VAE-Attention-gate-BraTS2020
from torch.utils.data import Dataset
import numpy as np
import os
import numpy as np
np.random.seed(0)
import random
random.seed(0)
# from random import sample
def validation_sampling(data_list, test_size=0.2):
n = le... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... |
"""
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
import os
import tempfile
im... |
#!/usr/bin/python3
from uuid import uuid4
from time import sleep
import logging
import sys
import dpn_utils.dpn_runner
import dpn_utils.dpn_tools
import threading
LOG_LEVEL = logging.INFO
LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s"
MAIN_LOG_PATH = "./sps_id_collision_test.log"
MODULE_NAME ... |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 requ... |
"""Runs the streamlit app.
Call this file in the terminal (from the `datathon-starter` dir)
via `streamlit run app.py`.
"""
import pandas as pd
import streamlit as st
import missingno as msno
import time
from pandas_profiling import ProfileReport
from streamlit_pandas_profiling import st_profile_report
from typing im... |
# --------------------------------------------------------------------------
# Source: https://gist.github.com/jinglescode/9d9ed6027e62e389e3165b59209e838e
# --------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck... |
from django.http import JsonResponse, HttpResponse
from django.views.generic import View
from app.RoleMethod import get_city
from app.models import *
class SynchronizeAddress(View):
"""
模块: 网络爬取全国地址信息
接口信息:
GET:
None
POST:
None
返回信息:
GET:
sta... |
from sqlalchemy import (
Column, Numeric, Integer, ForeignKey,)
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declared_attr
from glycan_profiling.serialize.analysis import BoundToAnalysis
from glycan_profiling.serialize.chromatogram import (
ChromatogramSolution,
... |
# Copyright (c) 2014 OpenStack Foundation.
# 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... |
from matplotlib import pyplot as plt
import numpy as np
import traj
joint_colors = ['r', 'b', 'g', 'c', 'm', 'y', 'k', 'w']
"""
Plot a 1 dimensional trajectory. Plots position, velocity, acceleration, and jerk versus time
in separate subplots.
Uses the entire provided figure, adding subplots as needed.
"""
def plot_s... |
# Import
import datetime
import json
import random
import time
import urllib
from datetime import timedelta
from typing import Optional
import geopy
import geopy.distance
import pandas as pd
from pyroutelib3 import Router
from shapely.geometry import Polygon, Point
from termcolor import colored
from tqdm import tqdm
... |
import logging as log
import webbrowser
from tkinter import Label as Lbl
from tkinter import Toplevel, Listbox, StringVar, BooleanVar, LabelFrame, TclError, TRUE, FALSE
from tkinter.font import families, Font
from tkinter.ttk import Frame, Label, Button, Scrollbar, Style, Entry, Combobox
import tkfontchooser # file t... |
from gnn_acopf.utils.observers import DefaultObserver
import numpy as np
from gnn_acopf.julia_interface import JuliaInterface
def _create_observer(create_jl=False):
if create_jl:
jl = JuliaInterface()
else:
jl = None
return DefaultObserver(jl)
def _example_casedict():
bus = {
"... |
## Animate fractals from an iterated function system
## by <NAME>
## <EMAIL>
## earlbellinger.com
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from tqdm import tqdm
from easing import easing
from PIL import ImageColor # for rgb
from numba import jit
from joblib import Para... |
#!/usr/bin/python
import os
import time
import tensorflow as tf
from tensorflow import flags
from tensorflow import gfile
from tensorflow import logging
import readers
import utils
import numpy as np
FLAGS = flags.FLAGS
flags.DEFINE_string("feature_names", "rgb", "Name of the feature "
"to use for training.")
flags.... |
import os
import argparse
import sys
import torch
from deepliif.util import util
def create_base_parser():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# basic parameters
parser.add_argument('--dataroot', required=True,
help='path to i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019. <NAME>, <NAME>, <NAME>, #
# <NAME>. All rights reserved. #
# Copyrights licensed under the CC BY 4.0 License. ... |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
# import click #command line interface
#import tkinter for simple gui
from tkinter import filedialog, Tk
#automate the boring stuff
import time, os, sys, re, warnings, shutil
#define localfile system
if not 'nb_dir' in globals():
nb_dir = os.getcwd()
d... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import io
import json
import logging
import re
impo... |
# This file contains the main class of droidbot
# It can be used after AVD was started, app was installed, and adb had been set up properly
# By configuring and creating a droidbot instance,
# droidbot will start interacting with Android in AVD like a human
import logging
import os
import shutil
import subprocess
impor... |
# -*- coding: utf-8 -*-
# 请求地址
# 入口配置
# 2019/02/14 上午11:29 @xndery
import sys
sys.path.append("./sense")
sys.path.append(".")
import configparser
import os,random,time
import datetime
import logging
import shutil,zipfile,hashlib
import uuid,socket,json
from sense.COMMON import AgentCommon
from urllib import request
f... |
# -*- coding: utf-8 -*- #
# Copyright 2021 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 requir... |
#conda environment: conda_mmdetection_deepsort
#command line to run: python3 tools/test_video_live.py configs/masktrack_rcnn_r50_fpn_1x_live_deepsort.py models/MaskTrackRCNN_epoch_12.pth --out outputs/results.pkl
#to update after changes to code ---> !pip install .
# Run full demo for results:
# python3 tools/test_vid... |
#!/usr/bin/python
#Copyright (c) 2014, <NAME> <<EMAIL>>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#* Redistributions of source code must retain the above copyright notice, this
# list of con... |
import logging
import multiprocessing
import time
from concurrent.futures.thread import ThreadPoolExecutor
import pytest
import salt.config
import salt.exceptions
import salt.ext.tornado.gen
import salt.ext.tornado.ioloop
import salt.log.setup
import salt.master
import salt.transport.zeromq
import salt.utils.platform
... |
import time
import itertools
from math import sqrt
from copy import deepcopy
import os
import json
import requests
import numpy as np
import edgeiq
START_TIME = time.time()
def send_data(url, route, json):
try:
url = url + route
requests.post(url=url, json=json)
except:
print("connect... |
import base64
import datetime
import subprocess
import sys
import threading
import time
from pathlib import Path
from xml.etree import ElementTree as ET
import click
import requests
from prettytable import PrettyTable
DATE = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d-%H')
TMP_PATH = Path('./tmp').r... |
from __future__ import annotations
import logging
logger = logging.getLogger(__name__)
import json
import multiprocessing
import os
import subprocess
import typing
from collections import Mapping
from pathlib import Path
from kolibri_app.globals import init_kolibri
from kolibri_app.globals import init_logging
from... |
# Lint as: python3
# Copyright 2020, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
# search.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# A... |
"""Test figures.tasks Daily task functions
# Overview of daily pipeline
Figures daily pipeline collects and aggregates data from Open edX (edx-platform)
into Figures models.
The Figures task functions are Celery tasks. However currently only the top
level task function is called asynchronously.
# Daily pipeline exe... |
import csv
import math
import networkx as nx
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from Objects import *
from parameters import *
from copy import deepcopy
from heapq import heappush, heappop, heapify
import time as t
import sys
sys.setrecursionlimit(10**6)
#Process the input file ... |
"""
This file defines all the presets (roles + rules).
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional
@dataclass
class Preset:
name: str
description: str
roles: List[PresetRole] = field(default_factory=list)
rules: List[PresetRule] = ... |
#!/usr/bin/env python3
# FMA: A Dataset For Music Analysis
# <NAME>, <NAME>, <NAME>, <NAME>, EPFL LTS2.
import os
import sys
import shutil
import pickle
import zipfile
import subprocess as sp
from datetime import datetime
from tqdm import tqdm, trange
import pandas as pd
import utils
TIME = datetime(2017, 4, 1).tim... |
# Imports
import datetime
import logging
import os
import sys
from . import rt
def run(job_obj):
logger = logging.getLogger('BL/RUN')
workdir, rtbldir, blstore = set_directories(job_obj)
pr_repo_loc, repo_dir_str = clone_pr_repo(job_obj, workdir)
bldate = get_bl_date(job_obj, pr_repo_loc)
bldir = f... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from __future__ import absolute_import, unicode_literals
from datetime import datetime
import types
from django.utils import timezone
import pytest
from souvenirs.utils import (adjust_to_calendar_month,
adjust_to_subscription_start,
iter_days, iter_months, iter... |
# -*- coding: utf-8 -*-
import os
import shutil
from pathlib import (
Path
)
from unittest import (
mock
)
from PIL import (
Image
)
from ocrd_models.ocrd_page import OcrdPage
import pytest
from tests.base import (
assets,
main
)
from ocrd.resolver import Resolver
from ocrd_utils import pushd_... |
# Copyright (c) 2020 Institution of Parallel and Distributed System, Shanghai Jiao Tong University
# ServerlessBench is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
# http://license.coscl.org.cn/M... |
'''
@Description:
@version:
@License: MIT
@Author: <NAME>
@Date: 2020-03-22 17:48:05
@LastEditors: <NAME>
@LastEditTime: 2020-03-26 18:35:10
'''
import os
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Layer
class Embedding(Layer):
def __init... |
import os
import time
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from pycocotools import mask as maskUtils
import onnx
import keras2onnx
from mrcnn.config import Config
from mrcnn import model as modellib, utils
ROOT_DIR = os.path.abspath("./")
# Directory to sa... |
"""Helper module to get system related information.
"""
import multiprocessing
import os
import socket
import time
from collections import namedtuple
from treadmill import exc
from treadmill import subproc
if os.name == 'nt':
import platform
import psutil
from .syscall import winapi
else:
from . imp... |
from dal.copo_da import DataFile, Annotation
import pandas
from django.http import HttpResponse
import json
from bson import json_util
from dal.copo_da import TextAnnotation
import numpy as np
from web.apps.web_copo.utils import ajax_handlers
from Bio import Entrez
# how many rows of each sheet should be shown to the ... |
from collections import defaultdict
from datetime import datetime
from distutils.util import strtobool
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from django.db.models import ... |
from enum import Flag, auto
from pathlib import Path
from typing import Optional, Union
import numpy as np
from .chunkbuffer import ChunkBuffer
from .h5utils import open_or_pass_dataset
from .types import File, Dataset, Shape, DType
class BufferPolicy(Flag):
"""
Flag indicating what happens when a TimeSerie... |
'''
Nested dictionary functions.
'''
import itertools
from functools import reduce
from . import sc_utils as scu
__all__ = ['getnested', 'setnested', 'makenested', 'iternested', 'mergenested',
'flattendict', 'search', 'nestedloop']
def makenested(nesteddict, keylist=None, value=None, overwrite=False, ge... |
import io
import json
import pickle
import pprint
from datetime import date
from string import Template
from zipfile import ZipFile
import numpy
import pandas
import sklearn
import scipy
try:
import lightgbm
except ImportError:
lightgbm = None
try:
import xgboost
except ImportError:
xgboost = None
f... |
#!/usr/bin/env python
import configparser
import glob
import os
import sys
import textwrap
from collections import defaultdict
from pathlib import Path
import numpy as np
import pandas as pd
from Bio import SeqIO
from phylofisher import help_formatter, tools
def collect_names(files):
"""
Collect all short n... |
"""
Tests for SuiteResource api.
"""
import json
from tests import case
from tests.case.api.crud import ApiCrudCases
class SuiteResourceTest(ApiCrudCases):
"""Please see the test cases implemented in tests.case.api.ApiCrudCases.
The following abstract methods must be implemented:
- factory(self) ... |
# Copyright (c) 2013-2017 <NAME> et al.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... |
import functools
import pytest
from collections import namedtuple
from pyspark.sql.types import (
StructField,
ArrayType,
BooleanType,
StringType,
LongType,
StructType,
DoubleType,
)
from mozetl.search.aggregates import (
search_aggregates,
search_clients_daily,
explode_search_co... |
# Copyright 2022 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @PROJECT : jupyter_Projects
# @Time : 2018/4/17 10:09
# @Author : <NAME>
# @Mail : <EMAIL>
# @File : learn_utils.py
# @Software: PyCharm
from __future__ import absolute_import, unicode_literals
import sys, os
import tensorflow as tf
import time
sys.path.appen... |
import uuid
import time
import re
from ipaddress import ip_address
from enum import Enum
from datetime import datetime, timezone
from sqlalchemy import Table, Column, PrimaryKeyConstraint, LargeBinary as sqla_binary
from sqlalchemy import Integer, String, MetaData, distinct
from sqlalchemy.dialects.mysql import VARBIN... |
"""empty message
Revision ID: c3a3fa694636
Revises:
Create Date: 2019-02-09 19:06:50.363700
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c3a3fa694636'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
import torch
import torch.nn as nn
from spectral import SpectralNorm
from torch.nn import functional as F
# Channel Attention
class ChannelAttentionModule(nn.Module):
def __init__(self):
super().__init__()
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def ... |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from lmfit import Model, Parameters, minimize, report_fit
from scipy.optimize import curve_fit
from scipy import stats
from utilities.statistical_tests import r_squared_calculator
from GEN_Utils import FileHandling... |
import argparse
import json
import os
from collections import defaultdict
import os.path as osp
import numpy as np
from PIL import Image
from tqdm import tqdm
def parse_args():
"""Use argparse to get command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--task', '-t', choice... |
from flask import Flask, render_template, request, flash ,session,send_file
from database import users, db_init, db
import re
import csv
from werkzeug.utils import secure_filename
from csrlc import replace_csv
import os
import pytesseract
from io import TextIOWrapper
import xlrd
import openpyxl
from openpyxl.utils.cel... |
"""
This module is the main module that contains the smart-alarm system.
What is does is, it extracts information from json files acquired using their corresponding APIs.
We can set alarms, read notifications and we are also able to delete them.
Functions:
hhmm_to_seconds(alarm_time) --
announce(announcement) --
titl... |
"""
This examples show how to train a Bi-Encoder for the MS Marco dataset (https://github.com/microsoft/MSMARCO-Passage-Ranking).
The queries and passages are passed independently to the transformer network to produce fixed sized embeddings.
These embeddings can then be compared using cosine-similarity to find matchin... |
"""
Makes directories with subsets of seismic time or depth images.
For example, the directory with name "subz_401_4_600" contains a
subset of a seismic depth image with 400 samples, 4 m sampling
interval, and the depth of the first sample is 600 m.
Author: <NAME>, Colorado School of Mines
Version: 2009.07.25
"""
from... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
"""
Python implementation of the LiNGAM algorithms.
The LiNGAM Project: https://sites.google.com/site/sshimizu06/lingam
"""
import numbers
import numpy as np
from sklearn.utils import check_array, resample
class BootstrapMixin():
"""Mixin class for all LiNGAM algorithms that implement the method of bootstrapping... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.