function_name stringlengths 1 63 | docstring stringlengths 50 5.89k | masked_code stringlengths 50 882k | implementation stringlengths 169 12.9k | start_line int32 1 14.6k | end_line int32 16 14.6k | file_content stringlengths 274 882k |
|---|---|---|---|---|---|---|
generate_bubblesort | Generates addition data with the given string prefix (i.e. 'train', 'test') and the specified
number of examples.
:param prefix: String prefix for saving the file ('train', 'test')
:param num_examples: Number of examples to generate. | """
generate_data.py
Core script for generating training/test addition data. First, generates random pairs of numbers,
then steps through an execution trace, computing the exact order of subroutines that need to be
called.
"""
import pickle
import numpy as np
from tasks.bubblesort.env.trace import Trace
# MASKED: ... | def generate_bubblesort(prefix, num_examples, debug=False, maximum=10000000000, debug_every=1000):
"""
Generates addition data with the given string prefix (i.e. 'train', 'test') and the specified
number of examples.
:param prefix: String prefix for saving the file ('train', 'test')
:param num_exam... | 15 | 34 | """
generate_data.py
Core script for generating training/test addition data. First, generates random pairs of numbers,
then steps through an execution trace, computing the exact order of subroutines that need to be
called.
"""
import pickle
import numpy as np
from tasks.bubblesort.env.trace import Trace
def genera... |
get_age | Take a datetime and return its "age" as a string.
The age can be in second, minute, hour, day, month or year. Only the
biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will
be returned.
Make sure date is not in the future, or else it won't work. | """Helper methods to handle the time in Home Assistant."""
import datetime as dt
import re
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import pytz
import pytz.exceptions as pytzexceptions
import pytz.tzinfo as pytzinfo
from homeassistant.const import MATCH_ALL
DATE_STR_FORMAT = "%Y-%m-%d"
UTC = ... | def get_age(date: dt.datetime) -> str:
"""
Take a datetime and return its "age" as a string.
The age can be in second, minute, hour, day, month or year. Only the
biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will
be returned.
Make sure date is not in the future, or else ... | 175 | 217 | """Helper methods to handle the time in Home Assistant."""
import datetime as dt
import re
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import pytz
import pytz.exceptions as pytzexceptions
import pytz.tzinfo as pytzinfo
from homeassistant.const import MATCH_ALL
DATE_STR_FORMAT = "%Y-%m-%d"
UTC = ... |
tokenizeChoice | Splits the `choice` into a series of tokens based on
the user's criteria.
If suffix indexing is enabled, the individual tokens
are further broken down and indexed by their suffix offsets. e.g.
'Banana', 'anana', 'nana', 'ana' | import re
import pygtrie as trie # type: ignore
from functools import reduce
__ALL__ = ('PrefixTokenizers', 'PrefixSearch')
class PrefixTokenizers:
# This string here is just an arbitrary long string so that
# re.split finds no matches and returns the entire phrase
ENTIRE_PHRASE = '::gooey/tokenizatio... | def tokenizeChoice(self, choice):
"""
Splits the `choice` into a series of tokens based on
the user's criteria.
If suffix indexing is enabled, the individual tokens
are further broken down and indexed by their suffix offsets. e.g.
'Banana', 'anana', 'nana', 'ana... | 73 | 90 | import re
import pygtrie as trie # type: ignore
from functools import reduce
__ALL__ = ('PrefixTokenizers', 'PrefixSearch')
class PrefixTokenizers:
# This string here is just an arbitrary long string so that
# re.split finds no matches and returns the entire phrase
ENTIRE_PHRASE = '::gooey/tokenizatio... |
list_combinations_generator | Generates combinations for items in the given list.
Args:
modalities: List of modalities available in the dataset.
Returns:
Combinations of items in the given list. | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... | def list_combinations_generator(modalities: list):
"""Generates combinations for items in the given list.
Args:
modalities: List of modalities available in the dataset.
Returns:
Combinations of items in the given list.
"""
modality_combinations = list()
# Itera... | 29 | 53 | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... |
data_combiner | Combines skeleton point information for all actions, all takes, given list of subject ids and given list of
modalities.
Args:
n_actions: Total number of actions in the original dataset.
subject_ids: List of subjects in the current set.
n_takes: Total number of takes in the original dataset.... | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... | def data_combiner(n_actions: int,
subject_ids: list,
n_takes: int,
modalities: list,
skeleton_pose_model: str):
"""Combines skeleton point information for all actions, all takes, given list of subject ids and given list of
modalities.
... | 56 | 121 | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... |
retrieve_hyperparameters | Based on the current_model_name returns a list of hyperparameters used for optimizing the model (if necessary).
Args:
current_model_name: Name of the model currently expected to be trained
Returns:
A dictionary containing the hyperparameter name and the values that will be used to optimize the model | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... | def retrieve_hyperparameters(current_model_name: str):
"""Based on the current_model_name returns a list of hyperparameters used for optimizing the model (if necessary).
Args:
current_model_name: Name of the model currently expected to be trained
Returns:
A dictionary conta... | 146 | 177 | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... |
per_combination_results_export | Exports the metrics_dataframe into a CSV format to the mentioned data_split folder. If the folder does not exist,
then the folder is created.
Args:
combination_name: Name of the current combination of modalities and skeleton pose model.
data_split: Name of the split the subset of the dataset belong... | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... | def per_combination_results_export(combination_name: str,
data_split: str,
metrics_dataframe: pd.DataFrame):
"""Exports the metrics_dataframe into a CSV format to the mentioned data_split folder. If the folder does not exist,
then the folder ... | 293 | 311 | # authors_name = 'Preetham Ganesh'
# project_title = 'Multi Sensor-based Human Activity Recognition using OpenCV and Sensor Fusion'
# email = 'preetham.ganesh2015@gmail.com'
import numpy as np
import os
import pandas as pd
import itertools
import logging
import sklearn.pipeline
from sklearn.metrics import accuracy_sc... |
__init__ | Initialize Generator object.
Args:
batch_size: The size of the batches to generate.
group_method: Determines how images are grouped together (defaults to 'ratio', one of ('none', 'random', 'ratio')).
shuffle_groups: If True, shuffles the groups each epoch.
input_size:
max_objects: | import cv2
import keras
import math
import matplotlib.pyplot as plt
import numpy as np
import random
import warnings
from generators.utils import get_affine_transform, affine_transform
from generators.utils import gaussian_radius, draw_gaussian, gaussian_radius_2, draw_gaussian_2
class Generator(keras.utils.Sequence... | def __init__(
self,
multi_scale=False,
multi_image_sizes=(320, 352, 384, 416, 448, 480, 512, 544, 576, 608),
misc_effect=None,
visual_effect=None,
batch_size=1,
group_method='ratio', # one of 'none', 'random', 'ratio'
s... | 18 | 58 | import cv2
import keras
import math
import matplotlib.pyplot as plt
import numpy as np
import random
import warnings
from generators.utils import get_affine_transform, affine_transform
from generators.utils import gaussian_radius, draw_gaussian, gaussian_radius_2, draw_gaussian_2
class Generator(keras.utils.Sequence... |
group_stat_vars_by_observation_properties | Groups stat vars by their observation schemas.
Groups Stat Vars by their inclusion of StatVar Observation
properties like measurementMethod or Unit.
The current template MCF schema does not support optional values in the
CSV so we must place these stat vars into
different template MCFs and CSVs.
Args:
indicator_c... | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | def group_stat_vars_by_observation_properties(indicator_codes):
""" Groups stat vars by their observation schemas.
Groups Stat Vars by their inclusion of StatVar Observation
properties like measurementMethod or Unit.
The current template MCF schema does not support optional values in the
... | 165 | 216 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
output_csv_and_tmcf_by_grouping | Outputs TMCFs and CSVs for each grouping of stat vars.
Args:
worldbank_dataframe: Dataframe containing all indicators for all
countries.
tmcfs_for_stat_vars: Array of tuples of template MCF,
columns on stat var observations,
indicator codes for that template.
indicator_codes -> Data... | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | def output_csv_and_tmcf_by_grouping(worldbank_dataframe, tmcfs_for_stat_vars,
indicator_codes):
""" Outputs TMCFs and CSVs for each grouping of stat vars.
Args:
worldbank_dataframe: Dataframe containing all indicators for all
countries.
... | 259 | 299 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
request_file | 从远端下载文件, 并构建request.FILES中的uploaded file对象返回.
@param url: 文件url路径, 如http://abc.im/12345.jpg
@return: SimpleUploadedFile object, it is containned by the request.FILES(dictionary-like object) | #coding=utf-8
#
# Created on Apr 23, 2014, by Junn
#
#
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from rest_framework.response import Response as RfResponse
from core import codes
import urllib
import httplib
i... | def request_file(url):
'''从远端下载文件, 并构建request.FILES中的uploaded file对象返回.
@param url: 文件url路径, 如http://abc.im/12345.jpg
@return: SimpleUploadedFile object, it is containned by the request.FILES(dictionary-like object)
'''
if not url:
return
response = requests.get(url)
ret... | 21 | 31 | #coding=utf-8
#
# Created on Apr 23, 2014, by Junn
#
#
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from rest_framework.response import Response as RfResponse
from core import codes
import urllib
... |
send_request | 发起http请求. 执行结果返回响应字符串
@param: The sample parameters format like following:
params = {'token': 'dF0zeqAPWs'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
host = 'fir.im'
port = 80
method = 'GET'
send_url = '/api/v2/app/version/541a7131f?token=dF0zeqBMX... | #coding=utf-8
#
# Created on Apr 23, 2014, by Junn
#
#
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from rest_framework.response import Response as RfResponse
from core import codes
import urllib
import httplib
i... | def send_request(host, send_url, method='GET', port=80, params={}, timeout=30,
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}):
'''发起http请求. 执行结果返回响应字符串
@param: The sample parameters format like following:
params = {'token': 'dF0zeqAP... | 33 | 54 | #coding=utf-8
#
# Created on Apr 23, 2014, by Junn
#
#
import json
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from rest_framework.response import Response as RfResponse
from core import codes
import urllib
... |
send_async_http | 发送一个异步请求至某个特定url,实现失败重试
每一次失败后会延时一段时间再去重试,延时时间由
interval和wait_factor决定
:param session:请求的异步session
:param method:请求方法
:param url:请求url
:param retries:失败重试次数
:param interval:失败后的再次异步请求的延时时长
:param wait_factor:每一次失败后延时乘以这个因子,延长重试等待时间,一般1<wf<2,即延时最多2^retries秒
:param timeout:连接超时时长
:param success_callback:成功回调函数
:param fai... | #coding:utf-8
"""
@author : linkin
@email : yooleak@outlook.com
@date : 2018-11-07
"""
import asyncio
import datetime
# MASKED: send_async_http function (lines 10-64) | async def send_async_http(session,method,url,*,
retries=1,
interval=1,
wait_factor=2,
timeout=30,
success_callback=None,
fail_callback=None,
... | 10 | 64 | #coding:utf-8
"""
@author : linkin
@email : yooleak@outlook.com
@date : 2018-11-07
"""
import asyncio
import datetime
async def send_async_http(session,method,url,*,
retries=1,
interval=1,
wait_factor=2,
... |
_calc_uia | Calculate the UI(a) by providing the labeling history and the majority vote results.
Parameters
----------
oracle_history: dict
The labeling history of an oracle. The key is the index of instance, the value is the
label given by the oracle.
majority_vote_result: dict
The results of majority vote of instan... | """
Pre-defined query strategy for noisy oracles.
In reality, the labels given by human is not always correct. For one hand,
there are some inevitable noise comes from the instrumentation of experimental
setting. On the other hand, people can become distracted or fatigued over time,
introducing variability in the qual... | def _calc_uia(self, oracle_history, majority_vote_result, alpha=0.05):
"""Calculate the UI(a) by providing the labeling history and the majority vote results.
Parameters
----------
oracle_history: dict
The labeling history of an oracle. The key is the index of instance, ... | 498 | 531 | """
Pre-defined query strategy for noisy oracles.
In reality, the labels given by human is not always correct. For one hand,
there are some inevitable noise comes from the instrumentation of experimental
setting. On the other hand, people can become distracted or fatigued over time,
introducing variability in the qual... |
add_node | add node method. Runs basic validation before adding.
:param dict node: dictionary of node's data | """
Copyright 2019 by Adam Lewicki
This file is part of the Game Theory library,
and is released under the "MIT License Agreement". Please see the LICENSE
file that should have been included as part of this package.
"""
import json
# ====================================================================================... | def add_node(self, node: dict):
"""
add node method. Runs basic validation before adding.
:param dict node: dictionary of node's data
"""
# check if it is not overriding existing node
if node.get('id') is not None:
if node['id'] in self._nodes:
... | 84 | 139 | """
Copyright 2019 by Adam Lewicki
This file is part of the Game Theory library,
and is released under the "MIT License Agreement". Please see the LICENSE
file that should have been included as part of this package.
"""
import json
# ====================================================================================... |
get_ann_info | Get COCO annotation by index.
Args:
idx (int): Index of data.
Returns:
dict: Annotation info of specified index. | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... | def get_ann_info(self, idx):
"""Get COCO annotation by index.
Args:
idx (int): Index of data.
Returns:
dict: Annotation info of specified index.
"""
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=[img_id])
... | 51 | 62 | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... |
get_cat_ids | Get COCO category ids by index.
Args:
idx (int): Index of data.
Returns:
list[int]: All categories in the image of specified index. | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... | def get_cat_ids(self, idx):
"""Get COCO category ids by index.
Args:
idx (int): Index of data.
Returns:
list[int]: All categories in the image of specified index.
"""
img_id = self.data_infos[idx]['id']
ann_ids = self.coco.get_ann_ids(img_ids=... | 64 | 75 | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... |
results2json | Dump the detection results to a COCO style json file.
There are 3 types of results: proposals, bbox predictions, mask
predictions, and they have different data types. This method will
automatically recognize the type, and dump them to json files.
Args:
results (list[list | tuple | ndarray]): Testing results of the
... | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... | def results2json(self, results, outfile_prefix):
"""Dump the detection results to a COCO style json file.
There are 3 types of results: proposals, bbox predictions, mask
predictions, and they have different data types. This method will
automatically recognize the type, and dump them ... | 246 | 281 | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... |
format_results | Format the results to json (standard format for COCO evaluation).
Args:
results (list[tuple | numpy.ndarray]): Testing results of the
dataset.
jsonfile_prefix (str | None): The prefix of json files. It includes
the file path and the prefix of filename, e.g., "a/b/prefix".
If not specifie... | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... | def format_results(self, results, jsonfile_prefix=None, **kwargs):
"""Format the results to json (standard format for COCO evaluation).
Args:
results (list[tuple | numpy.ndarray]): Testing results of the
dataset.
jsonfile_prefix (str | None): The prefix of jso... | 307 | 331 | import itertools
import logging
import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from mmdet.core import eval_recalls
from .builder import DATASETS
from... |
startup | Start up Django and Lino.
Optional `settings_module` is the name of a Django settings
module. If this is specified, set the
:envvar:`DJANGO_SETTINGS_MODULE` environment variable.
This is called automatically when a process is invoked by an
*admin command*.
In a document to be tested using :cmd:`doctest` you need to... | # -*- coding: UTF-8 -*-
# Copyright 2002-2019 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""
See :ref:`lino` for non-technical documentation.
The :mod:`lino` package itself is the first plugin for all Lino
applications, added automatically to your :setting:`INSTALLED_APPS`. It defines
no models, but... | def startup(settings_module=None):
"""
Start up Django and Lino.
Optional `settings_module` is the name of a Django settings
module. If this is specified, set the
:envvar:`DJANGO_SETTINGS_MODULE` environment variable.
This is called automatically when a process is invoked by an
*admin com... | 98 | 125 | # -*- coding: UTF-8 -*-
# Copyright 2002-2019 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""
See :ref:`lino` for non-technical documentation.
The :mod:`lino` package itself is the first plugin for all Lino
applications, added automatically to your :setting:`INSTALLED_APPS`. It defines
no models, but... |
last_executed_query | Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used by default, but this method
exists for database backends to provide a better implementation
accordin... | import decimal
from threading import local
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.utils import datetime_safe
from django.utils.importlib import import_module
class BaseDatabaseWrapper(local):
"""
Represents a database connection.
"""
ops = None
def ... | def last_executed_query(self, cursor, sql, params):
"""
Returns a string of the query last executed by the given cursor, with
placeholders replaced with actual values.
`sql` is the raw query containing placeholders, and `params` is the
sequence of parameters. These are used ... | 196 | 215 | import decimal
from threading import local
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.utils import datetime_safe
from django.utils.importlib import import_module
class BaseDatabaseWrapper(local):
"""
Represents a database connection.
"""
ops = None
def ... |
extract_each_layer | This image processing funtion is designed for the OCT image post processing.
It can remove the small regions and find the OCT layer boundary under the specified threshold.
:param image:
:param threshold:
:return: | import os
import scipy.misc as misc
import shutil
import cv2
import Constants
import numpy as np
from skimage import morphology
# MASKED: extract_each_layer function (lines 11-45)
if __name__ == '__main__':
image_path = '/home/jimmyliu/Zaiwang/crop-OCT/train/562.fds/crop-images/' \
'oct202.png... | def extract_each_layer(image, threshold):
"""
This image processing funtion is designed for the OCT image post processing.
It can remove the small regions and find the OCT layer boundary under the specified threshold.
:param image:
:param threshold:
:return:
"""
# convert the output to t... | 11 | 45 | import os
import scipy.misc as misc
import shutil
import cv2
import Constants
import numpy as np
from skimage import morphology
def extract_each_layer(image, threshold):
"""
This image processing funtion is designed for the OCT image post processing.
It can remove the small regions and find the OCT layer... |
classification_report | Create a report on classification statistics.
Parameters
----------
Y_hat : array-like, shape=(n_samples,)
List of data labels.
Y : array-like, shape=(n_samples,)
List of target truth labels.
beta : float, default=1
Strength of recall relative to precision in the F-score.
Returns
-------
rep... | """Classification Report"""
# Authors: Jeffrey Wang
# License: BSD 3 clause
import numpy as np
from sleepens.analysis import multiconfusion_matrix
def calculate_statistics(Y_hat, Y, beta=1, average=None):
"""
Calculate the precisions, recalls, F-beta scores, and
supports for each class in `targets`.
Parameters... | def classification_report(Y_hat, Y, beta=1):
"""
Create a report on classification statistics.
Parameters
----------
Y_hat : array-like, shape=(n_samples,)
List of data labels.
Y : array-like, shape=(n_samples,)
List of target truth labels.
beta : float, default=1
Strength of recall relative to precisio... | 98 | 154 | """Classification Report"""
# Authors: Jeffrey Wang
# License: BSD 3 clause
import numpy as np
from sleepens.analysis import multiconfusion_matrix
def calculate_statistics(Y_hat, Y, beta=1, average=None):
"""
Calculate the precisions, recalls, F-beta scores, and
supports for each class in `targets`.
... |
max_pool_forward_fast | A fast implementation of the forward pass for a max pooling layer.
This chooses between the reshape method and the im2col method. If the pooling
regions are square and tile the input image, then we can use the reshape
method which is very fast. Otherwise we fall back on the im2col method, which
is not much faster than... | import numpy as np
try:
from cs231n.im2col_cython import col2im_cython, im2col_cython
from cs231n.im2col_cython import col2im_6d_cython
except ImportError:
print ('run the following from the cs231n directory and try again:')
print ('python setup.py build_ext --inplace')
print ('You may also need to restart yo... | def max_pool_forward_fast(x, pool_param):
"""
A fast implementation of the forward pass for a max pooling layer.
This chooses between the reshape method and the im2col method. If the pooling
regions are square and tile the input image, then we can use the reshape
method which is very fast. Otherwise we fall ... | 132 | 153 | import numpy as np
try:
from cs231n.im2col_cython import col2im_cython, im2col_cython
from cs231n.im2col_cython import col2im_6d_cython
except ImportError:
print ('run the following from the cs231n directory and try again:')
print ('python setup.py build_ext --inplace')
print ('You may also need to restart yo... |
max_pool_backward_reshape | A fast implementation of the backward pass for the max pooling layer that
uses some clever broadcasting and reshaping.
This can only be used if the forward pass was computed using
max_pool_forward_reshape.
NOTE: If there are multiple argmaxes, this method will assign gradient to
ALL argmax elements of the input rathe... | import numpy as np
try:
from cs231n.im2col_cython import col2im_cython, im2col_cython
from cs231n.im2col_cython import col2im_6d_cython
except ImportError:
print ('run the following from the cs231n directory and try again:')
print ('python setup.py build_ext --inplace')
print ('You may also need to restart yo... | def max_pool_backward_reshape(dout, cache):
"""
A fast implementation of the backward pass for the max pooling layer that
uses some clever broadcasting and reshaping.
This can only be used if the forward pass was computed using
max_pool_forward_reshape.
NOTE: If there are multiple argmaxes, this method wi... | 193 | 221 | import numpy as np
try:
from cs231n.im2col_cython import col2im_cython, im2col_cython
from cs231n.im2col_cython import col2im_6d_cython
except ImportError:
print ('run the following from the cs231n directory and try again:')
print ('python setup.py build_ext --inplace')
print ('You may also need to restart yo... |
parse | Parse value of redis key on redis for encoded HASH, SET types, or
JSON / Protobuf encoded state-wrapped types and prints it
Args:
key: key on redis | #!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... | def parse(self, key: str):
"""
Parse value of redis key on redis for encoded HASH, SET types, or
JSON / Protobuf encoded state-wrapped types and prints it
Args:
key: key on redis
"""
redis_type = self.client.type(key).decode('utf-8')
key_type = k... | 117 | 146 | #!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... |
corrupt | Mostly used for debugging, purposely corrupts state encoded protobuf
in redis, and writes it back to datastore
Args:
key: key on redis | #!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... | def corrupt(self, key):
"""
Mostly used for debugging, purposely corrupts state encoded protobuf
in redis, and writes it back to datastore
Args:
key: key on redis
"""
rand_bytes = random.getrandbits(8)
byte_str = bytes([rand_bytes])
self.... | 148 | 160 | #!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... |
is_since | tests whether a date is on or since another date
Parameters
----------
y : int
the year to be tested
sy : int
the since year
m : int or str
the month to be tested. Optional, defaults to Jan
d : int
the day to be tested. Defaults to 1
sm : int or str
the since month. Optional, defaults to Jan
sd: int
the ... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def is_since(y, sy, m=1, d=1, sm=1, sd=1):
"""
tests whether a date is on or since another date
Parameters
----------
y : int
the year to be tested
sy : int
the since year
m : int or str
the month to be tested. Optional, defaults to Jan
d : int
the day to be test... | 122 | 150 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
is_before | tests whether a date is on or before another date
Parameters
----------
y : int
the year to be tested
by : int
the before year
m : int or str
the month to be tested. Optional, defaults to Dec
d : int
the day to be tested. Defaults to last day of the month
bm : int or str
the before month. Optional, default... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def is_before(y, by, m=12, d=None, bm=12, bd=None):
"""
tests whether a date is on or before another date
Parameters
----------
y : int
the year to be tested
by : int
the before year
m : int or str
the month to be tested. Optional, defaults to Dec
d : int
the day... | 153 | 185 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
is_between | tests whether a date is on or between two other dates
returns true if the target date is between the since date and the before
date, inclusive.
Parameters
----------
y : int
the year to be tested
sy : int
the since year
by : int
the before year
m : int or str
the month to be tested. Optional, defaults to Jan
... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def is_between(y, sy, by, m=1, d=1, sm=1, sd=1, bm=12, bd=None):
"""
tests whether a date is on or between two other dates
returns true if the target date is between the since date and the before
date, inclusive.
Parameters
----------
y : int
the year to be tested
sy : int
... | 188 | 228 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
has_started | true if today is after the dates given, inclusive
Parameters
----------
sy : int
the year to check today against
sm : int or str.
the month to check today against. Should be integer or in regolith MONTHS.
default is 1
sd : int.
the day to check today against. Default is 1
Returns
-------
bool
true if toda... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def has_started(sy, sm=None, sd=None):
"""
true if today is after the dates given, inclusive
Parameters
----------
sy : int
the year to check today against
sm : int or str.
the month to check today against. Should be integer or in regolith MONTHS.
default is 1
sd : int.... | 231 | 256 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
has_finished | true if today is before the dates given, inclusive
Parameters
----------
ey : int
end year, the year to check today against
em : int or str.
end month, the month to check today against. Should be integer or in regolith MONTHS.
default is 1
ed : int.
end-day, the day to check today against. Default is last ... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def has_finished(ey, em=None, ed=None):
"""
true if today is before the dates given, inclusive
Parameters
----------
ey : int
end year, the year to check today against
em : int or str.
end month, the month to check today against. Should be integer or in regolith MONTHS.
def... | 259 | 284 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
group | Group the document in the database according to the value of the doc[by] in db.
Parameters
----------
db : iterable
The database of documents.
by : basestring
The key to group the documents.
Returns
-------
grouped: dict
A dictionary mapping the feature value of group to the list of docs. All docs in the ... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def group(db, by):
"""
Group the document in the database according to the value of the doc[by] in db.
Parameters
----------
db : iterable
The database of documents.
by : basestring
The key to group the documents.
Returns
-------
grouped: dict
A dictionary m... | 801 | 836 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
group_member_ids | Get a list of all group member ids
Parameters
----------
ppl_coll: collection (list of dicts)
The people collection that should contain the group members
grp: string
The id of the group in groups.yml
Returns
-------
set:
The set of ids of the people in the group
Notes
-----
- Groups that are being tracke... | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... | def group_member_ids(ppl_coll, grpname):
"""Get a list of all group member ids
Parameters
----------
ppl_coll: collection (list of dicts)
The people collection that should contain the group members
grp: string
The id of the group in groups.yml
Returns
-------
set:
... | 862 | 895 | """Misc. regolith tools.
"""
import email.utils
import os
import platform
import re
import sys
import time
from copy import deepcopy
from calendar import monthrange
from datetime import datetime, date, timedelta
from regolith.dates import month_to_int, date_to_float, get_dates
from regolith.sorters import doc_date_ke... |
__init__ | Monitor qcodes parameters.
Args:
*parameters: Parameters to monitor.
interval: How often one wants to refresh the values. | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 unga <giulioungaretti@me.com>
#
# Distributed under terms of the MIT license.
"""
Monitor a set of parameters in a background thread
stream output over websocket
To start monitor, run this file, or if qcodes is installed as a module:
... | def __init__(self, *parameters: Parameter, interval: float = 1):
"""
Monitor qcodes parameters.
Args:
*parameters: Parameters to monitor.
interval: How often one wants to refresh the values.
"""
super().__init__()
# Check that all values are ... | 128 | 162 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 unga <giulioungaretti@me.com>
#
# Distributed under terms of the MIT license.
"""
Monitor a set of parameters in a background thread
stream output over websocket
To start monitor, run this file, or if qcodes is installed as a module:
... |
assertDetailedTraceback | Assert that L{printDetailedTraceback} produces and prints a detailed
traceback.
The detailed traceback consists of a header::
*--- Failure #20 ---
The body contains the stacktrace::
/twisted/trial/_synctest.py:1180: _run(...)
/twisted/python/util.py:1076: runWithWarningsSuppressed(...)
--- <exception caught... | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for the L{twisted.python.failure} module.
"""
from __future__ import division, absolute_import
import re
import sys
import traceback
import pdb
import linecache
from twisted.python.compat import _PY3, NativeStringIO
from twisted.... | def assertDetailedTraceback(self, captureVars=False, cleanFailure=False):
"""
Assert that L{printDetailedTraceback} produces and prints a detailed
traceback.
The detailed traceback consists of a header::
*--- Failure #20 ---
The body contains the stacktrace::
... | 180 | 255 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for the L{twisted.python.failure} module.
"""
from __future__ import division, absolute_import
import re
import sys
import traceback
import pdb
import linecache
from twisted.python.compat import _PY3, NativeStringIO
from twisted.... |
assertBriefTraceback | Assert that L{printBriefTraceback} produces and prints a brief
traceback.
The brief traceback consists of a header::
Traceback: <type 'exceptions.ZeroDivisionError'>: float division
The body with the stacktrace::
/twisted/trial/_synctest.py:1180:_run
/twisted/python/util.py:1076:runWithWarningsSuppressed
And... | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for the L{twisted.python.failure} module.
"""
from __future__ import division, absolute_import
import re
import sys
import traceback
import pdb
import linecache
from twisted.python.compat import _PY3, NativeStringIO
from twisted.... | def assertBriefTraceback(self, captureVars=False):
"""
Assert that L{printBriefTraceback} produces and prints a brief
traceback.
The brief traceback consists of a header::
Traceback: <type 'exceptions.ZeroDivisionError'>: float division
The body with the stacktra... | 258 | 300 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for the L{twisted.python.failure} module.
"""
from __future__ import division, absolute_import
import re
import sys
import traceback
import pdb
import linecache
from twisted.python.compat import _PY3, NativeStringIO
from twisted.... |
assertDefaultTraceback | Assert that L{printTraceback} produces and prints a default traceback.
The default traceback consists of a header::
Traceback (most recent call last):
The body with traceback::
File "/twisted/trial/_synctest.py", line 1180, in _run
runWithWarningsSuppressed(suppress, method)
And the footer::
--- <excep... | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for the L{twisted.python.failure} module.
"""
from __future__ import division, absolute_import
import re
import sys
import traceback
import pdb
import linecache
from twisted.python.compat import _PY3, NativeStringIO
from twisted.... | def assertDefaultTraceback(self, captureVars=False):
"""
Assert that L{printTraceback} produces and prints a default traceback.
The default traceback consists of a header::
Traceback (most recent call last):
The body with traceback::
File "/twisted/trial/_sync... | 303 | 349 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Test cases for the L{twisted.python.failure} module.
"""
from __future__ import division, absolute_import
import re
import sys
import traceback
import pdb
import linecache
from twisted.python.compat import _PY3, NativeStringIO
from twisted.... |
add_event_callback | Adds a callback for an event which is called internally by apps.
Args:
name (str): Name of the app.
namespace (str): Namespace of the event.
cb: Callback function.
event (str): Name of the event.
**kwargs: List of values to filter on, and additional arguments to pass to the callback.
Returns:
... | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... | async def add_event_callback(self, name, namespace, cb, event, **kwargs):
"""Adds a callback for an event which is called internally by apps.
Args:
name (str): Name of the app.
namespace (str): Namespace of the event.
cb: Callback function.
event (st... | 28 | 95 | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... |
fire_event | Fires an event.
If the namespace does not have a plugin associated with it, the event will be fired locally.
If a plugin is associated, the firing of the event will be delegated to the plugin, under the
understanding that when the event is fired, the plugin will notify appdaemon that it occurred,
usually via the syste... | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... | async def fire_event(self, namespace, event, **kwargs):
"""Fires an event.
If the namespace does not have a plugin associated with it, the event will be fired locally.
If a plugin is associated, the firing of the event will be delegated to the plugin, under the
understanding that wh... | 146 | 172 | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... |
has_log_callback | Returns ``True`` if the app has a log callback, ``False`` otherwise.
Used to prevent callback loops. In the calling logic, if this function returns
``True`` the resulting logging event will be suppressed.
Args:
name (str): Name of the app. | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... | async def has_log_callback(self, name):
"""Returns ``True`` if the app has a log callback, ``False`` otherwise.
Used to prevent callback loops. In the calling logic, if this function returns
``True`` the resulting logging event will be suppressed.
Args:
name (str): Name... | 255 | 279 | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... |
process_event_callbacks | Processes a pure event callback.
Locate any callbacks that may be registered for this event, check for filters and if appropriate,
dispatch the event for further checking and eventual action.
Args:
namespace (str): Namespace of the event.
data: Data associated with the event.
Returns:
None. | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... | async def process_event_callbacks(self, namespace, data):
"""Processes a pure event callback.
Locate any callbacks that may be registered for this event, check for filters and if appropriate,
dispatch the event for further checking and eventual action.
Args:
namespace (... | 281 | 353 | """Module to handle all events within AppDaemon."""
import uuid
from copy import deepcopy
import traceback
import datetime
from appdaemon.appdaemon import AppDaemon
import appdaemon.utils as utils
class Events:
"""Encapsulate event handling."""
def __init__(self, ad: AppDaemon):
"""Constructor.
... |
send_msg | Find the socket descriptor mapped by workerId and send them a message.
Args:
workerId: UUID string used to identify and retrieve a worker.
message: Message to be send. | import queue
from ..workers import Worker
from ..codes import WORKER_PROPERTIES
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls... | def send_msg(self, workerId: str, message: str):
""" Find the socket descriptor mapped by workerId and send them a message.
Args:
workerId: UUID string used to identify and retrieve a worker.
message: Message to be send.
"""
socket = self.connecti... | 40 | 49 | import queue
from ..workers import Worker
from ..codes import WORKER_PROPERTIES
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls... |
forward | Decode the bbox and do NMS if needed.
Args:
head_out (tuple): bbox_pred and cls_prob of bbox_head output.
rois (tuple): roi and rois_num of rpn_head output.
im_shape (Tensor): The shape of the input image.
scale_factor (Tensor): The scale factor of the input image.
Returns:
bbox_pred (Tensor): The... | # Copyright (c) 2020 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 appli... | def forward(self, head_out, rois, im_shape, scale_factor):
"""
Decode the bbox and do NMS if needed.
Args:
head_out (tuple): bbox_pred and cls_prob of bbox_head output.
rois (tuple): roi and rois_num of rpn_head output.
im_shape (Tensor): The shape of th... | 50 | 72 | # Copyright (c) 2020 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 appli... |
__call__ | Decode the mask_out and paste the mask to the origin image.
Args:
mask_out (Tensor): mask_head output with shape [N, 28, 28].
bbox_pred (Tensor): The output bboxes with shape [N, 6] after decode
and NMS, including labels, scores and bboxes.
bbox_num (Tensor): The number of prediction boxes of each ... | # Copyright (c) 2020 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 appli... | def __call__(self, mask_out, bboxes, bbox_num, origin_shape):
"""
Decode the mask_out and paste the mask to the origin image.
Args:
mask_out (Tensor): mask_head output with shape [N, 28, 28].
bbox_pred (Tensor): The output bboxes with shape [N, 6] after decode
... | 175 | 209 | # Copyright (c) 2020 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 appli... |
forward | Decode the bbox and do NMS for JDE model.
Args:
head_out (list): Bbox_pred and cls_prob of bbox_head output.
anchors (list): Anchors of JDE model.
Returns:
boxes_idx (Tensor): The index of kept bboxes after decode 'JDEBox'.
bbox_pred (Tensor): The output is the prediction with shape [N, 6]
i... | # Copyright (c) 2020 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 appli... | def forward(self, head_out, anchors):
"""
Decode the bbox and do NMS for JDE model.
Args:
head_out (list): Bbox_pred and cls_prob of bbox_head output.
anchors (list): Anchors of JDE model.
Returns:
boxes_idx (Tensor): The index of kept bboxes af... | 363 | 407 | # Copyright (c) 2020 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 appli... |
__call__ | Decode the bbox.
Args:
head_out (tuple): bbox_pred, cls_logit and masks of bbox_head output.
im_shape (Tensor): The shape of the input image.
scale_factor (Tensor): The scale factor of the input image.
Returns:
bbox_pred (Tensor): The output prediction with shape [N, 6], including
labels, score... | # Copyright (c) 2020 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 appli... | def __call__(self, head_out, im_shape, scale_factor):
"""
Decode the bbox.
Args:
head_out (tuple): bbox_pred, cls_logit and masks of bbox_head output.
im_shape (Tensor): The shape of the input image.
scale_factor (Tensor): The scale factor of the input im... | 515 | 570 | # Copyright (c) 2020 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 appli... |
authenticated_view | This view can be used to test requests with an authenticated user. Create a
user with a default username, save it and then use this user to log in.
Always returns a 200. | from django.conf.urls import url
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from django.urls import include, path, re_path
from .. import views
def repath_view(request):
return HttpRes... | def authenticated_view(request):
"""
This view can be used to test requests with an authenticated user. Create a
user with a default username, save it and then use this user to log in.
Always returns a 200.
"""
user = User(username="Jane Doe")
user.save()
login(request, user)
return... | 19 | 29 | from django.conf.urls import url
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from django.urls import include, path, re_path
from .. import views
def repath_view(request):
return HttpRes... |
_handle_mark_groups_arg_for_clustering | Handles the mark_groups=... keyword argument in plotting methods of
clusterings.
This is an internal method, you shouldn't need to mess around with it.
Its purpose is to handle the extended semantics of the mark_groups=...
keyword argument in the C{__plot__} method of L{VertexClustering} and
L{VertexCover} instances, ... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def _handle_mark_groups_arg_for_clustering(mark_groups, clustering):
"""Handles the mark_groups=... keyword argument in plotting methods of
clusterings.
This is an internal method, you shouldn't need to mess around with it.
Its purpose is to handle the extended semantics of the mark_groups=...
keyw... | 1,469 | 1,517 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
__init__ | Constructor.
@param membership: the membership list -- that is, the cluster
index in which each element of the set belongs to.
@param params: additional parameters to be stored in this
object's dictionary. | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def __init__(self, membership, params = None):
"""Constructor.
@param membership: the membership list -- that is, the cluster
index in which each element of the set belongs to.
@param params: additional parameters to be stored in this
object's dictionary."""
self... | 83 | 97 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
sizes | Returns the size of given clusters.
The indices are given as positional arguments. If there are no
positional arguments, the function will return the sizes of all clusters. | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def sizes(self, *args):
"""Returns the size of given clusters.
The indices are given as positional arguments. If there are no
positional arguments, the function will return the sizes of all clusters.
"""
counts = [0] * len(self)
for x in self._membership:
... | 159 | 172 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
summary | Returns the summary of the clustering.
The summary includes the number of items and clusters, and also the
list of members for each of the clusters if the verbosity is nonzero.
@param verbosity: determines whether the cluster members should be
printed. Zero verbosity prints the number of items and clusters only.
@r... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def summary(self, verbosity=0, width=None):
"""Returns the summary of the clustering.
The summary includes the number of items and clusters, and also the
list of members for each of the clusters if the verbosity is nonzero.
@param verbosity: determines whether the cluster members s... | 182 | 207 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
__init__ | Creates a clustering object for a given graph.
@param graph: the graph that will be associated to the clustering
@param membership: the membership list. The length of the list must
be equal to the number of vertices in the graph. If C{None}, every
vertex is assumed to belong to the same cluster.
@param modularity:... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def __init__(self, graph, membership = None, modularity = None, \
params = None, modularity_params = None):
"""Creates a clustering object for a given graph.
@param graph: the graph that will be associated to the clustering
@param membership: the membership list. The length... | 234 | 263 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
recalculate_modularity | Recalculates the stored modularity value.
This method must be called before querying the modularity score of the
clustering through the class member C{modularity} or C{q} if the
graph has been modified (edges have been added or removed) since the
creation of the L{VertexClustering} object.
@return: the new modularity... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def recalculate_modularity(self):
"""Recalculates the stored modularity value.
This method must be called before querying the modularity score of the
clustering through the class member C{modularity} or C{q} if the
graph has been modified (edges have been added or removed) since the... | 374 | 387 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
giant | Returns the giant community of the clustered graph.
The giant component a community for which no larger community exists.
@note: there can be multiple giant communities, this method will return
the copy of an arbitrary one if there are multiple giant communities.
@return: a copy of the giant community.
@preconditio... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def giant(self):
"""Returns the giant community of the clustered graph.
The giant component a community for which no larger community exists.
@note: there can be multiple giant communities, this method will return
the copy of an arbitrary one if there are multiple giant communitie... | 424 | 437 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
_traverse_inorder | Conducts an inorder traversal of the merge tree.
The inorder traversal returns the nodes on the last level in the order
they should be drawn so that no edges cross each other.
@return: the result of the inorder traversal in a list. | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def _traverse_inorder(self):
"""Conducts an inorder traversal of the merge tree.
The inorder traversal returns the nodes on the last level in the order
they should be drawn so that no edges cross each other.
@return: the result of the inorder traversal in a list."""
result ... | 594 | 621 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
format | Formats the dendrogram in a foreign format.
Currently only the Newick format is supported.
Example:
>>> d = Dendrogram([(2, 3), (0, 1), (4, 5)])
>>> d.format()
'((2,3)4,(0,1)5)6;'
>>> d.names = list("ABCDEFG")
>>> d.format()
'((C,D)E,(A,B)F)G;' | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def format(self, format="newick"):
"""Formats the dendrogram in a foreign format.
Currently only the Newick format is supported.
Example:
>>> d = Dendrogram([(2, 3), (0, 1), (4, 5)])
>>> d.format()
'((2,3)4,(0,1)5)6;'
>>> d.names = list("ABC... | 626 | 652 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
sizes | Returns the size of given clusters.
The indices are given as positional arguments. If there are no
positional arguments, the function will return the sizes of all clusters. | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def sizes(self, *args):
"""Returns the size of given clusters.
The indices are given as positional arguments. If there are no
positional arguments, the function will return the sizes of all clusters.
"""
if args:
return [len(self._clusters[idx]) for idx in args]
... | 1,156 | 1,164 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
summary | Returns the summary of the cover.
The summary includes the number of items and clusters, and also the
list of members for each of the clusters if the verbosity is nonzero.
@param verbosity: determines whether the cluster members should be
printed. Zero verbosity prints the number of items and clusters only.
@return... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def summary(self, verbosity=0, width=None):
"""Returns the summary of the cover.
The summary includes the number of items and clusters, and also the
list of members for each of the clusters if the verbosity is nonzero.
@param verbosity: determines whether the cluster members should... | 1,174 | 1,198 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
__init__ | Creates a cover object for a given graph.
@param graph: the graph that will be associated to the cover
@param clusters: the list of clusters. If C{None}, it is assumed
that there is only a single cluster that covers the whole graph. | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def __init__(self, graph, clusters = None):
"""Creates a cover object for a given graph.
@param graph: the graph that will be associated to the cover
@param clusters: the list of clusters. If C{None}, it is assumed
that there is only a single cluster that covers the whole graph.
... | 1,221 | 1,236 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
__init__ | Constructs a new cohesive block structure for the given graph.
If any of I{blocks}, I{cohesion} or I{parent} is C{None}, all the
arguments will be ignored and L{Graph.cohesive_blocks()} will be
called to calculate the cohesive blocks. Otherwise, these three
variables should describe the *result* of a cohesive block st... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def __init__(self, graph, blocks = None, cohesion = None, parent = None):
"""Constructs a new cohesive block structure for the given graph.
If any of I{blocks}, I{cohesion} or I{parent} is C{None}, all the
arguments will be ignored and L{Graph.cohesive_blocks()} will be
called to ca... | 1,360 | 1,389 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
__plot__ | Plots the cohesive block structure to the given Cairo context in
the given bounding box.
Since a L{CohesiveBlocks} instance is also a L{VertexCover}, keyword
arguments accepted by L{VertexCover.__plot__()} are also accepted here.
The only difference is that the vertices are colored according to their
maximal cohesions... | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... | def __plot__(self, context, bbox, palette, *args, **kwds):
"""Plots the cohesive block structure to the given Cairo context in
the given bounding box.
Since a L{CohesiveBlocks} instance is also a L{VertexCover}, keyword
arguments accepted by L{VertexCover.__plot__()} are also accept... | 1,440 | 1,467 | # vim:ts=4:sw=4:sts=4:et
# -*- coding: utf-8 -*-
"""Classes related to graph clustering.
@undocumented: _handle_mark_groups_arg_for_clustering, _prepare_community_comparison"""
__license__ = u"""
Copyright (C) 2006-2012 Tamás Nepusz <ntamas@gmail.com>
Pázmány Péter sétány 1/a, 1117 Budapest, Hungary
This program is... |
minute_timedeltas_wrt_first | Converts a list of datetime objects into a list of minute time deltas with respect to the first item.
For example, given the input datetime_lst:
[
'2019-08-22 14:32',
'2019-08-22 14:38',
'2019-08-22 14:42',
'2019-08-22 14:52',
'2019-08-22 14:57'
],
the result would be:
[32, 38, 42, 52, 57]
:param d... | from datetime import datetime, timedelta
from typing import Callable
def create_batch_list(n_batches: int) -> list:
return list(map(lambda x: x, range(1, n_batches + 1)))
def create_batch_dictionary(batch_lst: list, duration_lst: list, expected_finish_lst: list) -> dict:
batch_dict = {batch_lst[i]: (duratio... | def minute_timedeltas_wrt_first(datetime_lst: list) -> list:
"""
Converts a list of datetime objects into a list of minute time deltas with respect to the first item.
For example, given the input datetime_lst:
[
'2019-08-22 14:32',
'2019-08-22 14:38',
'2019-08-22 14:42',
... | 75 | 96 | from datetime import datetime, timedelta
from typing import Callable
def create_batch_list(n_batches: int) -> list:
return list(map(lambda x: x, range(1, n_batches + 1)))
def create_batch_dictionary(batch_lst: list, duration_lst: list, expected_finish_lst: list) -> dict:
batch_dict = {batch_lst[i]: (duratio... |
_build_top_model | Build Top Model
Build the fully connected layers of the network.
Parameters
----------
input_shape : tuple
Input data shape
dense_output : tuple, optional
Size of dense output layers, default is (256, 1024)
dropout : float, optional
Dropout rate, default is 0.1
Returns
-------
keras.model
Fully conne... | # -*- coding: utf-8 -*-
""" NETWORK
This module defines the BlendHunter class which can be used to retrain the
network or use predefined weights to make predictions on unseen data.
:Author: Samuel Farrens <samuel.farrens@cea.fr>
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns... | @staticmethod
def _build_top_model(input_shape, dense_output=(256, 1024), dropout=0.1):
""" Build Top Model
Build the fully connected layers of the network.
Parameters
----------
input_shape : tuple
Input data shape
dense_output : tuple, optional
... | 303 | 332 | # -*- coding: utf-8 -*-
""" NETWORK
This module defines the BlendHunter class which can be used to retrain the
network or use predefined weights to make predictions on unseen data.
:Author: Samuel Farrens <samuel.farrens@cea.fr>
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns... |
__init_subclass__ | An __init_subclass__ hook initializes all of the subclasses of a given class.
So for each subclass, it will call this block of code on import.
This replicates some metaclass magic without the need to be aware of metaclasses.
Here we use this to register each subclass in a dict that has the `is_datasource_for`
attribute... | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def __init_subclass__(cls, **kwargs):
"""
An __init_subclass__ hook initializes all of the subclasses of a given class.
So for each subclass, it will call this block of code on import.
This replicates some metaclass magic without the need to be aware of metaclasses.
Here we u... | 80 | 90 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
quantity | Return a `~astropy.units.quantity.Quantity` for the given column.
Parameters
----------
colname : `str`
The heading of the column you want output.
Returns
-------
quantity : `~astropy.units.quantity.Quantity` | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def quantity(self, colname, **kwargs):
"""
Return a `~astropy.units.quantity.Quantity` for the given column.
Parameters
----------
colname : `str`
The heading of the column you want output.
Returns
-------
quantity : `~astropy.units.quant... | 150 | 165 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
plot | Plot a plot of the time series
Parameters
----------
axes : `~matplotlib.axes.Axes` or None
If provided the image will be plotted on the given axes. Otherwise
the current axes will be used.
**plot_args : `dict`
Any additional plot arguments that should be used
when plotting.
Returns
-------
axes : `~... | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def plot(self, axes=None, **plot_args):
"""Plot a plot of the time series
Parameters
----------
axes : `~matplotlib.axes.Axes` or None
If provided the image will be plotted on the given axes. Otherwise
the current axes will be used.
**plot_args : `di... | 367 | 392 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
_validate_meta | Validates the meta-information associated with a TimeSeries.
This method includes very basic validation checks which apply to
all of the kinds of files that SunPy can read. Datasource-specific
validation should be handled in the relevant file in the
sunpy.timeseries.sources package.
Allows for default unit assignment... | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def _validate_meta(self):
"""
Validates the meta-information associated with a TimeSeries.
This method includes very basic validation checks which apply to
all of the kinds of files that SunPy can read. Datasource-specific
validation should be handled in the relevant file in... | 424 | 445 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
_validate_units | Validates the astropy unit-information associated with a TimeSeries.
This method includes very basic validation checks which apply to
all of the kinds of files that SunPy can read. Datasource-specific
validation should be handled in the relevant file in the
sunpy.timeseries.sources package.
Allows for default unit as... | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def _validate_units(self, units, **kwargs):
"""
Validates the astropy unit-information associated with a TimeSeries.
This method includes very basic validation checks which apply to
all of the kinds of files that SunPy can read. Datasource-specific
validation should be handl... | 447 | 470 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
_sanitize_units | Sanitises the collections.OrderedDict used to store the units.
Primarily this method will:
Remove entries that don't match up to a column,
Add unitless entries for columns with no units defined.
Re-arrange the order of the dictionary to match the columns. | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def _sanitize_units(self, **kwargs):
"""
Sanitises the collections.OrderedDict used to store the units.
Primarily this method will:
Remove entries that don't match up to a column,
Add unitless entries for columns with no units defined.
Re-arrange the order of the dic... | 472 | 495 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
_sanitize_metadata | Sanitises the TimeSeriesMetaData object used to store the metadata.
Primarily this method will:
Remove entries outside of the datas TimeRange or truncate TimeRanges
if the metadata overflows past the data,
Remove column references in the metadata that don't match to a column
in the data.
Remove metadata entries that h... | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def _sanitize_metadata(self, **kwargs):
"""
Sanitises the TimeSeriesMetaData object used to store the metadata.
Primarily this method will:
Remove entries outside of the datas TimeRange or truncate TimeRanges
if the metadata overflows past the data,
Remove column ref... | 497 | 515 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
__eq__ | Check two TimeSeries objects are the same, they have matching type, data,
metadata and units entries.
Parameters
----------
other : `~sunpy.timeseries.GenericTimeSeries`
The second TimeSeries object to compare with.
Returns
-------
result : `bool` | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | def __eq__(self, other):
"""
Check two TimeSeries objects are the same, they have matching type, data,
metadata and units entries.
Parameters
----------
other : `~sunpy.timeseries.GenericTimeSeries`
The second TimeSeries object to compare with.
R... | 576 | 598 | """
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... |
find_T_bit_to_right_of | Returns position of 1 (True) bit immediately to the right of
position bpos. Returns -1 if there is no such bit.
Parameters
----------
bpos : int
bit position
Returns
-------
int |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... | def find_T_bit_to_right_of(self, bpos):
"""
Returns position of 1 (True) bit immediately to the right of
position bpos. Returns -1 if there is no such bit.
Parameters
----------
bpos : int
bit position
Returns
-------
int
... | 151 | 182 |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... |
find_T_bit_to_left_of | Returns position of 1 (True) bit immediately to the left of position
bpos. Returns -1 if there is no such bit.
Parameters
----------
bpos : int
bit position
Returns
-------
int |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... | def find_T_bit_to_left_of(self, bpos):
"""
Returns position of 1 (True) bit immediately to the left of position
bpos. Returns -1 if there is no such bit.
Parameters
----------
bpos : int
bit position
Returns
-------
int
"... | 184 | 215 |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... |
get_bit_string | Returns self represented as string of length self.len of ones and
zeros. If bit_str is the output, [int(x) for x in bit_str] will turn
result to list of ints.
Returns
-------
str |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... | def get_bit_string(self):
"""
Returns self represented as string of length self.len of ones and
zeros. If bit_str is the output, [int(x) for x in bit_str] will turn
result to list of ints.
Returns
-------
str
"""
bit_str = ''
for beta... | 249 | 266 |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... |
lazy_advance | This method takes int "old_lazy" (which corresponds to bit vector
"old_normal"), and changes it to the next lazy int, "new_lazy" (
which corresponds to "new_normal").
example:
lazy sequence: 000, 001, 011, 010, 110, 111, 101, 100
old_lazy = 011
old_normal = 2 = 010
new_normal = 3 = 011
mask = (new_normal & ~old_nor... |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... | @staticmethod
def lazy_advance(old_normal, old_lazy):
"""
This method takes int "old_lazy" (which corresponds to bit vector
"old_normal"), and changes it to the next lazy int, "new_lazy" (
which corresponds to "new_normal").
example:
lazy sequence: 000, 001, 011... | 346 | 377 |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... |
__init__ | Creates an instance of this class.
Arguments:
sol_dim (int): The dimensionality of the problem space
max_iters (int): The maximum number of iterations to perform during optimization
popsize (int): The number of candidate solutions to be sampled at every iteration
num_elites (int): The number of top solu... | import os
import os.path as osp
import pickle
import random
from collections import deque
from datetime import datetime
import gym
import numpy as np
import scipy.stats as stats
import torch
import torch.optim as optim
from mpi4py import MPI
import dr
from dr.ppo.models import Policy, ValueNet
from dr.ppo.train impor... | def __init__(self, sol_dim, max_iters, popsize, num_elites, cost_function,
upper_bound=None, lower_bound=None, epsilon=0.001, alpha=0.25, viz_dir=None):
"""Creates an instance of this class.
Arguments:
sol_dim (int): The dimensionality of the problem space
ma... | 35 | 65 | import os
import os.path as osp
import pickle
import random
from collections import deque
from datetime import datetime
import gym
import numpy as np
import scipy.stats as stats
import torch
import torch.optim as optim
from mpi4py import MPI
import dr
from dr.ppo.models import Policy, ValueNet
from dr.ppo.train impor... |
plotfft | This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether the plot is done or not.
Returns
-------
f: array-like
the frequency values (x... | import pylab as pl
import numpy as np
from os import path
from numpy import abs, linspace, sin, pi, int16
import pandas
# MASKED: plotfft function (lines 8-33)
def synthbeats2(duration, meanhr=60, stdhr=1, samplingfreq=250):
#Minimaly based on the parameters from:
#http://physionet.cps.unizar.es/physiotools... | def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether t... | 8 | 33 | import pylab as pl
import numpy as np
from os import path
from numpy import abs, linspace, sin, pi, int16
import pandas
def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: ar... |
decorated_function | Decorator to check if the user is allowed access to the app.
If user is allowed, return the decorated function.
Otherwise, return an error page with corresponding message. | # -*- coding: utf-8 -*-
import json
import logging
from collections import defaultdict
from functools import wraps
from logging.config import dictConfig
from subprocess import call
import redis
import requests
from flask import Flask, Response, redirect, render_template, request, session, url_for
from flask_migrate im... | @wraps(f)
def decorated_function(*args, **kwargs):
"""
Decorator to check if the user is allowed access to the app.
If user is allowed, return the decorated function.
Otherwise, return an error page with corresponding message.
"""
canvas_user_id = session.get("can... | 53 | 90 | # -*- coding: utf-8 -*-
import json
import logging
from collections import defaultdict
from functools import wraps
from logging.config import dictConfig
from subprocess import call
import redis
import requests
from flask import Flask, Response, redirect, render_template, request, session, url_for
from flask_migrate im... |
get_moon_j2000 | Code to determine the apparent J2000 position for a given
time and at a given position for the observatory.
epoch needs to be a datetime or Time object.
position is a list/tuple of X/Y/Z positions | from datetime import datetime
from astropy.time import Time
def read_tle_file(tlefile, **kwargs):
"""
Read in a TLE file and return the TLE that is closest to the date you want to
propagate the orbit to.
"""
times = []
line1 = []
line2 = []
from os import path
from datetim... | def get_moon_j2000(epoch, line1, line2, position = None):
'''
Code to determine the apparent J2000 position for a given
time and at a given position for the observatory.
epoch needs to be a datetime or Time object.
position is a list/tuple of X/Y/Z positions
'''
from... | 138 | 173 | from datetime import datetime
from astropy.time import Time
def read_tle_file(tlefile, **kwargs):
"""
Read in a TLE file and return the TLE that is closest to the date you want to
propagate the orbit to.
"""
times = []
line1 = []
line2 = []
from os import path
... |
check_or_get_class | Returns the class and checks if the class inherits :attr:`superclass`.
Args:
class_or_name: Name or full path to the class, or the class itself.
module_paths (list, optional): Paths to candidate modules to search
for the class. This is used if :attr:`class_or_name` is a string and
the class can... | # Copyright 2018 The Texar 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 applicable ... | def check_or_get_class(class_or_name, module_path=None, superclass=None):
"""Returns the class and checks if the class inherits :attr:`superclass`.
Args:
class_or_name: Name or full path to the class, or the class itself.
module_paths (list, optional): Paths to candidate modules to search
... | 146 | 175 | # Copyright 2018 The Texar 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 applicable ... |
get_class | Returns the class based on class name.
Args:
class_name (str): Name or full path to the class.
module_paths (list): Paths to candidate modules to search for the
class. This is used if the class cannot be located solely based on
`class_name`. The first module in the list that contains the class
... | # Copyright 2018 The Texar 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 applicable ... | def get_class(class_name, module_paths=None):
"""Returns the class based on class name.
Args:
class_name (str): Name or full path to the class.
module_paths (list): Paths to candidate modules to search for the
class. This is used if the class cannot be located solely based on
... | 178 | 214 | # Copyright 2018 The Texar 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 applicable ... |
check_or_get_instance | Returns a class instance and checks types.
Args:
ins_or_class_or_name: Can be of 3 types:
- A class to instantiate.
- A string of the name or full path to a class to instantiate.
- The class instance to check types.
kwargs (dict): Keyword arguments for the class construc... | # Copyright 2018 The Texar 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 applicable ... | def check_or_get_instance(ins_or_class_or_name, kwargs, module_paths=None,
classtype=None):
"""Returns a class instance and checks types.
Args:
ins_or_class_or_name: Can be of 3 types:
- A class to instantiate.
- A string of the name or full path to a ... | 217 | 253 | # Copyright 2018 The Texar 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 applicable ... |
get_instance | Creates a class instance.
Args:
class_or_name: A class, or its name or full path to a class to
instantiate.
kwargs (dict): Keyword arguments for the class constructor.
module_paths (list, optional): Paths to candidate modules to
search for the class. This is used if the class cannot be
... | # Copyright 2018 The Texar 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 applicable ... | def get_instance(class_or_name, kwargs, module_paths=None):
"""Creates a class instance.
Args:
class_or_name: A class, or its name or full path to a class to
instantiate.
kwargs (dict): Keyword arguments for the class constructor.
module_paths (list, optional): Paths to cand... | 256 | 293 | # Copyright 2018 The Texar 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 applicable ... |
check_or_get_instance_with_redundant_kwargs | Returns a class instance and checks types.
Only those keyword arguments in :attr:`kwargs` that are included in the
class construction method are used.
Args:
ins_or_class_or_name: Can be of 3 types:
- A class to instantiate.
- A string of the name or module path to a class to instant... | # Copyright 2018 The Texar 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 applicable ... | def check_or_get_instance_with_redundant_kwargs(
ins_or_class_or_name, kwargs, module_paths=None, classtype=None):
"""Returns a class instance and checks types.
Only those keyword arguments in :attr:`kwargs` that are included in the
class construction method are used.
Args:
ins_or_clas... | 296 | 334 | # Copyright 2018 The Texar 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 applicable ... |
get_instance_with_redundant_kwargs | Creates a class instance.
Only those keyword arguments in :attr:`kwargs` that are included in the
class construction method are used.
Args:
class_name (str): A class or its name or module path.
kwargs (dict): A dictionary of arguments for the class constructor. It
may include invalid arguments which w... | # Copyright 2018 The Texar 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 applicable ... | def get_instance_with_redundant_kwargs(
class_name, kwargs, module_paths=None):
"""Creates a class instance.
Only those keyword arguments in :attr:`kwargs` that are included in the
class construction method are used.
Args:
class_name (str): A class or its name or module path.
k... | 337 | 372 | # Copyright 2018 The Texar 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 applicable ... |
get_function | Returns the function of specified name and module.
Args:
fn_or_name (str or callable): Name or full path to a function, or the
function itself.
module_paths (list, optional): A list of paths to candidate modules to
search for the function. This is used only when the function
cannot be l... | # Copyright 2018 The Texar 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 applicable ... | def get_function(fn_or_name, module_paths=None):
"""Returns the function of specified name and module.
Args:
fn_or_name (str or callable): Name or full path to a function, or the
function itself.
module_paths (list, optional): A list of paths to candidate modules to
sear... | 375 | 408 | # Copyright 2018 The Texar 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 applicable ... |
call_function_with_redundant_kwargs | Calls a function and returns the results.
Only those keyword arguments in :attr:`kwargs` that are included in the
function's argument list are used to call the function.
Args:
fn (function): A callable. If :attr:`fn` is not a python function,
:attr:`fn.__call__` is called.
kwargs (dict): A `dict` of a... | # Copyright 2018 The Texar 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 applicable ... | def call_function_with_redundant_kwargs(fn, kwargs):
"""Calls a function and returns the results.
Only those keyword arguments in :attr:`kwargs` that are included in the
function's argument list are used to call the function.
Args:
fn (function): A callable. If :attr:`fn` is not a python funct... | 411 | 440 | # Copyright 2018 The Texar 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 applicable ... |
get_instance_kwargs | Makes a dict of keyword arguments with the following structure:
`kwargs_ = {'hparams': dict(hparams), **kwargs}`.
This is typically used for constructing a module which takes a set of
arguments as well as a argument named `hparams`.
Args:
kwargs (dict): A dict of keyword arguments. Can be `None`.
hparams: A ... | # Copyright 2018 The Texar 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 applicable ... | def get_instance_kwargs(kwargs, hparams):
"""Makes a dict of keyword arguments with the following structure:
`kwargs_ = {'hparams': dict(hparams), **kwargs}`.
This is typically used for constructing a module which takes a set of
arguments as well as a argument named `hparams`.
Args:
kwarg... | 443 | 467 | # Copyright 2018 The Texar 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 applicable ... |
strip_token | Returns a copy of strings with leading and trailing tokens removed.
Note that besides :attr:`token`, all leading and trailing whitespace
characters are also removed.
If :attr:`is_token_list` is False, then the function assumes tokens in
:attr:`str_` are separated with whitespace character.
Args:
str_: A `str`, o... | # Copyright 2018 The Texar 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 applicable ... | def strip_token(str_, token, is_token_list=False, compat=True):
"""Returns a copy of strings with leading and trailing tokens removed.
Note that besides :attr:`token`, all leading and trailing whitespace
characters are also removed.
If :attr:`is_token_list` is False, then the function assumes tokens i... | 655 | 714 | # Copyright 2018 The Texar 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 applicable ... |
strip_eos | Remove the EOS token and all subsequent tokens.
If :attr:`is_token_list` is False, then the function assumes tokens in
:attr:`str_` are separated with whitespace character.
Args:
str_: A `str`, or an `n`-D numpy array or (possibly nested)
list of `str`.
eos_token (str): The EOS token. Default is '<EOS... | # Copyright 2018 The Texar 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 applicable ... | def strip_eos(str_, eos_token='<EOS>', is_token_list=False, compat=True):
"""Remove the EOS token and all subsequent tokens.
If :attr:`is_token_list` is False, then the function assumes tokens in
:attr:`str_` are separated with whitespace character.
Args:
str_: A `str`, or an `n`-D numpy array... | 717 | 761 | # Copyright 2018 The Texar 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 applicable ... |
strip_bos | Remove all leading BOS tokens.
Note that besides :attr:`bos_token`, all leading and trailing whitespace
characters are also removed.
If :attr:`is_token_list` is False, then the function assumes tokens in
:attr:`str_` are separated with whitespace character.
Args:
str_: A `str`, or an `n`-D numpy array or (possib... | # Copyright 2018 The Texar 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 applicable ... | def strip_bos(str_, bos_token='<BOS>', is_token_list=False, compat=True):
"""Remove all leading BOS tokens.
Note that besides :attr:`bos_token`, all leading and trailing whitespace
characters are also removed.
If :attr:`is_token_list` is False, then the function assumes tokens in
:attr:`str_` are ... | 767 | 813 | # Copyright 2018 The Texar 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 applicable ... |
str_join | Concats :attr:`tokens` along the last dimension with intervening
occurrences of :attr:`sep`.
Args:
tokens: An `n`-D numpy array or (possibly nested) list of `str`.
sep (str): The string intervening between the tokens.
compat (bool): Whether to convert tokens into `unicode` (Python 2)
or `str` (Pyth... | # Copyright 2018 The Texar 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 applicable ... | def str_join(tokens, sep=' ', compat=True):
"""Concats :attr:`tokens` along the last dimension with intervening
occurrences of :attr:`sep`.
Args:
tokens: An `n`-D numpy array or (possibly nested) list of `str`.
sep (str): The string intervening between the tokens.
compat (bool): Whe... | 883 | 910 | # Copyright 2018 The Texar 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 applicable ... |
get_schema | Information about a medication that is used to support knowledge.
id: Unique id for the element within a resource (for internal references). This
may be any string value that does not contain spaces.
extension: May be used to represent additional information that is not part of the basic
definition of the el... | from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class MedicationKnowledge_AdministrationGuidelinesSchema:
"""
Information abo... | @staticmethod
def get_schema(
max_nesting_depth: Optional[int] = 6,
nesting_depth: int = 0,
nesting_list: List[str] = [],
max_recursion_limit: Optional[int] = 2,
include_extension: Optional[bool] = False,
extension_fields: Optional[List[str]] = None,
exten... | 14 | 267 | from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class MedicationKnowledge_AdministrationGuidelinesSchema:
"""
Information abo... |
__init__ | The set of arguments for constructing a FeatureGroup resource.
:param pulumi.Input[str] event_time_feature_name: The Event Time Feature Name.
:param pulumi.Input[Sequence[pulumi.Input['FeatureGroupFeatureDefinitionArgs']]] feature_definitions: An Array of Feature Definition
:param pulumi.Input[str] record_identifier_fe... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | def __init__(__self__, *,
event_time_feature_name: pulumi.Input[str],
feature_definitions: pulumi.Input[Sequence[pulumi.Input['FeatureGroupFeatureDefinitionArgs']]],
record_identifier_feature_name: pulumi.Input[str],
description: Optional[pulumi.In... | 18 | 52 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
get | Get an existing FeatureGroup resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Option... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | @staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'FeatureGroup':
"""
Get an existing FeatureGroup resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
... | 251 | 276 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
_parse_dsn | Method parses dsn
Args:
dsn (str): dsn
Returns:
bool: True
Raises:
exception: Exception | # -*- coding: utf-8 -*-
"""DBO MSSQL driver
.. module:: lib.database.dbo.drivers.mssql.driver
:platform: Unix
:synopsis: DBO MSSQL driver
.. moduleauthor:: Petr Rašek <bowman@hydratk.org>
"""
try:
import pymssql
except ImportError:
raise NotImplementedError('MSSQL client is not supported for PyPy')
fr... | def _parse_dsn(self, dsn):
"""Method parses dsn
Args:
dsn (str): dsn
Returns:
bool: True
Raises:
exception: Exception
"""
dsn_opt = dsn.split(':')[1]
dsn_opt_tokens = dsn_opt.split(';')
for dsn_opt_token in dsn_o... | 36 | 66 | # -*- coding: utf-8 -*-
"""DBO MSSQL driver
.. module:: lib.database.dbo.drivers.mssql.driver
:platform: Unix
:synopsis: DBO MSSQL driver
.. moduleauthor:: Petr Rašek <bowman@hydratk.org>
"""
try:
import pymssql
except ImportError:
raise NotImplementedError('MSSQL client is not supported for PyPy')
fr... |
calc_is_correct | gt_bboxes: (N, 4) np.array in xywh format
pred_bboxes: (N, 5) np.array in conf+xywh format | import sys
import cv2
import os
from ast import literal_eval
from pathlib import Path
import shutil
import logging
import random
import pickle
import yaml
import subprocess
from PIL import Image
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import animatio... | def calc_is_correct(gt_bboxes, pred_bboxes, iou_th=0.5):
"""
gt_bboxes: (N, 4) np.array in xywh format
pred_bboxes: (N, 5) np.array in conf+xywh format
"""
if len(gt_bboxes) == 0 and len(pred_bboxes) == 0:
tps, fps, fns = 0, 0, 0
return tps, fps, fns
elif len(gt_bboxes) == 0:
... | 125 | 149 | import sys
import cv2
import os
from ast import literal_eval
from pathlib import Path
import shutil
import logging
import random
import pickle
import yaml
import subprocess
from PIL import Image
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import animatio... |
GetChromeProxyRequestHeaderValue | Get a specific Chrome-Proxy request header value.
Returns:
The value for a specific Chrome-Proxy request header value for a
given key. Returns None if no such key is present. | # Copyright 2014 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.
import logging
import time
from common import network_metrics
from telemetry.page import page_test
from telemetry.value import scalar
CHROME_PROXY_VIA_HEA... | def GetChromeProxyRequestHeaderValue(self, key):
"""Get a specific Chrome-Proxy request header value.
Returns:
The value for a specific Chrome-Proxy request header value for a
given key. Returns None if no such key is present.
"""
if 'Chrome-Proxy' not in self.response.request_headers... | 71 | 87 | # Copyright 2014 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.
import logging
import time
from common import network_metrics
from telemetry.page import page_test
from telemetry.value import scalar
CHROME_PROXY_VIA_HEA... |
get | Get an existing PrivateEndpoint resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Opt... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | @staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'PrivateEndpoint':
"""
Get an existing PrivateEndpoint resource's state with the given name, id, and optional extra
properties used to qualify the lo... | 246 | 272 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.