Datasets:

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
get_parameter_shift
Multiplier and shift for the given parameter, based on its gradient recipe. Args: idx (int): parameter index Returns: float, float: multiplier, shift
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
def get_parameter_shift(self, idx, shift=np.pi / 2): """Multiplier and shift for the given parameter, based on its gradient recipe. Args: idx (int): parameter index Returns: float, float: multiplier, shift """ # get the gradient recipe for this param...
648
684
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
compare
Compares with another :class:`~.Hamiltonian`, :class:`~Tensor`, or :class:`~Observable`, to determine if they are equivalent. Observables/Hamiltonians are equivalent if they represent the same operator (their matrix representations are equal), and they are defined on the same wires. .. Warning:: The compare meth...
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
def compare(self, other): r"""Compares with another :class:`~.Hamiltonian`, :class:`~Tensor`, or :class:`~Observable`, to determine if they are equivalent. Observables/Hamiltonians are equivalent if they represent the same operator (their matrix representations are equal), and they ...
1,096
1,132
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
heisenberg_expand
Expand the given local Heisenberg-picture array into a full-system one. Args: U (array[float]): array to expand (expected to be of the dimension ``1+2*self.num_wires``) wires (Wires): wires on the device the array ``U`` should be expanded to apply to Raises: ValueError: if the size of the input ma...
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
def heisenberg_expand(self, U, wires): """Expand the given local Heisenberg-picture array into a full-system one. Args: U (array[float]): array to expand (expected to be of the dimension ``1+2*self.num_wires``) wires (Wires): wires on the device the array ``U`` should be exp...
1,476
1,546
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
heisenberg_pd
Partial derivative of the Heisenberg picture transform matrix. Computed using grad_recipe. Args: idx (int): index of the parameter with respect to which the partial derivative is computed. Returns: array[float]: partial derivative
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
def heisenberg_pd(self, idx): """Partial derivative of the Heisenberg picture transform matrix. Computed using grad_recipe. Args: idx (int): index of the parameter with respect to which the partial derivative is computed. Returns: array[float...
1,602
1,641
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
heisenberg_tr
Heisenberg picture representation of the linear transformation carried out by the gate at current parameter values. Given a unitary quantum gate :math:`U`, we may consider its linear transformation in the Heisenberg picture, :math:`U^\dagger(\cdot) U`. If the gate is Gaussian, this linear transformation preserves the...
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
def heisenberg_tr(self, wires, inverse=False): r"""Heisenberg picture representation of the linear transformation carried out by the gate at current parameter values. Given a unitary quantum gate :math:`U`, we may consider its linear transformation in the Heisenberg picture, :math:`...
1,643
1,687
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
heisenberg_obs
Representation of the observable in the position/momentum operator basis. Returns the expansion :math:`q` of the observable, :math:`Q`, in the basis :math:`\mathbf{r} = (\I, \x_0, \p_0, \x_1, \p_1, \ldots)`. * For first-order observables returns a real vector such that :math:`Q = \sum_i q_i \mathbf{r}_i`. * For se...
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
def heisenberg_obs(self, wires): r"""Representation of the observable in the position/momentum operator basis. Returns the expansion :math:`q` of the observable, :math:`Q`, in the basis :math:`\mathbf{r} = (\I, \x_0, \p_0, \x_1, \p_1, \ldots)`. * For first-order observables returns...
1,710
1,729
# Copyright 2018-2020 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or...
prepare_data
Args: eval ('bool'): indicator for eval/infer. Returns:
# MIT License # Copyright (c) 2018 the NJUNMT-pytorch authors. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, m...
def prepare_data(seqs_x, seqs_y=None, cuda=False, batch_first=True): """ Args: eval ('bool'): indicator for eval/infer. Returns: """ def _np_pad_batch_2D(samples, pad, batch_first=True, cuda=True): batch_size = len(samples) sizes = [len(s) for s in samples] max_s...
104
145
# MIT License # Copyright (c) 2018 the NJUNMT-pytorch authors. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, m...
__init__
Initialize zone speaker. Args: section_proxy: Returns all sections when called. lane_proxy: Returns a LaneMsg for each section. obstacle_proxy: function which returns obstacles in a section. surface_marking_proxy: function which returns surface_markings in a section. parking_proxy: function which r...
"""Class definition of the ZoneSpeaker.""" import bisect import functools from typing import Any, Callable, List, Tuple import simulation_groundtruth.srv as groundtruth_srv from simulation_evaluation.msg import Speaker as SpeakerMsg from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg from simul...
def __init__( self, *, section_proxy: Callable[[], List[SectionMsg]], lane_proxy: Callable[[int], LaneMsg], obstacle_proxy: Callable[[int], List[LabeledPolygonMsg]], surface_marking_proxy: Callable[[int], List[LabeledPolygonMsg]], parking_proxy: Callable[[int]...
23
68
"""Class definition of the ZoneSpeaker.""" import bisect import functools from typing import Any, Callable, List, Tuple import simulation_groundtruth.srv as groundtruth_srv from simulation_evaluation.msg import Speaker as SpeakerMsg from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg from simul...
_intersection_yield_zones
Intervals in which the car is supposed to halt/stop (in front of intersections). Args: rule: only intersections with this rule are considered
"""Class definition of the ZoneSpeaker.""" import bisect import functools from typing import Any, Callable, List, Tuple import simulation_groundtruth.srv as groundtruth_srv from simulation_evaluation.msg import Speaker as SpeakerMsg from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg from simul...
def _intersection_yield_zones(self, rule: int) -> List[Tuple[float, float]]: """Intervals in which the car is supposed to halt/stop (in front of intersections). Args: rule: only intersections with this rule are considered """ intervals = [] for sec in self.secti...
124
149
"""Class definition of the ZoneSpeaker.""" import bisect import functools from typing import Any, Callable, List, Tuple import simulation_groundtruth.srv as groundtruth_srv from simulation_evaluation.msg import Speaker as SpeakerMsg from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg from simul...
speak
List of speaker msgs. Contents: * beginning of road -> :ref:`Speaker <speaker_msg>`.START_ZONE, end of road -> :ref:`Speaker <speaker_msg>`.END_ZONE, and in between -> :ref:`Speaker <speaker_msg>`.DRIVING_ZONE, * close to an obstacle -> :ref:`Speaker <speaker_msg>`.OVERTAKING_ZONE * before yiel...
"""Class definition of the ZoneSpeaker.""" import bisect import functools from typing import Any, Callable, List, Tuple import simulation_groundtruth.srv as groundtruth_srv from simulation_evaluation.msg import Speaker as SpeakerMsg from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg from simul...
def speak(self) -> List[SpeakerMsg]: """List of speaker msgs. Contents: * beginning of road -> :ref:`Speaker <speaker_msg>`.START_ZONE, end of road -> :ref:`Speaker <speaker_msg>`.END_ZONE, and in between -> :ref:`Speaker <speaker_msg>`.DRIVING_ZONE, ...
209
264
"""Class definition of the ZoneSpeaker.""" import bisect import functools from typing import Any, Callable, List, Tuple import simulation_groundtruth.srv as groundtruth_srv from simulation_evaluation.msg import Speaker as SpeakerMsg from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg from simul...
processMedlineFolder
Basic function that iterates through abstracts in a medline file, do a basic word count and save to a file Args: medlineFolder (folder): Medline XML folder containing abstracts outFolder (folder): Folder to save output data to Returns: Nothing
import argparse import xml.etree.cElementTree as etree import os from os import listdir from os.path import isfile, join import random # MASKED: processMedlineFolder function (lines 8-58) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Little toy example to "process" a Medline abstract file ...
def processMedlineFolder(medlineFolder,outFolder): """Basic function that iterates through abstracts in a medline file, do a basic word count and save to a file Args: medlineFolder (folder): Medline XML folder containing abstracts outFolder (folder): Folder to save output data to Returns: Nothing """ abstr...
8
58
import argparse import xml.etree.cElementTree as etree import os from os import listdir from os.path import isfile, join import random def processMedlineFolder(medlineFolder,outFolder): """Basic function that iterates through abstracts in a medline file, do a basic word count and save to a file Args: medlineFolde...
mock_match
Checked for params on a mocked function is as expected It is necesary as sometimes we get a tuple and at the mock data we have lists. Examples: ``` >>> mock_match("A", "A") True >>> mock_match("A", "B") False >>> mock_match(["A", "B", "C"], ["A", "B", "C"]) True >>> mock_match(["A", "B", "C"], "*") True ```
import json import yaml """ SMock -- Serverboards Mock library -- Mock comfortably. This library helps to mock function and method calls, getting the data from an external yaml file. """ class MockWrapper: """ Wraps all the data returned by the mocked function to behave like a dictionary, like an object...
def mock_match(A, B): """ Checked for params on a mocked function is as expected It is necesary as sometimes we get a tuple and at the mock data we have lists. Examples: ``` >>> mock_match("A", "A") True >>> mock_match("A", "B") False >>> mock_match(["A", "B", "C"], ["A", "...
86
110
import json import yaml """ SMock -- Serverboards Mock library -- Mock comfortably. This library helps to mock function and method calls, getting the data from an external yaml file. """ class MockWrapper: """ Wraps all the data returned by the mocked function to behave like a dictionary, like an object...
subset_with_values
Determines whether or not it is possible to create the target sum using values in the list. Values in the list can be positive, negative, or zero. The function returns a tuple of exactly two items. The first is a boolean, that indicates true if the sum is possible and false if it is not. The second element in the tuple...
''' Created on Sep 18, 2017 @author: jschm ''' from cs115 import map def powerset(lst): """returns the power set of the list - the set of all subsets of the list""" if lst == []: return [[]] #power set is a list of lists #this way is more efficent for getting the combinations of the characters ...
def subset_with_values(target, lst): """Determines whether or not it is possible to create the target sum using values in the list. Values in the list can be positive, negative, or zero. The function returns a tuple of exactly two items. The first is a boolean, that indicates true if the sum is possible...
36
49
''' Created on Sep 18, 2017 @author: jschm ''' from cs115 import map def powerset(lst): """returns the power set of the list - the set of all subsets of the list""" if lst == []: return [[]] #power set is a list of lists #this way is more efficent for getting the combinations of the characters ...
get_keypoint
The [x y] position of a given facial keypoint. Args: keypoint: the keypoint type to return the position.
# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa import math from enum import Enum from typing import Callable, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.g...
def get_keypoint(self, keypoint: FaceKeypoint) -> torch.Tensor: """The [x y] position of a given facial keypoint. Args: keypoint: the keypoint type to return the position. """ if keypoint == FaceKeypoint.EYE_LEFT: out = self._data[..., (4, 5)] elif ke...
71
89
# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa import math from enum import Enum from typing import Callable, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.g...
clean_block_record
Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache
import asyncio import dataclasses import logging import multiprocessing from concurrent.futures.process import ProcessPoolExecutor from enum import Enum from typing import Dict, List, Optional, Set, Tuple, Union from clvm.casts import int_from_bytes from kujenga.consensus.block_body_validation import validate_block_b...
def clean_block_record(self, height: int): """ Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache """ if height < 0: return None blocks_to_remove = self.__heigh...
703
720
import asyncio import dataclasses import logging import multiprocessing from concurrent.futures.process import ProcessPoolExecutor from enum import Enum from typing import Dict, List, Optional, Set, Tuple, Union from clvm.casts import int_from_bytes from kujenga.consensus.block_body_validation import validate_block_b...
clean_block_records
Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments.
import asyncio import dataclasses import logging import multiprocessing from concurrent.futures.process import ProcessPoolExecutor from enum import Enum from typing import Dict, List, Optional, Set, Tuple, Union from clvm.casts import int_from_bytes from kujenga.consensus.block_body_validation import validate_block_b...
def clean_block_records(self): """ Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments. """ if len(self.__block_rec...
722
736
import asyncio import dataclasses import logging import multiprocessing from concurrent.futures.process import ProcessPoolExecutor from enum import Enum from typing import Dict, List, Optional, Set, Tuple, Union from clvm.casts import int_from_bytes from kujenga.consensus.block_body_validation import validate_block_b...
import_json_object
Converts a JSON formatted object to a ListData object. Args: json_dictionary(dict): a dictionary that is formatted as JSON Returns: Examples: >>> my_json_object = { ... 1: {'label': 'Example', 'value': 3}, ... 2: {'label': 'Test', 'value': 1}, ... 3: {'label': 'Tryout'} ... } >>> prin...
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
def import_json_object(instance, json_object): """ Converts a JSON formatted object to a ListData object. Args: json_dictionary(dict): a dictionary that is formatted as JSON Returns: Examples: >>> my_json_object = { ... 1: {'...
111
179
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
transpose_dataset
>>> my_listdata = ListData() >>> my_listdata.dataset = [['name', 'birth_date'], ['john', 2084], ['jane', 2054]] >>> my_listdata.transpose_dataset().dataset [['name', 'john', 'jane'], ['birth_date', 2084, 2054]] >>> my_listdata.transpose_dataset().dataset [['name', 'birth_date'], ['john', 2084], ['jane', 2054]] >>> my_...
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
def transpose_dataset(instance): """ >>> my_listdata = ListData() >>> my_listdata.dataset = [['name', 'birth_date'], ['john', 2084], ['jane', 2054]] >>> my_listdata.transpose_dataset().dataset [['name', 'john', 'jane'], ['birth_date', 2084, 2054]] >>> my_listdata.tra...
248
265
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
append_column
:param new_column_values: :param new_column_name: :param dataset: :return: Changes the inputted dataset when ran (no need for assigning the output to a variable). :usage: append_column(NEW_COLUMN_VARIABLES_LIST, NEW_COLUMN_NAME_STRING, DATASET) :example: >>> my_list_data = ListData() >>> my_list_data.dataset =...
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
def append_column(instance, new_column_values, new_column_name): """ :param new_column_values: :param new_column_name: :param dataset: :return: Changes the inputted dataset when ran (no need for assigning the output to a variable). :usage: append_column(NEW_COLUMN_VA...
410
453
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
replace_headers
Replaces headers of a dataset. Args: header_replacements_list(list): A list of strings to replace headers Returns: Nothing; modifies the provided dataset. Examples: >>> example_data = [['day', 'month'], ['1', 'June'], ['3', 'May'], ['4', 'Jun']] >>> my_list_data = ListData() >>> my_list_data.data...
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
def replace_headers(instance, header_replacements_list): """ Replaces headers of a dataset. Args: header_replacements_list(list): A list of strings to replace headers Returns: Nothing; modifies the provided dataset. Examples: >>> example...
508
538
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
append_row
Overrides the ListData method of the same name to change buffer state to 'not empty' after adding something to the buffer Args: new_row(list, bool, str, int): The object to be added as a new row to buffer Returns: ListData object (self) Examples: # initiate >>> my_buffer = ListBuffer() # empty? ...
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
def append_row(self, new_row): """ Overrides the ListData method of the same name to change buffer state to 'not empty' after adding something to the buffer Args: new_row(list, bool, str, int): The object to be added as a new row to buffer Returns: L...
548
582
class ListData(): def __init__(instance): ### INTERNAL PARAMETERS ############# instance.missing_data_character = " " ##################################### instance.dataset = [] def headers(instance): """ Returns the first row of the instance.dataset R...
solve
Solve for a stable model of specs. Arguments: specs (list): list of Specs to solve. dump (tuple): what to dump models (int): number of models to search (default: 0)
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
def solve(specs, dump=(), models=0, timers=False, stats=False, tests=False): """Solve for a stable model of specs. Arguments: specs (list): list of Specs to solve. dump (tuple): what to dump models (int): number of models to search (default: 0) """ driver = PyclingoDriver() ...
1,671
1,691
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
__init__
Driver for the Python clingo interface. Arguments: cores (bool): whether to generate unsatisfiable cores for better error reporting. asp (file-like): optional stream to write a text-based ASP program for debugging or verification.
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
def __init__(self, cores=True, asp=None): """Driver for the Python clingo interface. Arguments: cores (bool): whether to generate unsatisfiable cores for better error reporting. asp (file-like): optional stream to write a text-based ASP program ...
280
295
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
condition
Generate facts for a dependency or virtual provider condition. Arguments: required_spec (spack.spec.Spec): the spec that triggers this condition imposed_spec (spack.spec.Spec or None): the sepc with constraints that are imposed when this condition is triggered name (str or None): name for `required...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
def condition(self, required_spec, imposed_spec=None, name=None): """Generate facts for a dependency or virtual provider condition. Arguments: required_spec (spack.spec.Spec): the spec that triggers this condition imposed_spec (spack.spec.Spec or None): the sepc with constra...
663
702
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
reorder_flags
Order compiler flags on specs in predefined order. We order flags so that any node's flags will take priority over those of its dependents. That is, the deepest node in the DAG's flags will appear last on the compile line, in the order they were specified. The solver determines wihch flags are on nodes; this routine...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
def reorder_flags(self): """Order compiler flags on specs in predefined order. We order flags so that any node's flags will take priority over those of its dependents. That is, the deepest node in the DAG's flags will appear last on the compile line, in the order they were ...
1,537
1,584
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from __future__ import print_function import collections import copy import itertools import os import pprint import sys i...
__init__
Creates an instance of a value in this executor. Args: value: Depending on `type_spec`, either a `tf.Tensor`, `tf.data.Dataset`, or a nested structure of these stored in an `Struct`. tf_function_cache: A cache obeying `dict` semantics that can be used to look up previously embedded TensorFlow functions. ...
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def __init__(self, value, tf_function_cache, type_spec=None, device=None): """Creates an instance of a value in this executor. Args: value: Depending on `type_spec`, either a `tf.Tensor`, `tf.data.Dataset`, or a nested structure of these stored in an `Struct`. tf_function_cache: A cache o...
349
369
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
__init__
Creates a new instance of an eager executor. Args: device: An optional `tf.config.LogicalDevice` that this executor will schedule all of its operations to run on. For example, the list of logical devices can be obtained using `tf.config.list_logical_devices()`. Raises: RuntimeError: If not executing e...
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def __init__(self, device=None): """Creates a new instance of an eager executor. Args: device: An optional `tf.config.LogicalDevice` that this executor will schedule all of its operations to run on. For example, the list of logical devices can be obtained using `tf.config.list_l...
421
442
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
create_call
Creates a call to `comp` with optional `arg`. Args: comp: As documented in `executor_base.Executor`. arg: As documented in `executor_base.Executor`. Returns: An instance of `EagerValue` representing the result of the call. Raises: RuntimeError: If not executing eagerly. TypeError: If the arguments are of t...
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
@tracing.trace async def create_call(self, comp, arg=None): """Creates a call to `comp` with optional `arg`. Args: comp: As documented in `executor_base.Executor`. arg: As documented in `executor_base.Executor`. Returns: An instance of `EagerValue` representing the result of the call...
468
499
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
create_struct
Creates a tuple of `elements`. Args: elements: As documented in `executor_base.Executor`. Returns: An instance of `EagerValue` that represents the constructed tuple.
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
@tracing.trace async def create_struct(self, elements): """Creates a tuple of `elements`. Args: elements: As documented in `executor_base.Executor`. Returns: An instance of `EagerValue` that represents the constructed tuple. """ elements = structure.to_elements(structure.from_conta...
501
522
# Copyright 2019, The TensorFlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
AFF4Path
Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type.
#!/usr/bin/env python """Pathspecs are methods of specifying the path on the client. The GRR client has a number of drivers to virtualize access to different objects to create a Virtual File System (VFS) abstraction. These are called 'VFS Handlers' and they provide typical file-like operations (e.g. read, seek, tell a...
def AFF4Path(self, client_urn): """Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type. """ # If the first level is OS and the s...
192
252
#!/usr/bin/env python """Pathspecs are methods of specifying the path on the client. The GRR client has a number of drivers to virtualize access to different objects to create a Virtual File System (VFS) abstraction. These are called 'VFS Handlers' and they provide typical file-like operations (e.g. read, seek, tell a...
AsRegEx
Return the current glob as a simple regex. Note: No interpolation is performed. Returns: A RegularExpression() object.
#!/usr/bin/env python """Pathspecs are methods of specifying the path on the client. The GRR client has a number of drivers to virtualize access to different objects to create a Virtual File System (VFS) abstraction. These are called 'VFS Handlers' and they provide typical file-like operations (e.g. read, seek, tell a...
def AsRegEx(self): """Return the current glob as a simple regex. Note: No interpolation is performed. Returns: A RegularExpression() object. """ parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value) result = "".join(self._ReplaceRegExPart(p) for p in parts) return rdf_stan...
326
337
#!/usr/bin/env python """Pathspecs are methods of specifying the path on the client. The GRR client has a number of drivers to virtualize access to different objects to create a Virtual File System (VFS) abstraction. These are called 'VFS Handlers' and they provide typical file-like operations (e.g. read, seek, tell a...
get_profile_contact_info
Return data for a single profile. [public_id] - public identifier i.e. tom-quirk-1928345 [urn_id] - id provided by the related URN
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
def get_profile_contact_info(self, public_id=None, urn_id=None): """ Return data for a single profile. [public_id] - public identifier i.e. tom-quirk-1928345 [urn_id] - id provided by the related URN """ res = self.client.session.get( f"{self.client.API_B...
175
208
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
get_profile
Return data for a single profile. [public_id] - public identifier i.e. tom-quirk-1928345 [urn_id] - id provided by the related URN
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
def get_profile(self, public_id=None, urn_id=None): """ Return data for a single profile. [public_id] - public identifier i.e. tom-quirk-1928345 [urn_id] - id provided by the related URN """ sleep( random.randint(2, 5) ) # sleep a random duration...
210
277
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
get_similar_companies
Return similar companies for a single company. [public_id] - public identifier i.e. univeristy-of-queensland
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
def get_similar_companies(self, public_id): """ Return similar companies for a single company. [public_id] - public identifier i.e. univeristy-of-queensland """ sleep( random.randint(2, 5) ) # sleep a random duration to try and evade suspention ...
430
446
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
get_company
Return data for a single company. [public_id] - public identifier i.e. univeristy-of-queensland
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
def get_company(self, public_id): """ Return data for a single company. [public_id] - public identifier i.e. univeristy-of-queensland """ sleep( random.randint(2, 5) ) # sleep a random duration to try and evade suspention params = { "...
448
491
""" Provides linkedin api-related code """ import random import logging from time import sleep import json from linkedin_api.utils.helpers import get_id_from_urn from linkedin_api.client import Client logger = logging.getLogger(__name__) class Linkedin(object): """ Class for accessing Linkedin API. """...
_compute_nary_hessian_vector_product
Returns a function accepting `2 * len(arguments)` arguments to compute a Hessian-vector product of a multivariate function. Notes ----- The implementation is based on TensorFlow's '_hessian_vector_product' function in 'tensorflow.python.ops.gradients_impl'.
import itertools try: import theano import theano.tensor as T from theano.gradient import disconnected_grad except ImportError: theano = None T = None from ._backend import Backend from .. import make_graph_backend_decorator class _TheanoBackend(Backend): def __init__(self): super()....
def _compute_nary_hessian_vector_product(self, gradients, arguments): """Returns a function accepting `2 * len(arguments)` arguments to compute a Hessian-vector product of a multivariate function. Notes ----- The implementation is based on TensorFlow's '_hessian_vector_produ...
64
90
import itertools try: import theano import theano.tensor as T from theano.gradient import disconnected_grad except ImportError: theano = None T = None from ._backend import Backend from .. import make_graph_backend_decorator class _TheanoBackend(Backend): def __init__(self): super()....
_find_boundaries_subpixel
See ``find_boundaries(..., mode='subpixel')``. Notes ----- This function puts in an empty row and column between each *actual* row and column of the image, for a corresponding shape of $2s - 1$ for every image dimension of size $s$. These "interstitial" rows and columns are filled as ``True`` if they separate two labe...
from __future__ import division import numpy as np from scipy import ndimage as ndi from ..morphology import dilation, erosion, square from ..util import img_as_float, view_as_windows from ..color import gray2rgb # MASKED: _find_boundaries_subpixel function (lines 10-46) def find_boundaries(label_img, connectivity...
def _find_boundaries_subpixel(label_img): """See ``find_boundaries(..., mode='subpixel')``. Notes ----- This function puts in an empty row and column between each *actual* row and column of the image, for a corresponding shape of $2s - 1$ for every image dimension of size $s$. These "interstiti...
10
46
from __future__ import division import numpy as np from scipy import ndimage as ndi from ..morphology import dilation, erosion, square from ..util import img_as_float, view_as_windows from ..color import gray2rgb def _find_boundaries_subpixel(label_img): """See ``find_boundaries(..., mode='subpixel')``. Not...
lat_lon_grid_deltas
Calculate the delta between grid points that are in a latitude/longitude format. Calculate the signed delta distance between grid points when the grid spacing is defined by delta lat/lon rather than delta x/y Parameters ---------- longitude : array_like array of longitudes defining the grid latitude : array_like ...
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
@exporter.export @preprocess_xarray def lat_lon_grid_deltas(longitude, latitude, **kwargs): r"""Calculate the delta between grid points that are in a latitude/longitude format. Calculate the signed delta distance between grid points when the grid spacing is defined by delta lat/lon rather than delta x/y ...
741
794
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
grid_deltas_from_dataarray
Calculate the horizontal deltas between grid points of a DataArray. Calculate the signed delta distance between grid points of a DataArray in the horizontal directions, whether the grid is lat/lon or x/y. Parameters ---------- f : `xarray.DataArray` Parsed DataArray on a latitude/longitude grid, in (..., lat, lon...
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
@exporter.export def grid_deltas_from_dataarray(f): """Calculate the horizontal deltas between grid points of a DataArray. Calculate the signed delta distance between grid points of a DataArray in the horizontal directions, whether the grid is lat/lon or x/y. Parameters ---------- f : `xarray....
797
831
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
laplacian
Calculate the laplacian of a grid of values. Works for both regularly-spaced data, and grids with varying spacing. Either `coordinates` or `deltas` must be specified, or `f` must be given as an `xarray.DataArray` with attached coordinate and projection information. If `f` is an `xarray.DataArray`, and `coordinates` ...
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
@exporter.export def laplacian(f, **kwargs): """Calculate the laplacian of a grid of values. Works for both regularly-spaced data, and grids with varying spacing. Either `coordinates` or `deltas` must be specified, or `f` must be given as an `xarray.DataArray` with attached coordinate and projection ...
1,126
1,177
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
angle_to_direction
Convert the meteorological angle to directional text. Works for angles greater than or equal to 360 (360 -> N | 405 -> NE) and rounds to the nearest angle (355 -> N | 404 -> NNE) Parameters ---------- input_angle : numeric or array-like numeric Angles such as 0, 25, 45, 360, 410, etc full : boolean True retur...
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
@exporter.export @preprocess_xarray def angle_to_direction(input_angle, full=False, level=3): """Convert the meteorological angle to directional text. Works for angles greater than or equal to 360 (360 -> N | 405 -> NE) and rounds to the nearest angle (355 -> N | 404 -> NNE) Parameters ---------- ...
1,306
1,396
# Copyright (c) 2016,2017,2018,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Contains a collection of generally useful calculation tools.""" import functools from operator import itemgetter import numpy as np from numpy.core.numeric import ...
parse
`parse` should always `yield` a dict that follows the Event Schema <https://city-bureau.github.io/city-scrapers/06_event_schema.html>. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs.
# -*- coding: utf-8 -*- import scrapy from city_scrapers.spider import Spider from datetime import datetime, timedelta from dateutil.parser import parse as dateparse import re class Chi_school_community_action_councilSpider(Spider): name = 'chi_school_community_action_council' long_name = 'Chicago Public Schoo...
def parse(self, response): """ `parse` should always `yield` a dict that follows the Event Schema <https://city-bureau.github.io/city-scrapers/06_event_schema.html>. Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping needs. """ month_coun...
14
52
# -*- coding: utf-8 -*- import scrapy from city_scrapers.spider import Spider from datetime import datetime, timedelta from dateutil.parser import parse as dateparse import re class Chi_school_community_action_councilSpider(Spider): name = 'chi_school_community_action_council' long_name = 'Chicago Public Schoo...
_orient_edges
Orient edges in a skeleton graph to estimate the causal DAG, or CPDAG. Uses the separation sets to orient edges via conditional independence testing. Parameters ---------- skel_graph : nx.Graph A skeleton graph. If ``None``, then will initialize PC using a complete graph. By default None. sep_set : _type_ ...
from itertools import combinations from typing import Callable, Dict, Set, Tuple, Union import networkx as nx import pandas as pd from causal_networkx import ADMG from causal_networkx.discovery.classes import ConstraintDiscovery def _has_both_edges(dag, i, j): return dag.has_edge(i, j) and dag.has_edge(j, i) ...
def _orient_edges(self, skel_graph, sep_set): """Orient edges in a skeleton graph to estimate the causal DAG, or CPDAG. Uses the separation sets to orient edges via conditional independence testing. Parameters ---------- skel_graph : nx.Graph A skeleton ...
97
211
from itertools import combinations from typing import Callable, Dict, Set, Tuple, Union import networkx as nx import pandas as pd from causal_networkx import ADMG from causal_networkx.discovery.classes import ConstraintDiscovery def _has_both_edges(dag, i, j): return dag.has_edge(i, j) and dag.has_edge(j, i) ...
__init__
:param transformer_type: The Transformer type, such as Bert, GPT2, DistilBert, etc. :param transformer_model_key: The transformer model key. This is the directory for the model. :param transformer_tokenizer_key: The transformer tokenizer key. This is the tokenizer directory. :param hidden: The hidden output layers to u...
from functools import partial from typing import List, Optional, Union from transformers import (AlbertModel, AlbertTokenizer, BartModel, BigBirdModel, BigBirdTokenizer, BartTokenizer, BertModel, BertTokenizer, CamembertModel, CamembertTokenizer, CTRLModel, ...
def __init__( self, transformer_type: str = 'Bert', transformer_model_key: str = 'bert-base-uncased', transformer_tokenizer_key: str = None, hidden: Union[List[int], int] = -2, reduce_option: str = 'mean', sentence_handler: SentenceHandler = SentenceHandler(),...
103
146
from functools import partial from typing import List, Optional, Union from transformers import (AlbertModel, AlbertTokenizer, BartModel, BigBirdModel, BigBirdTokenizer, BartTokenizer, BertModel, BertTokenizer, CamembertModel, CamembertTokenizer, CTRLModel, ...
__init__
Método de inicialização de pássaro. Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de lançamento e angulo de lançamento :param x: :param y:
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math DESTRUIDO = 'Destruido' ATIVO = 'Ativo' GRAVIDADE = 10 # m/s^2 class Ator(): """ Classe que representa um ator. Ele representa um ponto cartesiano na tela. """ _caracter_ativo = 'A' _caracter_destruido = ' ' def _...
def __init__(self, x=0, y=0): """ Método de inicialização de pássaro. Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de lançamento e angulo de lançamento :param x: :param y: """ super().__init__...
78
92
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math DESTRUIDO = 'Destruido' ATIVO = 'Ativo' GRAVIDADE = 10 # m/s^2 class Ator(): """ Classe que representa um ator. Ele representa um ponto cartesiano na tela. """ _caracter_ativo = 'A' _caracter_destruido = ' ' def _...
calcular_posicao
Método que cálcula a posição do passaro de acordo com o tempo. Antes do lançamento o pássaro deve retornar o valor de sua posição inicial Depois do lançamento o pássaro deve calcular de acordo com sua posição inicial, velocidade escalar, ângulo de lancamento, gravidade (constante GRAVIDADE) e o tempo do jogo. Após a...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math DESTRUIDO = 'Destruido' ATIVO = 'Ativo' GRAVIDADE = 10 # m/s^2 class Ator(): """ Classe que representa um ator. Ele representa um ponto cartesiano na tela. """ _caracter_ativo = 'A' _caracter_destruido = ' ' def _...
def calcular_posicao(self, tempo): """ Método que cálcula a posição do passaro de acordo com o tempo. Antes do lançamento o pássaro deve retornar o valor de sua posição inicial Depois do lançamento o pássaro deve calcular de acordo com sua posição inicial, velocidade escalar, ...
110
127
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math DESTRUIDO = 'Destruido' ATIVO = 'Ativo' GRAVIDADE = 10 # m/s^2 class Ator(): """ Classe que representa um ator. Ele representa um ponto cartesiano na tela. """ _caracter_ativo = 'A' _caracter_destruido = ' ' def _...
get_tasks
--- description: get all tasks associated with the specified step. tags: - Tasks parameters: - name: "flow_id" in: "path" description: "flow_id" required: true type: "string" - name: "run_number" in: "path" description: "run_number" required: true type: "integer" - name: "step_name" in: "path" descr...
from ..data.models import TaskRow from ..data.postgres_async_db import AsyncPostgresDB from .utils import read_body, format_response, handle_exceptions import asyncio class TaskApi(object): _task_table = None lock = asyncio.Lock() def __init__(self, app): app.router.add_route( "GET", ...
@format_response @handle_exceptions async def get_tasks(self, request): """ --- description: get all tasks associated with the specified step. tags: - Tasks parameters: - name: "flow_id" in: "path" description: "flow_id" r...
29
65
from ..data.models import TaskRow from ..data.postgres_async_db import AsyncPostgresDB from .utils import read_body, format_response, handle_exceptions import asyncio class TaskApi(object): _task_table = None lock = asyncio.Lock() def __init__(self, app): app.router.add_route( "GET", ...
get_task
--- description: get all artifacts associated with the specified task. tags: - Tasks parameters: - name: "flow_id" in: "path" description: "flow_id" required: true type: "string" - name: "run_number" in: "path" description: "run_number" required: true type: "integer" - name: "step_name" in: "path" d...
from ..data.models import TaskRow from ..data.postgres_async_db import AsyncPostgresDB from .utils import read_body, format_response, handle_exceptions import asyncio class TaskApi(object): _task_table = None lock = asyncio.Lock() def __init__(self, app): app.router.add_route( "GET", ...
@format_response @handle_exceptions async def get_task(self, request): """ --- description: get all artifacts associated with the specified task. tags: - Tasks parameters: - name: "flow_id" in: "path" description: "flow_id" ...
67
110
from ..data.models import TaskRow from ..data.postgres_async_db import AsyncPostgresDB from .utils import read_body, format_response, handle_exceptions import asyncio class TaskApi(object): _task_table = None lock = asyncio.Lock() def __init__(self, app): app.router.add_route( "GET", ...
create_task
--- description: This end-point allow to test that service is up. tags: - Tasks parameters: - name: "flow_id" in: "path" description: "flow_id" required: true type: "string" - name: "run_number" in: "path" description: "run_number" required: true type: "integer" - name: "step_name" in: "path" descri...
from ..data.models import TaskRow from ..data.postgres_async_db import AsyncPostgresDB from .utils import read_body, format_response, handle_exceptions import asyncio class TaskApi(object): _task_table = None lock = asyncio.Lock() def __init__(self, app): app.router.add_route( "GET", ...
@format_response @handle_exceptions async def create_task(self, request): """ --- description: This end-point allow to test that service is up. tags: - Tasks parameters: - name: "flow_id" in: "path" description: "flow_id" ...
112
173
from ..data.models import TaskRow from ..data.postgres_async_db import AsyncPostgresDB from .utils import read_body, format_response, handle_exceptions import asyncio class TaskApi(object): _task_table = None lock = asyncio.Lock() def __init__(self, app): app.router.add_route( "GET", ...
__decide_h_extension
Decides which language 'owns' how many .h files :returns: The report with divided header files
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
def __decide_h_extension(self): """ Decides which language 'owns' how many .h files :returns: The report with divided header files """ report = self.__report h_files = report['C']['.h'] if h_files > 0: c_files = (sum(report['C'].values()) - h_file...
145
175
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
__calculate_main_language
Calculates the main language (maximum of files extensions) :param report: The report :returns: The main language.
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
def __calculate_main_language(self, report): """ Calculates the main language (maximum of files extensions) :param report: The report :returns: The main language. """ max_files = 0 max_lang = None for language in report: lang_fiels =...
177
194
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
__calculate_used_languages
Calculates the used languages by throwing away the extension counts and collapsing them to the language. Only languages that have at least one file extension are kept and will appear in the report :param report: The report :returns: The used languages.
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
def __calculate_used_languages(self, report): """ Calculates the used languages by throwing away the extension counts and collapsing them to the language. Only languages that have at least one file extension are kept and will appear in the report :param report: The repor...
196
214
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
scrab
Counts the files that have an extension of one of the languages :param project: The project that the scrab task shall analyse :param filepath: The filepath to the file that can be analysed :param file: The file as string that can be analysed :returns: Report that contains the scrabbed information of ...
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
def scrab(self, project, filepath, file): """ Counts the files that have an extension of one of the languages :param project: The project that the scrab task shall analyse :param filepath: The filepath to the file that can be analysed :param file: The file a...
216
231
""" The MIT License (MIT) Copyright (c) 2017 Andreas Poppele Copyright (c) 2017 Roland Jaeger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
add_gt_
Add ground truth as assigned results. Args: gt_labels (torch.Tensor): Labels of gt boxes
# Modification 2020 RangiLyu # Copyright 2018-2019 Open-MMLab. # 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 applicabl...
def add_gt_(self, gt_labels): """Add ground truth as assigned results. Args: gt_labels (torch.Tensor): Labels of gt boxes """ self_inds = torch.arange( 1, len(gt_labels) + 1, dtype=torch.long, device=gt_labels.device ) self.gt_inds = torch.cat...
211
227
# Modification 2020 RangiLyu # Copyright 2018-2019 Open-MMLab. # 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 applicabl...
assert_matches_stdout
Asserts a PCollection of strings matches the expected stdout elements. Args: actual (beam.PCollection): A PCollection. expected (List[str]): A list of stdout elements, one line per element. normalize_fn (Function[any]): A function to normalize elements before comparing them. Can be used to sort lists befor...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
def assert_matches_stdout( actual, expected_stdout, normalize_fn=lambda elem: elem, label=''): """Asserts a PCollection of strings matches the expected stdout elements. Args: actual (beam.PCollection): A PCollection. expected (List[str]): A list of stdout elements, one line per element. normalize_f...
29
49
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
__init__
Initialize the Language class. Instead of "en" etc. we call the language "stanfordnlp_en" to not cause conflicts with spaCy's built-in languages. Using entry points, this also allows serializing and deserializing the language class and "lang": "stanfordnlp_en" in the meta.json will automatically instantiate this class...
# coding: utf8 from spacy.symbols import POS, TAG, DEP, LEMMA, HEAD from spacy.language import Language from spacy.tokens import Doc from spacy.util import get_lang_class import numpy import re class StanfordNLPLanguage(Language): # MASKED: __init__ function (lines 11-37) def make_doc(self, text): return...
def __init__(self, snlp, meta=None, **kwargs): """Initialize the Language class. Instead of "en" etc. we call the language "stanfordnlp_en" to not cause conflicts with spaCy's built-in languages. Using entry points, this also allows serializing and deserializing the language class ...
11
37
# coding: utf8 from spacy.symbols import POS, TAG, DEP, LEMMA, HEAD from spacy.language import Language from spacy.tokens import Doc from spacy.util import get_lang_class import numpy import re class StanfordNLPLanguage(Language): def __init__(self, snlp, meta=None, **kwargs): """Initialize the Language c...
get_tokens_with_heads
Flatten the tokens in the StanfordNLP Doc and extract the token indices of the sentence start tokens to set is_sent_start. snlp_doc (stanfordnlp.Document): The processed StanfordNLP doc. RETURNS (list): The tokens (words).
# coding: utf8 from spacy.symbols import POS, TAG, DEP, LEMMA, HEAD from spacy.language import Language from spacy.tokens import Doc from spacy.util import get_lang_class import numpy import re class StanfordNLPLanguage(Language): def __init__(self, snlp, meta=None, **kwargs): """Initialize the Language c...
def get_tokens_with_heads(self, snlp_doc): """Flatten the tokens in the StanfordNLP Doc and extract the token indices of the sentence start tokens to set is_sent_start. snlp_doc (stanfordnlp.Document): The processed StanfordNLP doc. RETURNS (list): The tokens (words). """ ...
139
162
# coding: utf8 from spacy.symbols import POS, TAG, DEP, LEMMA, HEAD from spacy.language import Language from spacy.tokens import Doc from spacy.util import get_lang_class import numpy import re class StanfordNLPLanguage(Language): def __init__(self, snlp, meta=None, **kwargs): """Initialize the Language c...
set_seed
Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed to set.
# !pip install transformers import torch from transformers.file_utils import is_tf_available, is_torch_available, is_torch_tpu_available from transformers import BertTokenizerFast, BertForSequenceClassification from transformers import Trainer, TrainingArguments import numpy as np import random from sklearn.datasets i...
def set_seed(seed: int): """ Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` and/or ``tf`` (if installed). Args: seed (:obj:`int`): The seed to set. """ random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.ma...
14
30
# !pip install transformers import torch from transformers.file_utils import is_tf_available, is_torch_available, is_torch_tpu_available from transformers import BertTokenizerFast, BertForSequenceClassification from transformers import Trainer, TrainingArguments import numpy as np import random from sklearn.datasets i...
reduceFrame
Takes in a depth image and rescales it Args: height_ratio: Determines fraction of rows to keep sub_sample: Scaling factor for image
''' Adapted from https://github.com/IntelligentQuadruped, with permission Description: Module to connect to camera and retrieve RGB and depth data. Currently supports the Intel RealSense R200 Camera. ''' import numpy as np import logging import time import cv2 import matplotlib.pyplot as plt from skimage.transform imp...
def reduceFrame(self, depth, height_ratio = 0.5, sub_sample = 0.3, reduce_to = 'lower'): """ Takes in a depth image and rescales it Args: height_ratio: Determines fraction of rows to keep sub_sample: Scaling factor for image """ if (height_ratio > 1.0...
92
144
''' Adapted from https://github.com/IntelligentQuadruped, with permission Description: Module to connect to camera and retrieve RGB and depth data. Currently supports the Intel RealSense R200 Camera. ''' import numpy as np import logging import time import cv2 import matplotlib.pyplot as plt from skimage.transform imp...
_args_to_matching_arrays
Converts a list to array using the first element for dtype. This method is used to match the behavior of `tf.concat`. Args: args_list: A list or tuple of arguments. dtype_hint: An optional hint used when converting the args to tensors. Returns: A list of tensors.
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def _args_to_matching_arrays(args_list, dtype_hint=None): """Converts a list to array using the first element for dtype. This method is used to match the behavior of `tf.concat`. Args: args_list: A list or tuple of arguments. dtype_hint: An optional hint used when converting the args to tensors. Retur...
125
149
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
get_sqrl_url_params
Get SQRL url params to be added as querystring params in the SQRL url. By default this only adds ``nut=<nut>``. Returns ------- str URLEncoded querystring params
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals from django.core.urlresolvers import reverse from django.http import QueryDict from .crypto import generate_randomness from .models import SQRLNut from .utils import get_user_ip class SQRLInitialization(object): """ SQ...
def get_sqrl_url_params(self): """ Get SQRL url params to be added as querystring params in the SQRL url. By default this only adds ``nut=<nut>``. Returns ------- str URLEncoded querystring params """ qd = QueryDict('', mutable=True) ...
106
121
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals from django.core.urlresolvers import reverse from django.http import QueryDict from .crypto import generate_randomness from .models import SQRLNut from .utils import get_user_ip class SQRLInitialization(object): """ SQ...
count_flops_attn
A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, )
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flo...
356
373
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
forward
Apply QKV attention. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention.
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
def forward(self, qkv, y): """ Apply QKV attention. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape if y is None: assert width % (3 * self.n_hea...
386
409
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
forward
Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention.
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width /...
425
444
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
forward
Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param y: an [N, L] Tensor of texts, if conditional. :return: an [N x C x ...] Tensor of outputs.
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
def forward(self, x, timesteps, y=None): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param y: an [N, L] Tensor of texts, if conditional. :return: an [N x C x ...] Tensor of outputs. ...
737
764
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
forward
Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :return: an [N x K] Tensor of outputs.
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
def forward(self, x, timesteps): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :return: an [N x K] Tensor of outputs. """ emb = self.time_embed(timestep_embedding(timesteps, sel...
1,035
1,053
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32, convert_module_to_f16_2 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_modu...
findTimeColumn
Dynamically determine which column of a log file contains dates. Parameters: row: A row of a logfile Returns: iterator: An integer defining the row that contains a valid date string.
import csv # csv reader functions from collections.abc import Counter # count uniques in a file quickly, O(nlogn) from decimal import Decimal # just to show decimals with lower precision # Global Variables # from cfltools.settings import APPFOLDER class IpAddress: def __init__(self, ip, numOccurances): ...
def findTimeColumn(row): """Dynamically determine which column of a log file contains dates. Parameters: row: A row of a logfile Returns: iterator: An integer defining the row that contains a valid date string. """ import dateparser iterator = 0 for item in row: ...
18
39
import csv # csv reader functions from collections.abc import Counter # count uniques in a file quickly, O(nlogn) from decimal import Decimal # just to show decimals with lower precision # Global Variables # from cfltools.settings import APPFOLDER class IpAddress: def __init__(self, ip, numOccurances): ...
magpath
Takes the perpendicular deflection field and reconstructs the path integrated magnetic field. Args: wBx (array): x-component perpendicular deflection field. wBy (array): y-component perpendicular deflection field. Returns: Bxpath (array): Path integrated magnetic field x-component. Bypath (array): Pa...
""" Takes the gradients of the solution to the screen mapping potential problem and reconstructs the perpendicular deflection field. """ import numpy as np import scipy as sp import scipy.interpolate import scipy.misc import scipy.ndimage from .constants import M_PROTON_G, ESU, C_CMS def reconstruct(ri, li, rs, v, x...
def magpath(wBx, wBy): """ Takes the perpendicular deflection field and reconstructs the path integrated magnetic field. Args: wBx (array): x-component perpendicular deflection field. wBy (array): y-component perpendicular deflection field. Returns: Bxpath (array): Path int...
49
67
""" Takes the gradients of the solution to the screen mapping potential problem and reconstructs the perpendicular deflection field. """ import numpy as np import scipy as sp import scipy.interpolate import scipy.misc import scipy.ndimage from .constants import M_PROTON_G, ESU, C_CMS def reconstruct(ri, li, rs, v, x...
fluximage2
An alternative approach to creating a flux image out of a perpendicular deflection field. Args: x (array): Plasma x-coordinates (cm). y (array): Plasma x-coordinates (cm). phix (array): Gradient of screen mapping potential in x-direction. phiy (array): Gradient of screen mapping potential in y-direct...
""" Takes the gradients of the solution to the screen mapping potential problem and reconstructs the perpendicular deflection field. """ import numpy as np import scipy as sp import scipy.interpolate import scipy.misc import scipy.ndimage from .constants import M_PROTON_G, ESU, C_CMS def reconstruct(ri, li, rs, v, x...
def fluximage2(x, y, phix, phiy, flux0, scale_fact=1, scale_order=3): """ An alternative approach to creating a flux image out of a perpendicular deflection field. Args: x (array): Plasma x-coordinates (cm). y (array): Plasma x-coordinates (cm). phix (array): Gradient of scree...
133
174
""" Takes the gradients of the solution to the screen mapping potential problem and reconstructs the perpendicular deflection field. """ import numpy as np import scipy as sp import scipy.interpolate import scipy.misc import scipy.ndimage from .constants import M_PROTON_G, ESU, C_CMS def reconstruct(ri, li, rs, v, x...
apply
Quantize the weights and activations to calculate for specific layers. Args: model(paddle.nn.Layer): The target model which would calculate the input quantization scale. Returns: None
# 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 app...
def apply(self, model): """ Quantize the weights and activations to calculate for specific layers. Args: model(paddle.nn.Layer): The target model which would calculate the input quantization scale. Returns: None """ ...
342
368
# 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 app...
_is_skip_quant_op
The input op should be skipped quantization. 1. the type of input op should be conv2d, depthwise_conv2d or matmul 2. the previous ops of the input op are not fake_quantize_dequantize ops
# 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 app...
def _is_skip_quant_op(self, block, in_op): """ The input op should be skipped quantization. 1. the type of input op should be conv2d, depthwise_conv2d or matmul 2. the previous ops of the input op are not fake_quantize_dequantize ops """ target_op_types = [ ...
592
607
# 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 app...
captcha
Create a captcha. Args: path: save path, default None. fmt: image format, PNG / JPEG. Returns: A tuple, (name, text, StringIO.value). For example: ('fXZJN4AFxHGoU5mIlcsdOypa', 'JGW9', '‰PNG  ...')
#!/usr/bin/env python # -*- coding: utf-8 -*- # refer to `https://bitbucket.org/akorn/wheezy.captcha` import random import string import os.path from io import BytesIO from PIL import Image from PIL import ImageFilter from PIL.ImageDraw import Draw from PIL.ImageFont import truetype class Bezier: def __init__(...
def captcha(self, path=None, fmt='JPEG'): """Create a captcha. Args: path: save path, default None. fmt: image format, PNG / JPEG. Returns: A tuple, (name, text, StringIO.value). For example: ('fXZJN4AFxHGoU5mIlcsdOypa', 'JGW9'...
194
218
#!/usr/bin/env python # -*- coding: utf-8 -*- # refer to `https://bitbucket.org/akorn/wheezy.captcha` import random import string import os.path from io import BytesIO from PIL import Image from PIL import ImageFilter from PIL.ImageDraw import Draw from PIL.ImageFont import truetype class Bezier: def __init__(...
parse_requirements
Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessin...
#!/usr/bin/env python # -*- coding: utf-8 -*- """pipreqs - Generate pip requirements.txt file based on imports Usage: pipreqs [options] <path> Options: --use-local Use ONLY local package info instead of querying PyPI --pypi-server <url> Use custom PyPi server --proxy <url> Use Prox...
def parse_requirements(file_): """Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to p...
231
277
#!/usr/bin/env python # -*- coding: utf-8 -*- """pipreqs - Generate pip requirements.txt file based on imports Usage: pipreqs [options] <path> Options: --use-local Use ONLY local package info instead of querying PyPI --pypi-server <url> Use custom PyPi server --proxy <url> Use Prox...
compare_modules
Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do exist in the specified file.
#!/usr/bin/env python # -*- coding: utf-8 -*- """pipreqs - Generate pip requirements.txt file based on imports Usage: pipreqs [options] <path> Options: --use-local Use ONLY local package info instead of querying PyPI --pypi-server <url> Use custom PyPi server --proxy <url> Use Prox...
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do e...
280
297
#!/usr/bin/env python # -*- coding: utf-8 -*- """pipreqs - Generate pip requirements.txt file based on imports Usage: pipreqs [options] <path> Options: --use-local Use ONLY local package info instead of querying PyPI --pypi-server <url> Use custom PyPi server --proxy <url> Use Prox...
load_data
load data set Args: name: name of data set (one of {names}) Returns: largest connected component of data set
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
def load_data(name): """ load data set Args: name: name of data set (one of {names}) Returns: largest connected component of data set """ data = _dataloaders[name]() data = largest_connected_component(data=data) data.num_nodes = data.x.shape[0] return data
208
222
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
prepare_patches
initialise patch data if ``output_folder`` does not exist, else load existing patch data Args: output_folder: folder for storing patch data **kwargs: arguments passed to :py:func:`~local2global_embedding.patches.create_patch_data` Returns: patch_data, patch_graph
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
def prepare_patches(output_folder, **kwargs): """ initialise patch data if ``output_folder`` does not exist, else load existing patch data Args: output_folder: folder for storing patch data **kwargs: arguments passed to :py:func:`~local2global_embedding.patches.create_patch_data` Retur...
228
249
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
csvlist
Create an argparse type that parses comma separated lists of type ``input_type`` Args: input_type: type of list elements Returns: list parser
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
def csvlist(input_type=str): """ Create an argparse type that parses comma separated lists of type ``input_type`` Args: input_type: type of list elements Returns: list parser """ def make_list(input_str): return [input_type(s) for s in input_str.split(',')] make_li...
252
274
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
reduce_to_dims
remove all data for dimensions not in ``dims`` Args: dims: list of dimensions to keep
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
def reduce_to_dims(self, dims): """ remove all data for dimensions not in ``dims`` Args: dims: list of dimensions to keep """ index = [i for i, d in enumerate(dims) if self.contains_dim(d)] for key1 in self._data: if isinstance(self._data[key1...
139
150
"""Training run script""" import argparse import json from pathlib import Path from bisect import bisect_left import torch import torch_geometric as tg import matplotlib.pyplot as plt import local2global as l2g from local2global_embedding.embedding import speye, train, embedding, VGAE_model, VGAE_loss, reconstructio...
run_convolution
Run convolution between the nist cross section and a sine curve representing initial scattering distribution. Returns: centered_data: angular distribution spread after each scattering event
# -*- coding: utf-8 -*- """ Created on Thu Mar 12 16:39:59 2020 @author: nicholls """ import os import numpy as np import matplotlib.pyplot as plt #%% class AngularSpreadCalc(): """ class for calculating how angular spread changes with iterations: Inputs: iterations: maxinum number of iterat...
def run_convolution(self): """ Run convolution between the nist cross section and a sine curve representing initial scattering distribution. Returns: centered_data: angular distribution spread after each scattering event """ # normalise cross sect...
77
96
# -*- coding: utf-8 -*- """ Created on Thu Mar 12 16:39:59 2020 @author: nicholls """ import os import numpy as np import matplotlib.pyplot as plt #%% class AngularSpreadCalc(): """ class for calculating how angular spread changes with iterations: Inputs: iterations: maxinum number of iterat...
submit
Submit the process with the supplied inputs to the daemon runners immediately returning control to the interpreter. The return value will be the calculation node of the submitted process. :param process: the process class to submit :param inputs: the inputs to be passed to the process :return: the calculation node of ...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
def submit(process, **inputs): """ Submit the process with the supplied inputs to the daemon runners immediately returning control to the interpreter. The return value will be the calculation node of the submitted process. :param process: the process class to submit :param inputs: the inputs to be ...
73
94
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
send_blocks_and_test
Send blocks to test node and test whether the tip advances. - add all blocks to our block_store - send a headers message for the final block - the on_getheaders handler will ensure that any getheaders are responded to - if request_block is True: wait for getdata for each of the blocks. The on_getdata handler will en...
#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """BitcoinSN P2...
def send_blocks_and_test(self, blocks, rpc, success=True, request_block=True, reject_code=None, reject_reason=None, timeout=60): """Send blocks to test node and test whether the tip advances. - add all blocks to our block_store - send a headers message for the final block - the o...
485
518
#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """BitcoinSN P2...
_trusted_commit
Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the change. commit_type: str. The type of commit. Possible values are in core.storage.base_models.COMMIT_TYPE_CHOICES. com...
# coding: utf-8 # # Copyright 2017 The Oppia 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 requi...
def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): """Record the event to the commit log after the model commit. Note that this extends the superclass method. Args: committer_id: str. The user_id of the user who committed the ...
643
681
# coding: utf-8 # # Copyright 2017 The Oppia 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 requi...
__init__
Wrapper for freesasa config: str Path to configuration file containing residue composition and atomic parameters - freesasa format. options: dict, optional Options to change how PDBs are parsed by freesasa. parameters: dict, optional Parameters to alter how freesasa computes surface area.
import os import freesasa from .extract_residues import extract_residue # Defaults _DEFAULT_OPTIONS = { 'hetatm': True, 'hydrogen': True, # 'halt-at-unknown': True, # 'separate-chains' : False, 'separate-models': True } _DEFAULT_PARAMETERS = { 'algorithm': freesasa.LeeRichards, 'probe-r...
def __init__(self, config, wsas_params, tmp_dir, nonstandard_residue_files, nonstandard_residue, ligand_topology, options=None, parameters=None): """Wrapper for freesasa config: str Path to configuration file containing residue composition and atomic parameters - freesasa fo...
53
76
import os import freesasa from .extract_residues import extract_residue # Defaults _DEFAULT_OPTIONS = { 'hetatm': True, 'hydrogen': True, # 'halt-at-unknown': True, # 'separate-chains' : False, 'separate-models': True } _DEFAULT_PARAMETERS = { 'algorithm': freesasa.LeeRichards, 'probe-r...
_create_freesasa_section_text
Create text to add to freesasa configuration file to incorporate new residue. Parameters ---------- new_residues : dict Non-standard residues to add to the freesasa config file. keys = residue names, values = atom name to type mapping (dict). sasa_atom_params: dict Maps atom type to properties needed by fr...
import os import freesasa from .extract_residues import extract_residue # Defaults _DEFAULT_OPTIONS = { 'hetatm': True, 'hydrogen': True, # 'halt-at-unknown': True, # 'separate-chains' : False, 'separate-models': True } _DEFAULT_PARAMETERS = { 'algorithm': freesasa.LeeRichards, 'probe-r...
@staticmethod def _create_freesasa_section_text(new_residues, sasa_atom_params): """ Create text to add to freesasa configuration file to incorporate new residue. Parameters ---------- new_residues : dict Non-standard residues to add to the freesasa config fi...
145
202
import os import freesasa from .extract_residues import extract_residue # Defaults _DEFAULT_OPTIONS = { 'hetatm': True, 'hydrogen': True, # 'halt-at-unknown': True, # 'separate-chains' : False, 'separate-models': True } _DEFAULT_PARAMETERS = { 'algorithm': freesasa.LeeRichards, 'probe-r...
list_jobs
Lists the jobs in the Databricks Job Service. :param limit: The limit/batch size used to retrieve jobs. :param offset: The offset of the first job to return, relative to the most recently created job. :param expand_tasks: Whether to include task and cluster details in the response. :return: A list of jobs.
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
def list_jobs(self, limit: int = 25, offset: int = 0, expand_tasks: bool = False) -> List[Dict[str, Any]]: """ Lists the jobs in the Databricks Job Service. :param limit: The limit/batch size used to retrieve jobs. :param offset: The offset of the first job to return, relative to th...
144
168
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
get_run_state
Retrieves run state of the run. Please note that any Airflow tasks that call the ``get_run_state`` method will result in failure unless you have enabled xcom pickling. This can be done using the following environment variable: ``AIRFLOW__CORE__ENABLE_XCOM_PICKLING`` If you do not want to enable xcom pickling, use th...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
def get_run_state(self, run_id: int) -> RunState: """ Retrieves run state of the run. Please note that any Airflow tasks that call the ``get_run_state`` method will result in failure unless you have enabled xcom pickling. This can be done using the following environment var...
212
230
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
start
Start the Pea. This method calls :meth:`start` in :class:`threading.Thread` or :class:`multiprocesssing.Process`. .. #noqa: DAR201
import argparse import multiprocessing import os import threading import time from typing import Any, Tuple, Union, Dict, Optional from .helper import _get_event, ConditionalEvent from ... import __stop_msg__, __ready_msg__, __default_host__ from ...enums import PeaRoleType, RuntimeBackendType, SocketType from ...exce...
def start(self): """Start the Pea. This method calls :meth:`start` in :class:`threading.Thread` or :class:`multiprocesssing.Process`. .. #noqa: DAR201 """ self.worker.start() if not self.args.noblock_on_start: self.wait_start_success() return self
168
176
import argparse import multiprocessing import os import threading import time from typing import Any, Tuple, Union, Dict, Optional from .helper import _get_event, ConditionalEvent from ... import __stop_msg__, __ready_msg__, __default_host__ from ...enums import PeaRoleType, RuntimeBackendType, SocketType from ...exce...
cltv_lock_to_height
Modify the scriptPubKey to add an OP_CHECKLOCKTIMEVERIFY, and make a transaction that spends it. This transforms the output script to anyone can spend (OP_TRUE) if the lock time condition is valid. Default height is -1 which leads CLTV to fail TODO: test more ways that transactions using CLTV could be invalid (eg lo...
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BIP65 (CHECKLOCKTIMEVERIFY). Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) b...
def cltv_lock_to_height(node, tx, to_address, amount, height=-1): '''Modify the scriptPubKey to add an OP_CHECKLOCKTIMEVERIFY, and make a transaction that spends it. This transforms the output script to anyone can spend (OP_TRUE) if the lock time condition is valid. Default height is -1 which lead...
44
84
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BIP65 (CHECKLOCKTIMEVERIFY). Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) b...
expand_dims
Is similar to [numpy.expand_dims](https://docs.scipy.org/doc/numpy/reference/generated/numpy.expand_dims.html). var = torch.range(0, 9).view(-1, 2) torch.expand_dims(var, 0).size() # (1, 5, 2)
""" Taken from vithursant's repo: https://github.com/vithursant/MagnetLoss-PyTorch/blob/master/magnet_loss/magnet_loss.py """ import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F class MagnetLoss(nn.Module): """ Magnet loss technique presen...
def expand_dims(var, dim=0): """ Is similar to [numpy.expand_dims](https://docs.scipy.org/doc/numpy/reference/generated/numpy.expand_dims.html). var = torch.range(0, 9).view(-1, 2) torch.expand_dims(var, 0).size() # (1, 5, 2) """ sizes = list(var.size()) sizes.insert(dim, 1) ...
211
219
""" Taken from vithursant's repo: https://github.com/vithursant/MagnetLoss-PyTorch/blob/master/magnet_loss/magnet_loss.py """ import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F class MagnetLoss(nn.Module): """ Magnet loss technique presen...
_save_summary_of_run
Saves 2 files: - run_summary.txt: A user-friendly resume of the monte carlo run. - models_details.json: A full serialized version of the models. Contains info that lacks in the txt file like the loss or optimizer.
import logging import os import json import tensorflow as tf import pandas as pd import numpy as np from tqdm import tqdm import datetime from pdb import set_trace from time import sleep from openpyxl import load_workbook, Workbook from openpyxl.worksheet.table import Table from tensorflow.keras.losses import categoric...
def _save_summary_of_run(self, run_summary, data_summary): """ Saves 2 files: - run_summary.txt: A user-friendly resume of the monte carlo run. - models_details.json: A full serialized version of the models. Contains info that lacks in the txt file like the lo...
372
394
import logging import os import json import tensorflow as tf import pandas as pd import numpy as np from tqdm import tqdm import datetime from pdb import set_trace from time import sleep from openpyxl import load_workbook, Workbook from openpyxl.worksheet.table import Table from tensorflow.keras.losses import categoric...
grad_norm
Compute each parameter's gradient's norm and their overall norm. The overall norm is computed over all gradients together, as if they were concatenated into a single vector. Args: norm_type: The type of the used p-norm, cast to float if necessary. Can be ``'inf'`` for infinity norm. Return: norms: Th...
import os import logging from typing import Dict, Union from datetime import timedelta import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pandas as pd import mlflow import torch import pytorch_lightning as pl import pprint pp = pprint.PrettyPrinter(indent=4) from arnet i...
def grad_norm(self, norm_type: Union[float, int, str]) -> Dict[str, float]: """Compute each parameter's gradient's norm and their overall norm. The overall norm is computed over all gradients together, as if they were concatenated into a single vector. Args: norm_type: ...
60
97
import os import logging from typing import Dict, Union from datetime import timedelta import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pandas as pd import mlflow import torch import pytorch_lightning as pl import pprint pp = pprint.PrettyPrinter(indent=4) from arnet i...
init_obj
Finds a function handle with the name given as 'type' in config, and returns the instance initialized with corresponding arguments given. `object = config.init_obj('name', module, a, b=1)` is equivalent to `object = module.name(a, b=1)`
import os import logging, glob from pathlib import Path from functools import reduce, partial from operator import getitem from datetime import datetime # from .logger import setup_logging # import logger.setup_logging # from . import logger from .logger import setup_logging from .util import read_json, write_json # pr...
def init_obj(self, name, module, *args, **kwargs): """ Finds a function handle with the name given as 'type' in config, and returns the instance initialized with corresponding arguments given. `object = config.init_obj('name', module, a, b=1)` is equivalent to `objec...
105
118
import os import logging, glob from pathlib import Path from functools import reduce, partial from operator import getitem from datetime import datetime # from .logger import setup_logging # import logger.setup_logging # from . import logger from .logger import setup_logging from .util import read_json, write_json # pr...
init_ftn
Finds a function handle with the name given as 'type' in config, and returns the function with given arguments fixed with functools.partial. `function = config.init_ftn('name', module, a, b=1)` is equivalent to `function = lambda *args, **kwargs: module.name(a, *args, b=1, **kwargs)`.
import os import logging, glob from pathlib import Path from functools import reduce, partial from operator import getitem from datetime import datetime # from .logger import setup_logging # import logger.setup_logging # from . import logger from .logger import setup_logging from .util import read_json, write_json # pr...
def init_ftn(self, name, module, *args, **kwargs): """ Finds a function handle with the name given as 'type' in config, and returns the function with given arguments fixed with functools.partial. `function = config.init_ftn('name', module, a, b=1)` is equivalent to `...
120
133
import os import logging, glob from pathlib import Path from functools import reduce, partial from operator import getitem from datetime import datetime # from .logger import setup_logging # import logger.setup_logging # from . import logger from .logger import setup_logging from .util import read_json, write_json # pr...
_get_sorted_box_lims
Sort the uncertainties for each box in boxes based on a normalization given box_init. Unrestricted dimensions are dropped. The sorting is based on the normalization of the first box in boxes. Parameters ---------- boxes : list of numpy structured arrays box_init : numpy structured array Returns ------- tuple with...
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
def _get_sorted_box_lims(boxes, box_init): '''Sort the uncertainties for each box in boxes based on a normalization given box_init. Unrestricted dimensions are dropped. The sorting is based on the normalization of the first box in boxes. Parameters ---------- boxes : list of numpy structured ar...
40
75
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
_determine_restricted_dims
returns a list of dimensions that is restricted Parameters ---------- box_limits : pd.DataFrame box_init : pd.DataFrame Returns ------- list of str
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
def _determine_restricted_dims(box_limits, box_init): '''returns a list of dimensions that is restricted Parameters ---------- box_limits : pd.DataFrame box_init : pd.DataFrame Returns ------- list of str ''' cols = box_init.columns.values restricted_dims = cols[np.all( ...
146
164
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
_in_box
returns the a boolean index indicated which data points are inside and which are outside of the given box_lims Parameters ---------- x : pd.DataFrame boxlim : pd.DataFrame Returns ------- ndarray boolean 1D array Raises ------ Attribute error if not numbered columns are not pandas category dtype
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
def _in_box(x, boxlim): ''' returns the a boolean index indicated which data points are inside and which are outside of the given box_lims Parameters ---------- x : pd.DataFrame boxlim : pd.DataFrame Returns ------- ndarray boolean 1D array Raises ------ A...
203
241
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
plot_tradeoff
Visualize the trade off between coverage and density. Color is used to denote the number of restricted dimensions. Parameters ---------- cmap : valid matplotlib colormap Returns ------- a Figure instance
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
def plot_tradeoff(peeling_trajectory, cmap=mpl.cm.viridis): # @UndefinedVariable '''Visualize the trade off between coverage and density. Color is used to denote the number of restricted dimensions. Parameters ---------- cmap : valid matplotlib colormap Returns ------- a Figure instan...
599
639
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
plot_unc
Parameters: ---------- xi : int the row at which to plot i : int the index of the uncertainty being plotted j : int the index of the box being plotted u : string the uncertainty being plotted: ax : axes instance the ax on which to plot
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
def plot_unc(box_init, xi, i, j, norm_box_lim, box_lim, u, ax, color=sns.color_palette()[0]): ''' Parameters: ---------- xi : int the row at which to plot i : int the index of the uncertainty being plotted j : int the index of the box being plotted u : ...
642
679
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
plot_boxes
Helper function for plotting multiple boxlims Parameters ---------- x : pd.DataFrame boxes : list of pd.DataFrame together : bool
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
def plot_boxes(x, boxes, together): '''Helper function for plotting multiple boxlims Parameters ---------- x : pd.DataFrame boxes : list of pd.DataFrame together : bool ''' box_init = _make_box(x) box_lims, uncs = _get_sorted_box_lims(boxes, box_init) # normalize the box lims...
682
736
''' Scenario discovery utilities used by both :mod:`cart` and :mod:`prim` ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import abc import enum import itertools import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as patche...
sample_size_cal
调研样本量的计算 参考:https://www.surveysystem.com/sscalc.htm sample_size_cal(interval,N,alpha=0.05) 输入: interval: 误差范围,例如0.03 N: 总体的大小,一般1万以上就没啥差别啦 alpha:置信水平,默认95%
# -*- coding: utf-8 -* '''问卷数据分析工具包 Created on Tue Nov 8 20:05:36 2016 @author: JSong 1、针对问卷星数据,编写并封装了很多常用算法 2、利用report工具包,能将数据直接导出为PPTX 该工具包支持一下功能: 1、编码问卷星、问卷网等数据 2、封装描述统计和交叉分析函数 3、支持生成一份整体的报告和相关数据 ''' import os import re import sys import math import time import pandas as pd import numpy as np import matplo...
def sample_size_cal(interval,N,alpha=0.05): '''调研样本量的计算 参考:https://www.surveysystem.com/sscalc.htm sample_size_cal(interval,N,alpha=0.05) 输入: interval: 误差范围,例如0.03 N: 总体的大小,一般1万以上就没啥差别啦 alpha:置信水平,默认95% ''' import scipy.stats as stats p=stats.norm.ppf(1-alpha/2) if interval>1...
1,418
1,435
# -*- coding: utf-8 -* '''问卷数据分析工具包 Created on Tue Nov 8 20:05:36 2016 @author: JSong 1、针对问卷星数据,编写并封装了很多常用算法 2、利用report工具包,能将数据直接导出为PPTX 该工具包支持一下功能: 1、编码问卷星、问卷网等数据 2、封装描述统计和交叉分析函数 3、支持生成一份整体的报告和相关数据 ''' import os import re import sys import math import time import pandas as pd import numpy as np import matplo...