repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
J535D165/recordlinkage
recordlinkage/api.py
Index.random
def random(self, *args, **kwargs): """Add a random index. Shortcut of :class:`recordlinkage.index.Random`:: from recordlinkage.index import Random indexer = recordlinkage.Index() indexer.add(Random()) """ indexer = Random() self.add(indexer) return self
python
def random(self, *args, **kwargs): """Add a random index. Shortcut of :class:`recordlinkage.index.Random`:: from recordlinkage.index import Random indexer = recordlinkage.Index() indexer.add(Random()) """ indexer = Random() self.add(indexer) return self
[ "def", "random", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "indexer", "=", "Random", "(", ")", "self", ".", "add", "(", "indexer", ")", "return", "self" ]
Add a random index. Shortcut of :class:`recordlinkage.index.Random`:: from recordlinkage.index import Random indexer = recordlinkage.Index() indexer.add(Random())
[ "Add", "a", "random", "index", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L74-L88
train
206,500
J535D165/recordlinkage
recordlinkage/api.py
Compare.exact
def exact(self, *args, **kwargs): """Compare attributes of pairs exactly. Shortcut of :class:`recordlinkage.compare.Exact`:: from recordlinkage.compare import Exact indexer = recordlinkage.Compare() indexer.add(Exact()) """ compare = Exact(*args, **kwargs) self.add(compare) return self
python
def exact(self, *args, **kwargs): """Compare attributes of pairs exactly. Shortcut of :class:`recordlinkage.compare.Exact`:: from recordlinkage.compare import Exact indexer = recordlinkage.Compare() indexer.add(Exact()) """ compare = Exact(*args, **kwargs) self.add(compare) return self
[ "def", "exact", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "compare", "=", "Exact", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "add", "(", "compare", ")", "return", "self" ]
Compare attributes of pairs exactly. Shortcut of :class:`recordlinkage.compare.Exact`:: from recordlinkage.compare import Exact indexer = recordlinkage.Compare() indexer.add(Exact())
[ "Compare", "attributes", "of", "pairs", "exactly", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L147-L161
train
206,501
J535D165/recordlinkage
recordlinkage/api.py
Compare.string
def string(self, *args, **kwargs): """Compare attributes of pairs with string algorithm. Shortcut of :class:`recordlinkage.compare.String`:: from recordlinkage.compare import String indexer = recordlinkage.Compare() indexer.add(String()) """ compare = String(*args, **kwargs) self.add(compare) return self
python
def string(self, *args, **kwargs): """Compare attributes of pairs with string algorithm. Shortcut of :class:`recordlinkage.compare.String`:: from recordlinkage.compare import String indexer = recordlinkage.Compare() indexer.add(String()) """ compare = String(*args, **kwargs) self.add(compare) return self
[ "def", "string", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "compare", "=", "String", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "add", "(", "compare", ")", "return", "self" ]
Compare attributes of pairs with string algorithm. Shortcut of :class:`recordlinkage.compare.String`:: from recordlinkage.compare import String indexer = recordlinkage.Compare() indexer.add(String())
[ "Compare", "attributes", "of", "pairs", "with", "string", "algorithm", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L163-L177
train
206,502
J535D165/recordlinkage
recordlinkage/api.py
Compare.numeric
def numeric(self, *args, **kwargs): """Compare attributes of pairs with numeric algorithm. Shortcut of :class:`recordlinkage.compare.Numeric`:: from recordlinkage.compare import Numeric indexer = recordlinkage.Compare() indexer.add(Numeric()) """ compare = Numeric(*args, **kwargs) self.add(compare) return self
python
def numeric(self, *args, **kwargs): """Compare attributes of pairs with numeric algorithm. Shortcut of :class:`recordlinkage.compare.Numeric`:: from recordlinkage.compare import Numeric indexer = recordlinkage.Compare() indexer.add(Numeric()) """ compare = Numeric(*args, **kwargs) self.add(compare) return self
[ "def", "numeric", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "compare", "=", "Numeric", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "add", "(", "compare", ")", "return", "self" ]
Compare attributes of pairs with numeric algorithm. Shortcut of :class:`recordlinkage.compare.Numeric`:: from recordlinkage.compare import Numeric indexer = recordlinkage.Compare() indexer.add(Numeric())
[ "Compare", "attributes", "of", "pairs", "with", "numeric", "algorithm", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L179-L193
train
206,503
J535D165/recordlinkage
recordlinkage/api.py
Compare.geo
def geo(self, *args, **kwargs): """Compare attributes of pairs with geo algorithm. Shortcut of :class:`recordlinkage.compare.Geographic`:: from recordlinkage.compare import Geographic indexer = recordlinkage.Compare() indexer.add(Geographic()) """ compare = Geographic(*args, **kwargs) self.add(compare) return self
python
def geo(self, *args, **kwargs): """Compare attributes of pairs with geo algorithm. Shortcut of :class:`recordlinkage.compare.Geographic`:: from recordlinkage.compare import Geographic indexer = recordlinkage.Compare() indexer.add(Geographic()) """ compare = Geographic(*args, **kwargs) self.add(compare) return self
[ "def", "geo", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "compare", "=", "Geographic", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "add", "(", "compare", ")", "return", "self" ]
Compare attributes of pairs with geo algorithm. Shortcut of :class:`recordlinkage.compare.Geographic`:: from recordlinkage.compare import Geographic indexer = recordlinkage.Compare() indexer.add(Geographic())
[ "Compare", "attributes", "of", "pairs", "with", "geo", "algorithm", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L195-L209
train
206,504
J535D165/recordlinkage
recordlinkage/api.py
Compare.date
def date(self, *args, **kwargs): """Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date()) """ compare = Date(*args, **kwargs) self.add(compare) return self
python
def date(self, *args, **kwargs): """Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date()) """ compare = Date(*args, **kwargs) self.add(compare) return self
[ "def", "date", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "compare", "=", "Date", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "add", "(", "compare", ")", "return", "self" ]
Compare attributes of pairs with date algorithm. Shortcut of :class:`recordlinkage.compare.Date`:: from recordlinkage.compare import Date indexer = recordlinkage.Compare() indexer.add(Date())
[ "Compare", "attributes", "of", "pairs", "with", "date", "algorithm", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L211-L225
train
206,505
J535D165/recordlinkage
recordlinkage/measures.py
reduction_ratio
def reduction_ratio(links_pred, *total): """Compute the reduction ratio. The reduction ratio is 1 minus the ratio candidate matches and the maximum number of pairs possible. Parameters ---------- links_pred: int, pandas.MultiIndex The number of candidate record pairs or the pandas.MultiIndex with record pairs. *total: pandas.DataFrame object(s) The DataFrames are used to compute the full index size with the full_index_size function. Returns ------- float The reduction ratio. """ n_max = full_index_size(*total) if isinstance(links_pred, pandas.MultiIndex): links_pred = len(links_pred) if links_pred > n_max: raise ValueError("n has to be smaller of equal n_max") return 1 - links_pred / n_max
python
def reduction_ratio(links_pred, *total): """Compute the reduction ratio. The reduction ratio is 1 minus the ratio candidate matches and the maximum number of pairs possible. Parameters ---------- links_pred: int, pandas.MultiIndex The number of candidate record pairs or the pandas.MultiIndex with record pairs. *total: pandas.DataFrame object(s) The DataFrames are used to compute the full index size with the full_index_size function. Returns ------- float The reduction ratio. """ n_max = full_index_size(*total) if isinstance(links_pred, pandas.MultiIndex): links_pred = len(links_pred) if links_pred > n_max: raise ValueError("n has to be smaller of equal n_max") return 1 - links_pred / n_max
[ "def", "reduction_ratio", "(", "links_pred", ",", "*", "total", ")", ":", "n_max", "=", "full_index_size", "(", "*", "total", ")", "if", "isinstance", "(", "links_pred", ",", "pandas", ".", "MultiIndex", ")", ":", "links_pred", "=", "len", "(", "links_pred...
Compute the reduction ratio. The reduction ratio is 1 minus the ratio candidate matches and the maximum number of pairs possible. Parameters ---------- links_pred: int, pandas.MultiIndex The number of candidate record pairs or the pandas.MultiIndex with record pairs. *total: pandas.DataFrame object(s) The DataFrames are used to compute the full index size with the full_index_size function. Returns ------- float The reduction ratio.
[ "Compute", "the", "reduction", "ratio", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L33-L63
train
206,506
J535D165/recordlinkage
recordlinkage/measures.py
full_index_size
def full_index_size(*args): """Compute the number of records in a full index. Compute the number of records in a full index without building the index itself. The result is the maximum number of record pairs possible. This function is especially useful in measures like the `reduction_ratio`. Deduplication: Given a DataFrame A with length N, the full index size is N*(N-1)/2. Linking: Given a DataFrame A with length N and a DataFrame B with length M, the full index size is N*M. Parameters ---------- *args: int, pandas.MultiIndex, pandas.Series, pandas.DataFrame A pandas object or a int representing the length of a dataset to link. When there is one argument, it is assumed that the record linkage is a deduplication process. Examples -------- Use integers: >>> full_index_size(10) # deduplication: 45 pairs >>> full_index_size(10, 10) # linking: 100 pairs or pandas objects >>> full_index_size(DF) # deduplication: len(DF)*(len(DF)-1)/2 pairs >>> full_index_size(DF, DF) # linking: len(DF)*len(DF) pairs """ # check if a list or tuple is passed as argument if len(args) == 1 and isinstance(args[0], (list, tuple)): args = tuple(args[0]) if len(args) == 1: n = get_length(args[0]) size = int(n * (n - 1) / 2) else: size = numpy.prod([get_length(arg) for arg in args]) return size
python
def full_index_size(*args): """Compute the number of records in a full index. Compute the number of records in a full index without building the index itself. The result is the maximum number of record pairs possible. This function is especially useful in measures like the `reduction_ratio`. Deduplication: Given a DataFrame A with length N, the full index size is N*(N-1)/2. Linking: Given a DataFrame A with length N and a DataFrame B with length M, the full index size is N*M. Parameters ---------- *args: int, pandas.MultiIndex, pandas.Series, pandas.DataFrame A pandas object or a int representing the length of a dataset to link. When there is one argument, it is assumed that the record linkage is a deduplication process. Examples -------- Use integers: >>> full_index_size(10) # deduplication: 45 pairs >>> full_index_size(10, 10) # linking: 100 pairs or pandas objects >>> full_index_size(DF) # deduplication: len(DF)*(len(DF)-1)/2 pairs >>> full_index_size(DF, DF) # linking: len(DF)*len(DF) pairs """ # check if a list or tuple is passed as argument if len(args) == 1 and isinstance(args[0], (list, tuple)): args = tuple(args[0]) if len(args) == 1: n = get_length(args[0]) size = int(n * (n - 1) / 2) else: size = numpy.prod([get_length(arg) for arg in args]) return size
[ "def", "full_index_size", "(", "*", "args", ")", ":", "# check if a list or tuple is passed as argument", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "args", "=...
Compute the number of records in a full index. Compute the number of records in a full index without building the index itself. The result is the maximum number of record pairs possible. This function is especially useful in measures like the `reduction_ratio`. Deduplication: Given a DataFrame A with length N, the full index size is N*(N-1)/2. Linking: Given a DataFrame A with length N and a DataFrame B with length M, the full index size is N*M. Parameters ---------- *args: int, pandas.MultiIndex, pandas.Series, pandas.DataFrame A pandas object or a int representing the length of a dataset to link. When there is one argument, it is assumed that the record linkage is a deduplication process. Examples -------- Use integers: >>> full_index_size(10) # deduplication: 45 pairs >>> full_index_size(10, 10) # linking: 100 pairs or pandas objects >>> full_index_size(DF) # deduplication: len(DF)*(len(DF)-1)/2 pairs >>> full_index_size(DF, DF) # linking: len(DF)*len(DF) pairs
[ "Compute", "the", "number", "of", "records", "in", "a", "full", "index", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L83-L124
train
206,507
J535D165/recordlinkage
recordlinkage/measures.py
true_positives
def true_positives(links_true, links_pred): """Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of correctly predicted links. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_true & links_pred)
python
def true_positives(links_true, links_pred): """Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of correctly predicted links. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_true & links_pred)
[ "def", "true_positives", "(", "links_true", ",", "links_pred", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "return", "len", "(", "links_true", "&", "links_pred", ")" ]
Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of correctly predicted links.
[ "Count", "the", "number", "of", "True", "Positives", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L127-L149
train
206,508
J535D165/recordlinkage
recordlinkage/measures.py
true_negatives
def true_negatives(links_true, links_pred, total): """Count the number of True Negatives. Returns the number of correctly predicted non-links, also called the number of True Negatives (TN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. total: int, pandas.MultiIndex The count of all record pairs (both links and non-links). When the argument is a pandas.MultiIndex, the length of the index is used. Returns ------- int The number of correctly predicted non-links. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) if isinstance(total, pandas.MultiIndex): total = len(total) return int(total) - len(links_true | links_pred)
python
def true_negatives(links_true, links_pred, total): """Count the number of True Negatives. Returns the number of correctly predicted non-links, also called the number of True Negatives (TN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. total: int, pandas.MultiIndex The count of all record pairs (both links and non-links). When the argument is a pandas.MultiIndex, the length of the index is used. Returns ------- int The number of correctly predicted non-links. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) if isinstance(total, pandas.MultiIndex): total = len(total) return int(total) - len(links_true | links_pred)
[ "def", "true_negatives", "(", "links_true", ",", "links_pred", ",", "total", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "if", "isinstance", "(", "total", ",", "pandas", ...
Count the number of True Negatives. Returns the number of correctly predicted non-links, also called the number of True Negatives (TN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. total: int, pandas.MultiIndex The count of all record pairs (both links and non-links). When the argument is a pandas.MultiIndex, the length of the index is used. Returns ------- int The number of correctly predicted non-links.
[ "Count", "the", "number", "of", "True", "Negatives", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L152-L181
train
206,509
J535D165/recordlinkage
recordlinkage/measures.py
false_positives
def false_positives(links_true, links_pred): """Count the number of False Positives. Returns the number of incorrect predictions of true non-links. (true non- links, but predicted as links). This value is known as the number of False Positives (FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false positives. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_pred.difference(links_true))
python
def false_positives(links_true, links_pred): """Count the number of False Positives. Returns the number of incorrect predictions of true non-links. (true non- links, but predicted as links). This value is known as the number of False Positives (FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false positives. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_pred.difference(links_true))
[ "def", "false_positives", "(", "links_true", ",", "links_pred", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "return", "len", "(", "links_pred", ".", "difference", "(", "lin...
Count the number of False Positives. Returns the number of incorrect predictions of true non-links. (true non- links, but predicted as links). This value is known as the number of False Positives (FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false positives.
[ "Count", "the", "number", "of", "False", "Positives", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L184-L208
train
206,510
J535D165/recordlinkage
recordlinkage/measures.py
false_negatives
def false_negatives(links_true, links_pred): """Count the number of False Negatives. Returns the number of incorrect predictions of true links. (true links, but predicted as non-links). This value is known as the number of False Negatives (FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false negatives. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_true.difference(links_pred))
python
def false_negatives(links_true, links_pred): """Count the number of False Negatives. Returns the number of incorrect predictions of true links. (true links, but predicted as non-links). This value is known as the number of False Negatives (FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false negatives. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) return len(links_true.difference(links_pred))
[ "def", "false_negatives", "(", "links_true", ",", "links_pred", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "return", "len", "(", "links_true", ".", "difference", "(", "lin...
Count the number of False Negatives. Returns the number of incorrect predictions of true links. (true links, but predicted as non-links). This value is known as the number of False Negatives (FN). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. Returns ------- int The number of false negatives.
[ "Count", "the", "number", "of", "False", "Negatives", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L211-L235
train
206,511
J535D165/recordlinkage
recordlinkage/measures.py
confusion_matrix
def confusion_matrix(links_true, links_pred, total=None): """Compute the confusion matrix. The confusion matrix is of the following form: +----------------------+-----------------------+----------------------+ | | Predicted Positives | Predicted Negatives | +======================+=======================+======================+ | **True Positives** | True Positives (TP) | False Negatives (FN) | +----------------------+-----------------------+----------------------+ | **True Negatives** | False Positives (FP) | True Negatives (TN) | +----------------------+-----------------------+----------------------+ The confusion matrix is an informative way to analyse a prediction. The matrix can used to compute measures like precision and recall. The count of true prositives is [0,0], false negatives is [0,1], true negatives is [1,1] and false positives is [1,0]. Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. total: int, pandas.MultiIndex The count of all record pairs (both links and non-links). When the argument is a pandas.MultiIndex, the length of the index is used. If the total is None, the number of True Negatives is not computed. Default None. Returns ------- numpy.array The confusion matrix with TP, TN, FN, FP values. Note ---- The number of True Negatives is computed based on the total argument. This argument is the number of record pairs of the entire matrix. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) tp = true_positives(links_true, links_pred) fp = false_positives(links_true, links_pred) fn = false_negatives(links_true, links_pred) if total is None: tn = numpy.nan else: tn = true_negatives(links_true, links_pred, total) return numpy.array([[tp, fn], [fp, tn]])
python
def confusion_matrix(links_true, links_pred, total=None): """Compute the confusion matrix. The confusion matrix is of the following form: +----------------------+-----------------------+----------------------+ | | Predicted Positives | Predicted Negatives | +======================+=======================+======================+ | **True Positives** | True Positives (TP) | False Negatives (FN) | +----------------------+-----------------------+----------------------+ | **True Negatives** | False Positives (FP) | True Negatives (TN) | +----------------------+-----------------------+----------------------+ The confusion matrix is an informative way to analyse a prediction. The matrix can used to compute measures like precision and recall. The count of true prositives is [0,0], false negatives is [0,1], true negatives is [1,1] and false positives is [1,0]. Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. total: int, pandas.MultiIndex The count of all record pairs (both links and non-links). When the argument is a pandas.MultiIndex, the length of the index is used. If the total is None, the number of True Negatives is not computed. Default None. Returns ------- numpy.array The confusion matrix with TP, TN, FN, FP values. Note ---- The number of True Negatives is computed based on the total argument. This argument is the number of record pairs of the entire matrix. """ links_true = _get_multiindex(links_true) links_pred = _get_multiindex(links_pred) tp = true_positives(links_true, links_pred) fp = false_positives(links_true, links_pred) fn = false_negatives(links_true, links_pred) if total is None: tn = numpy.nan else: tn = true_negatives(links_true, links_pred, total) return numpy.array([[tp, fn], [fp, tn]])
[ "def", "confusion_matrix", "(", "links_true", ",", "links_pred", ",", "total", "=", "None", ")", ":", "links_true", "=", "_get_multiindex", "(", "links_true", ")", "links_pred", "=", "_get_multiindex", "(", "links_pred", ")", "tp", "=", "true_positives", "(", ...
Compute the confusion matrix. The confusion matrix is of the following form: +----------------------+-----------------------+----------------------+ | | Predicted Positives | Predicted Negatives | +======================+=======================+======================+ | **True Positives** | True Positives (TP) | False Negatives (FN) | +----------------------+-----------------------+----------------------+ | **True Negatives** | False Positives (FP) | True Negatives (TN) | +----------------------+-----------------------+----------------------+ The confusion matrix is an informative way to analyse a prediction. The matrix can used to compute measures like precision and recall. The count of true prositives is [0,0], false negatives is [0,1], true negatives is [1,1] and false positives is [1,0]. Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series The predicted links. total: int, pandas.MultiIndex The count of all record pairs (both links and non-links). When the argument is a pandas.MultiIndex, the length of the index is used. If the total is None, the number of True Negatives is not computed. Default None. Returns ------- numpy.array The confusion matrix with TP, TN, FN, FP values. Note ---- The number of True Negatives is computed based on the total argument. This argument is the number of record pairs of the entire matrix.
[ "Compute", "the", "confusion", "matrix", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/measures.py#L238-L292
train
206,512
J535D165/recordlinkage
recordlinkage/contrib/compare/random/random.py
RandomContinuous.compute
def compute(self, pairs, x=None, x_link=None): """Return continuous random values for each record pair. Parameters ---------- pairs : pandas.MultiIndex A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to link. x : pandas.DataFrame The DataFrame to link. If `x_link` is given, the comparing is a linking problem. If `x_link` is not given, the problem is one of deduplication. x_link : pandas.DataFrame, optional The second DataFrame. Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tuple with multiple pandas.Series, pandas.DataFrame, numpy.ndarray objects. """ df_empty = pd.DataFrame(index=pairs) return self._compute( tuple([df_empty]), tuple([df_empty]) )
python
def compute(self, pairs, x=None, x_link=None): """Return continuous random values for each record pair. Parameters ---------- pairs : pandas.MultiIndex A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to link. x : pandas.DataFrame The DataFrame to link. If `x_link` is given, the comparing is a linking problem. If `x_link` is not given, the problem is one of deduplication. x_link : pandas.DataFrame, optional The second DataFrame. Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tuple with multiple pandas.Series, pandas.DataFrame, numpy.ndarray objects. """ df_empty = pd.DataFrame(index=pairs) return self._compute( tuple([df_empty]), tuple([df_empty]) )
[ "def", "compute", "(", "self", ",", "pairs", ",", "x", "=", "None", ",", "x_link", "=", "None", ")", ":", "df_empty", "=", "pd", ".", "DataFrame", "(", "index", "=", "pairs", ")", "return", "self", ".", "_compute", "(", "tuple", "(", "[", "df_empty...
Return continuous random values for each record pair. Parameters ---------- pairs : pandas.MultiIndex A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to link. x : pandas.DataFrame The DataFrame to link. If `x_link` is given, the comparing is a linking problem. If `x_link` is not given, the problem is one of deduplication. x_link : pandas.DataFrame, optional The second DataFrame. Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tuple with multiple pandas.Series, pandas.DataFrame, numpy.ndarray objects.
[ "Return", "continuous", "random", "values", "for", "each", "record", "pair", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/contrib/compare/random/random.py#L80-L107
train
206,513
J535D165/recordlinkage
recordlinkage/base.py
_parallel_compare_helper
def _parallel_compare_helper(class_obj, pairs, x, x_link=None): """Internal function to overcome pickling problem in python2.""" return class_obj._compute(pairs, x, x_link)
python
def _parallel_compare_helper(class_obj, pairs, x, x_link=None): """Internal function to overcome pickling problem in python2.""" return class_obj._compute(pairs, x, x_link)
[ "def", "_parallel_compare_helper", "(", "class_obj", ",", "pairs", ",", "x", ",", "x_link", "=", "None", ")", ":", "return", "class_obj", ".", "_compute", "(", "pairs", ",", "x", ",", "x_link", ")" ]
Internal function to overcome pickling problem in python2.
[ "Internal", "function", "to", "overcome", "pickling", "problem", "in", "python2", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L35-L37
train
206,514
J535D165/recordlinkage
recordlinkage/base.py
chunk_pandas
def chunk_pandas(frame_or_series, chunksize=None): """Chunk a frame into smaller, equal parts.""" if not isinstance(chunksize, int): raise ValueError('argument chunksize needs to be integer type') bins = np.arange(0, len(frame_or_series), step=chunksize) for b in bins: yield frame_or_series[b:b + chunksize]
python
def chunk_pandas(frame_or_series, chunksize=None): """Chunk a frame into smaller, equal parts.""" if not isinstance(chunksize, int): raise ValueError('argument chunksize needs to be integer type') bins = np.arange(0, len(frame_or_series), step=chunksize) for b in bins: yield frame_or_series[b:b + chunksize]
[ "def", "chunk_pandas", "(", "frame_or_series", ",", "chunksize", "=", "None", ")", ":", "if", "not", "isinstance", "(", "chunksize", ",", "int", ")", ":", "raise", "ValueError", "(", "'argument chunksize needs to be integer type'", ")", "bins", "=", "np", ".", ...
Chunk a frame into smaller, equal parts.
[ "Chunk", "a", "frame", "into", "smaller", "equal", "parts", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L40-L49
train
206,515
J535D165/recordlinkage
recordlinkage/base.py
BaseIndex.add
def add(self, model): """Add a index method. This method is used to add index algorithms. If multiple algorithms are added, the union of the record pairs from the algorithm is taken. Parameters ---------- model : list, class A (list of) index algorithm(s) from :mod:`recordlinkage.index`. """ if isinstance(model, list): self.algorithms = self.algorithms + model else: self.algorithms.append(model)
python
def add(self, model): """Add a index method. This method is used to add index algorithms. If multiple algorithms are added, the union of the record pairs from the algorithm is taken. Parameters ---------- model : list, class A (list of) index algorithm(s) from :mod:`recordlinkage.index`. """ if isinstance(model, list): self.algorithms = self.algorithms + model else: self.algorithms.append(model)
[ "def", "add", "(", "self", ",", "model", ")", ":", "if", "isinstance", "(", "model", ",", "list", ")", ":", "self", ".", "algorithms", "=", "self", ".", "algorithms", "+", "model", "else", ":", "self", ".", "algorithms", ".", "append", "(", "model", ...
Add a index method. This method is used to add index algorithms. If multiple algorithms are added, the union of the record pairs from the algorithm is taken. Parameters ---------- model : list, class A (list of) index algorithm(s) from :mod:`recordlinkage.index`.
[ "Add", "a", "index", "method", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L83-L98
train
206,516
J535D165/recordlinkage
recordlinkage/base.py
BaseIndexAlgorithm._dedup_index
def _dedup_index(self, df_a): """Build an index for deduplicating a dataset. Parameters ---------- df_a : (tuple of) pandas.Series The data of the DataFrame to build the index with. Returns ------- pandas.MultiIndex A pandas.MultiIndex with record pairs. Each record pair contains the index values of two records. The records are sampled from the lower triangular part of the matrix. """ pairs = self._link_index(df_a, df_a) # Remove all pairs not in the lower triangular part of the matrix. # This part can be inproved by not comparing the level values, but the # level itself. pairs = pairs[pairs.labels[0] > pairs.labels[1]] return pairs
python
def _dedup_index(self, df_a): """Build an index for deduplicating a dataset. Parameters ---------- df_a : (tuple of) pandas.Series The data of the DataFrame to build the index with. Returns ------- pandas.MultiIndex A pandas.MultiIndex with record pairs. Each record pair contains the index values of two records. The records are sampled from the lower triangular part of the matrix. """ pairs = self._link_index(df_a, df_a) # Remove all pairs not in the lower triangular part of the matrix. # This part can be inproved by not comparing the level values, but the # level itself. pairs = pairs[pairs.labels[0] > pairs.labels[1]] return pairs
[ "def", "_dedup_index", "(", "self", ",", "df_a", ")", ":", "pairs", "=", "self", ".", "_link_index", "(", "df_a", ",", "df_a", ")", "# Remove all pairs not in the lower triangular part of the matrix.", "# This part can be inproved by not comparing the level values, but the", ...
Build an index for deduplicating a dataset. Parameters ---------- df_a : (tuple of) pandas.Series The data of the DataFrame to build the index with. Returns ------- pandas.MultiIndex A pandas.MultiIndex with record pairs. Each record pair contains the index values of two records. The records are sampled from the lower triangular part of the matrix.
[ "Build", "an", "index", "for", "deduplicating", "a", "dataset", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L268-L290
train
206,517
J535D165/recordlinkage
recordlinkage/base.py
BaseCompareFeature._compute
def _compute(self, left_on, right_on): """Compare the data on the left and right. :meth:`BaseCompareFeature._compute` and :meth:`BaseCompareFeature.compute` differ on the accepted arguments. `_compute` accepts indexed data while `compute` accepts the record pairs and the DataFrame's. Parameters ---------- left_on : (tuple of) pandas.Series Data to compare with `right_on` right_on : (tuple of) pandas.Series Data to compare with `left_on` Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tuple with multiple pandas.Series, pandas.DataFrame, numpy.ndarray objects. """ result = self._compute_vectorized(*tuple(left_on + right_on)) return result
python
def _compute(self, left_on, right_on): """Compare the data on the left and right. :meth:`BaseCompareFeature._compute` and :meth:`BaseCompareFeature.compute` differ on the accepted arguments. `_compute` accepts indexed data while `compute` accepts the record pairs and the DataFrame's. Parameters ---------- left_on : (tuple of) pandas.Series Data to compare with `right_on` right_on : (tuple of) pandas.Series Data to compare with `left_on` Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tuple with multiple pandas.Series, pandas.DataFrame, numpy.ndarray objects. """ result = self._compute_vectorized(*tuple(left_on + right_on)) return result
[ "def", "_compute", "(", "self", ",", "left_on", ",", "right_on", ")", ":", "result", "=", "self", ".", "_compute_vectorized", "(", "*", "tuple", "(", "left_on", "+", "right_on", ")", ")", "return", "result" ]
Compare the data on the left and right. :meth:`BaseCompareFeature._compute` and :meth:`BaseCompareFeature.compute` differ on the accepted arguments. `_compute` accepts indexed data while `compute` accepts the record pairs and the DataFrame's. Parameters ---------- left_on : (tuple of) pandas.Series Data to compare with `right_on` right_on : (tuple of) pandas.Series Data to compare with `left_on` Returns ------- pandas.Series, pandas.DataFrame, numpy.ndarray The result of comparing record pairs (the features). Can be a tuple with multiple pandas.Series, pandas.DataFrame, numpy.ndarray objects.
[ "Compare", "the", "data", "on", "the", "left", "and", "right", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L426-L450
train
206,518
J535D165/recordlinkage
recordlinkage/base.py
BaseCompare.compare_vectorized
def compare_vectorized(self, comp_func, labels_left, labels_right, *args, **kwargs): """Compute the similarity between values with a callable. This method initialises the comparing of values with a custom function/callable. The function/callable should accept numpy.ndarray's. Example ------- >>> comp = recordlinkage.Compare() >>> comp.compare_vectorized(custom_callable, 'first_name', 'name') >>> comp.compare(PAIRS, DATAFRAME1, DATAFRAME2) Parameters ---------- comp_func : function A comparison function. This function can be a built-in function or a user defined comparison function. The function should accept numpy.ndarray's as first two arguments. labels_left : label, pandas.Series, pandas.DataFrame The labels, Series or DataFrame to compare. labels_right : label, pandas.Series, pandas.DataFrame The labels, Series or DataFrame to compare. *args : Additional arguments to pass to callable comp_func. **kwargs : Additional keyword arguments to pass to callable comp_func. (keyword 'label' is reserved.) label : (list of) label(s) The name of the feature and the name of the column. IMPORTANT: This argument is a keyword argument and can not be part of the arguments of comp_func. """ label = kwargs.pop('label', None) if isinstance(labels_left, tuple): labels_left = list(labels_left) if isinstance(labels_right, tuple): labels_right = list(labels_right) feature = BaseCompareFeature( labels_left, labels_right, args, kwargs, label=label) feature._f_compare_vectorized = comp_func self.add(feature)
python
def compare_vectorized(self, comp_func, labels_left, labels_right, *args, **kwargs): """Compute the similarity between values with a callable. This method initialises the comparing of values with a custom function/callable. The function/callable should accept numpy.ndarray's. Example ------- >>> comp = recordlinkage.Compare() >>> comp.compare_vectorized(custom_callable, 'first_name', 'name') >>> comp.compare(PAIRS, DATAFRAME1, DATAFRAME2) Parameters ---------- comp_func : function A comparison function. This function can be a built-in function or a user defined comparison function. The function should accept numpy.ndarray's as first two arguments. labels_left : label, pandas.Series, pandas.DataFrame The labels, Series or DataFrame to compare. labels_right : label, pandas.Series, pandas.DataFrame The labels, Series or DataFrame to compare. *args : Additional arguments to pass to callable comp_func. **kwargs : Additional keyword arguments to pass to callable comp_func. (keyword 'label' is reserved.) label : (list of) label(s) The name of the feature and the name of the column. IMPORTANT: This argument is a keyword argument and can not be part of the arguments of comp_func. """ label = kwargs.pop('label', None) if isinstance(labels_left, tuple): labels_left = list(labels_left) if isinstance(labels_right, tuple): labels_right = list(labels_right) feature = BaseCompareFeature( labels_left, labels_right, args, kwargs, label=label) feature._f_compare_vectorized = comp_func self.add(feature)
[ "def", "compare_vectorized", "(", "self", ",", "comp_func", ",", "labels_left", ",", "labels_right", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "label", "=", "kwargs", ".", "pop", "(", "'label'", ",", "None", ")", "if", "isinstance", "(", "la...
Compute the similarity between values with a callable. This method initialises the comparing of values with a custom function/callable. The function/callable should accept numpy.ndarray's. Example ------- >>> comp = recordlinkage.Compare() >>> comp.compare_vectorized(custom_callable, 'first_name', 'name') >>> comp.compare(PAIRS, DATAFRAME1, DATAFRAME2) Parameters ---------- comp_func : function A comparison function. This function can be a built-in function or a user defined comparison function. The function should accept numpy.ndarray's as first two arguments. labels_left : label, pandas.Series, pandas.DataFrame The labels, Series or DataFrame to compare. labels_right : label, pandas.Series, pandas.DataFrame The labels, Series or DataFrame to compare. *args : Additional arguments to pass to callable comp_func. **kwargs : Additional keyword arguments to pass to callable comp_func. (keyword 'label' is reserved.) label : (list of) label(s) The name of the feature and the name of the column. IMPORTANT: This argument is a keyword argument and can not be part of the arguments of comp_func.
[ "Compute", "the", "similarity", "between", "values", "with", "a", "callable", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L584-L631
train
206,519
J535D165/recordlinkage
recordlinkage/base.py
BaseCompare._get_labels_left
def _get_labels_left(self, validate=None): """Get all labels of the left dataframe.""" labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_left) # check requested labels (for better error messages) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" raise KeyError(error_msg) return unique(labels)
python
def _get_labels_left(self, validate=None): """Get all labels of the left dataframe.""" labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_left) # check requested labels (for better error messages) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" raise KeyError(error_msg) return unique(labels)
[ "def", "_get_labels_left", "(", "self", ",", "validate", "=", "None", ")", ":", "labels", "=", "[", "]", "for", "compare_func", "in", "self", ".", "features", ":", "labels", "=", "labels", "+", "listify", "(", "compare_func", ".", "labels_left", ")", "# ...
Get all labels of the left dataframe.
[ "Get", "all", "labels", "of", "the", "left", "dataframe", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L633-L647
train
206,520
J535D165/recordlinkage
recordlinkage/base.py
BaseCompare._get_labels_right
def _get_labels_right(self, validate=None): """Get all labels of the right dataframe.""" labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_right) # check requested labels (for better error messages) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" raise KeyError(error_msg) return unique(labels)
python
def _get_labels_right(self, validate=None): """Get all labels of the right dataframe.""" labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_right) # check requested labels (for better error messages) if not is_label_dataframe(labels, validate): error_msg = "label is not found in the dataframe" raise KeyError(error_msg) return unique(labels)
[ "def", "_get_labels_right", "(", "self", ",", "validate", "=", "None", ")", ":", "labels", "=", "[", "]", "for", "compare_func", "in", "self", ".", "features", ":", "labels", "=", "labels", "+", "listify", "(", "compare_func", ".", "labels_right", ")", "...
Get all labels of the right dataframe.
[ "Get", "all", "labels", "of", "the", "right", "dataframe", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L649-L662
train
206,521
J535D165/recordlinkage
recordlinkage/base.py
BaseCompare._union
def _union(self, objs, index=None, column_i=0): """Make a union of the features. The term 'union' is based on the terminology of scikit-learn. """ feat_conc = [] for feat, label in objs: # result is tuple of results if isinstance(feat, tuple): if label is None: label = [None] * len(feat) partial_result = self._union( zip(feat, label), column_i=column_i) feat_conc.append(partial_result) column_i = column_i + partial_result.shape[1] # result is pandas.Series. elif isinstance(feat, pandas.Series): feat.reset_index(drop=True, inplace=True) if label is None: label = column_i feat.rename(label, inplace=True) feat_conc.append(feat) column_i = column_i + 1 # result is pandas.DataFrame elif isinstance(feat, pandas.DataFrame): feat.reset_index(drop=True, inplace=True) if label is None: label = np.arange(column_i, column_i + feat.shape[1]) feat.columns = label feat_conc.append(feat) column_i = column_i + feat.shape[1] # result is numpy 1d array elif is_numpy_like(feat) and len(feat.shape) == 1: if label is None: label = column_i f = pandas.Series(feat, name=label, copy=False) feat_conc.append(f) column_i = column_i + 1 # result is numpy 2d array elif is_numpy_like(feat) and len(feat.shape) == 2: if label is None: label = np.arange(column_i, column_i + feat.shape[1]) feat_df = pandas.DataFrame(feat, columns=label, copy=False) if label is None: feat_df.columns = [None for _ in range(feat_df.shape[1])] feat_conc.append(feat_df) column_i = column_i + feat.shape[1] # other results are not (yet) supported else: raise ValueError("expected numpy.ndarray or " "pandas object to be returned, " "got '{}'".format(feat.__class__.__name__)) result = pandas.concat(feat_conc, axis=1, copy=False) if index is not None: result.set_index(index, inplace=True) return result
python
def _union(self, objs, index=None, column_i=0): """Make a union of the features. The term 'union' is based on the terminology of scikit-learn. """ feat_conc = [] for feat, label in objs: # result is tuple of results if isinstance(feat, tuple): if label is None: label = [None] * len(feat) partial_result = self._union( zip(feat, label), column_i=column_i) feat_conc.append(partial_result) column_i = column_i + partial_result.shape[1] # result is pandas.Series. elif isinstance(feat, pandas.Series): feat.reset_index(drop=True, inplace=True) if label is None: label = column_i feat.rename(label, inplace=True) feat_conc.append(feat) column_i = column_i + 1 # result is pandas.DataFrame elif isinstance(feat, pandas.DataFrame): feat.reset_index(drop=True, inplace=True) if label is None: label = np.arange(column_i, column_i + feat.shape[1]) feat.columns = label feat_conc.append(feat) column_i = column_i + feat.shape[1] # result is numpy 1d array elif is_numpy_like(feat) and len(feat.shape) == 1: if label is None: label = column_i f = pandas.Series(feat, name=label, copy=False) feat_conc.append(f) column_i = column_i + 1 # result is numpy 2d array elif is_numpy_like(feat) and len(feat.shape) == 2: if label is None: label = np.arange(column_i, column_i + feat.shape[1]) feat_df = pandas.DataFrame(feat, columns=label, copy=False) if label is None: feat_df.columns = [None for _ in range(feat_df.shape[1])] feat_conc.append(feat_df) column_i = column_i + feat.shape[1] # other results are not (yet) supported else: raise ValueError("expected numpy.ndarray or " "pandas object to be returned, " "got '{}'".format(feat.__class__.__name__)) result = pandas.concat(feat_conc, axis=1, copy=False) if index is not None: result.set_index(index, inplace=True) return result
[ "def", "_union", "(", "self", ",", "objs", ",", "index", "=", "None", ",", "column_i", "=", "0", ")", ":", "feat_conc", "=", "[", "]", "for", "feat", ",", "label", "in", "objs", ":", "# result is tuple of results", "if", "isinstance", "(", "feat", ",",...
Make a union of the features. The term 'union' is based on the terminology of scikit-learn.
[ "Make", "a", "union", "of", "the", "features", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L753-L819
train
206,522
J535D165/recordlinkage
recordlinkage/base.py
BaseClassifier.predict
def predict(self, comparison_vectors): """Predict the class of the record pairs. Classify a set of record pairs based on their comparison vectors into matches, non-matches and possible matches. The classifier has to be trained to call this method. Parameters ---------- comparison_vectors : pandas.DataFrame Dataframe with comparison vectors. return_type : str Deprecated. Use recordlinkage.options instead. Use the option `recordlinkage.set_option('classification.return_type', 'index')` instead. Returns ------- pandas.Series A pandas Series with the labels 1 (for the matches) and 0 (for the non-matches). """ logging.info("Classification - predict matches and non-matches") # make the predicition prediction = self._predict(comparison_vectors.values) self._post_predict(prediction) # format and return the result return self._return_result(prediction, comparison_vectors)
python
def predict(self, comparison_vectors): """Predict the class of the record pairs. Classify a set of record pairs based on their comparison vectors into matches, non-matches and possible matches. The classifier has to be trained to call this method. Parameters ---------- comparison_vectors : pandas.DataFrame Dataframe with comparison vectors. return_type : str Deprecated. Use recordlinkage.options instead. Use the option `recordlinkage.set_option('classification.return_type', 'index')` instead. Returns ------- pandas.Series A pandas Series with the labels 1 (for the matches) and 0 (for the non-matches). """ logging.info("Classification - predict matches and non-matches") # make the predicition prediction = self._predict(comparison_vectors.values) self._post_predict(prediction) # format and return the result return self._return_result(prediction, comparison_vectors)
[ "def", "predict", "(", "self", ",", "comparison_vectors", ")", ":", "logging", ".", "info", "(", "\"Classification - predict matches and non-matches\"", ")", "# make the predicition", "prediction", "=", "self", ".", "_predict", "(", "comparison_vectors", ".", "values", ...
Predict the class of the record pairs. Classify a set of record pairs based on their comparison vectors into matches, non-matches and possible matches. The classifier has to be trained to call this method. Parameters ---------- comparison_vectors : pandas.DataFrame Dataframe with comparison vectors. return_type : str Deprecated. Use recordlinkage.options instead. Use the option `recordlinkage.set_option('classification.return_type', 'index')` instead. Returns ------- pandas.Series A pandas Series with the labels 1 (for the matches) and 0 (for the non-matches).
[ "Predict", "the", "class", "of", "the", "record", "pairs", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L1001-L1031
train
206,523
J535D165/recordlinkage
recordlinkage/base.py
BaseClassifier.prob
def prob(self, comparison_vectors, return_type=None): """Compute the probabilities for each record pair. For each pair of records, estimate the probability of being a match. Parameters ---------- comparison_vectors : pandas.DataFrame The dataframe with comparison vectors. return_type : str Deprecated. (default 'series') Returns ------- pandas.Series or numpy.ndarray The probability of being a match for each record pair. """ if return_type is not None: warnings.warn("The argument 'return_type' is removed. " "Default value is now 'series'.", VisibleDeprecationWarning, stacklevel=2) logging.info("Classification - compute probabilities") prob_match = self._prob_match(comparison_vectors.values) return pandas.Series(prob_match, index=comparison_vectors.index)
python
def prob(self, comparison_vectors, return_type=None): """Compute the probabilities for each record pair. For each pair of records, estimate the probability of being a match. Parameters ---------- comparison_vectors : pandas.DataFrame The dataframe with comparison vectors. return_type : str Deprecated. (default 'series') Returns ------- pandas.Series or numpy.ndarray The probability of being a match for each record pair. """ if return_type is not None: warnings.warn("The argument 'return_type' is removed. " "Default value is now 'series'.", VisibleDeprecationWarning, stacklevel=2) logging.info("Classification - compute probabilities") prob_match = self._prob_match(comparison_vectors.values) return pandas.Series(prob_match, index=comparison_vectors.index)
[ "def", "prob", "(", "self", ",", "comparison_vectors", ",", "return_type", "=", "None", ")", ":", "if", "return_type", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"The argument 'return_type' is removed. \"", "\"Default value is now 'series'.\"", ",", "...
Compute the probabilities for each record pair. For each pair of records, estimate the probability of being a match. Parameters ---------- comparison_vectors : pandas.DataFrame The dataframe with comparison vectors. return_type : str Deprecated. (default 'series') Returns ------- pandas.Series or numpy.ndarray The probability of being a match for each record pair.
[ "Compute", "the", "probabilities", "for", "each", "record", "pair", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L1047-L1073
train
206,524
J535D165/recordlinkage
recordlinkage/base.py
BaseClassifier._return_result
def _return_result(self, result, comparison_vectors=None): """Return different formatted classification results. """ return_type = cf.get_option('classification.return_type') if type(result) != np.ndarray: raise ValueError("numpy.ndarray expected.") # return the pandas.MultiIndex if return_type == 'index': return comparison_vectors.index[result.astype(bool)] # return a pandas.Series elif return_type == 'series': return pandas.Series( result, index=comparison_vectors.index, name='classification') # return a numpy.ndarray elif return_type == 'array': return result # return_type not known else: raise ValueError( "return_type {} unknown. Choose 'index', 'series' or " "'array'".format(return_type))
python
def _return_result(self, result, comparison_vectors=None): """Return different formatted classification results. """ return_type = cf.get_option('classification.return_type') if type(result) != np.ndarray: raise ValueError("numpy.ndarray expected.") # return the pandas.MultiIndex if return_type == 'index': return comparison_vectors.index[result.astype(bool)] # return a pandas.Series elif return_type == 'series': return pandas.Series( result, index=comparison_vectors.index, name='classification') # return a numpy.ndarray elif return_type == 'array': return result # return_type not known else: raise ValueError( "return_type {} unknown. Choose 'index', 'series' or " "'array'".format(return_type))
[ "def", "_return_result", "(", "self", ",", "result", ",", "comparison_vectors", "=", "None", ")", ":", "return_type", "=", "cf", ".", "get_option", "(", "'classification.return_type'", ")", "if", "type", "(", "result", ")", "!=", "np", ".", "ndarray", ":", ...
Return different formatted classification results.
[ "Return", "different", "formatted", "classification", "results", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/base.py#L1075-L1103
train
206,525
J535D165/recordlinkage
recordlinkage/datasets/generate.py
binary_vectors
def binary_vectors(n, n_match, m=[0.9] * 8, u=[0.1] * 8, random_state=None, return_links=False, dtype=np.int8): """Generate random binary comparison vectors. This function is used to generate random comparison vectors. The result of each comparison is a binary value (0 or 1). Parameters ---------- n : int The total number of comparison vectors. n_match : int The number of matching record pairs. m : list, default [0.9] * 8, optional A list of m probabilities of each partially identifying variable. The m probability is the probability that an identifier in matching record pairs agrees. u : list, default [0.9] * 8, optional A list of u probabilities of each partially identifying variable. The u probability is the probability that an identifier in non-matching record pairs agrees. random_state : int or numpy.random.RandomState, optional Seed for the random number generator with an integer or numpy RandomState object. return_links: bool When True, the function returns also the true links. dtype: numpy.dtype The dtype of each column in the returned DataFrame. Returns ------- pandas.DataFrame A dataframe with comparison vectors. """ if len(m) != len(u): raise ValueError("the length of 'm' is not equal the length of 'u'") if n_match >= n or n_match < 0: raise ValueError("the number of matches is bounded by [0, n]") # set the random seed np.random.seed(random_state) matches = [] nonmatches = [] sample_set = np.array([0, 1], dtype=dtype) for i, _ in enumerate(m): p_mi = [1 - m[i], m[i]] p_ui = [1 - u[i], u[i]] comp_mi = np.random.choice(sample_set, (n_match, 1), p=p_mi) comp_ui = np.random.choice(sample_set, (n - n_match, 1), p=p_ui) nonmatches.append(comp_ui) matches.append(comp_mi) match_block = np.concatenate(matches, axis=1) nonmatch_block = np.concatenate(nonmatches, axis=1) data_np = np.concatenate((match_block, nonmatch_block), axis=0) index_np = np.random.randint(1001, 1001 + n * 2, (n, 2)) data_col_names = ['c_%s' % (i + 1) for i in range(len(m))] data_mi = pd.MultiIndex.from_arrays([index_np[:, 0], index_np[:, 1]]) data_df = pd.DataFrame(data_np, index=data_mi, columns=data_col_names) features = data_df.sample(frac=1, random_state=random_state) if return_links: links = data_mi[:n_match] return features, links else: return features
python
def binary_vectors(n, n_match, m=[0.9] * 8, u=[0.1] * 8, random_state=None, return_links=False, dtype=np.int8): """Generate random binary comparison vectors. This function is used to generate random comparison vectors. The result of each comparison is a binary value (0 or 1). Parameters ---------- n : int The total number of comparison vectors. n_match : int The number of matching record pairs. m : list, default [0.9] * 8, optional A list of m probabilities of each partially identifying variable. The m probability is the probability that an identifier in matching record pairs agrees. u : list, default [0.9] * 8, optional A list of u probabilities of each partially identifying variable. The u probability is the probability that an identifier in non-matching record pairs agrees. random_state : int or numpy.random.RandomState, optional Seed for the random number generator with an integer or numpy RandomState object. return_links: bool When True, the function returns also the true links. dtype: numpy.dtype The dtype of each column in the returned DataFrame. Returns ------- pandas.DataFrame A dataframe with comparison vectors. """ if len(m) != len(u): raise ValueError("the length of 'm' is not equal the length of 'u'") if n_match >= n or n_match < 0: raise ValueError("the number of matches is bounded by [0, n]") # set the random seed np.random.seed(random_state) matches = [] nonmatches = [] sample_set = np.array([0, 1], dtype=dtype) for i, _ in enumerate(m): p_mi = [1 - m[i], m[i]] p_ui = [1 - u[i], u[i]] comp_mi = np.random.choice(sample_set, (n_match, 1), p=p_mi) comp_ui = np.random.choice(sample_set, (n - n_match, 1), p=p_ui) nonmatches.append(comp_ui) matches.append(comp_mi) match_block = np.concatenate(matches, axis=1) nonmatch_block = np.concatenate(nonmatches, axis=1) data_np = np.concatenate((match_block, nonmatch_block), axis=0) index_np = np.random.randint(1001, 1001 + n * 2, (n, 2)) data_col_names = ['c_%s' % (i + 1) for i in range(len(m))] data_mi = pd.MultiIndex.from_arrays([index_np[:, 0], index_np[:, 1]]) data_df = pd.DataFrame(data_np, index=data_mi, columns=data_col_names) features = data_df.sample(frac=1, random_state=random_state) if return_links: links = data_mi[:n_match] return features, links else: return features
[ "def", "binary_vectors", "(", "n", ",", "n_match", ",", "m", "=", "[", "0.9", "]", "*", "8", ",", "u", "=", "[", "0.1", "]", "*", "8", ",", "random_state", "=", "None", ",", "return_links", "=", "False", ",", "dtype", "=", "np", ".", "int8", ")...
Generate random binary comparison vectors. This function is used to generate random comparison vectors. The result of each comparison is a binary value (0 or 1). Parameters ---------- n : int The total number of comparison vectors. n_match : int The number of matching record pairs. m : list, default [0.9] * 8, optional A list of m probabilities of each partially identifying variable. The m probability is the probability that an identifier in matching record pairs agrees. u : list, default [0.9] * 8, optional A list of u probabilities of each partially identifying variable. The u probability is the probability that an identifier in non-matching record pairs agrees. random_state : int or numpy.random.RandomState, optional Seed for the random number generator with an integer or numpy RandomState object. return_links: bool When True, the function returns also the true links. dtype: numpy.dtype The dtype of each column in the returned DataFrame. Returns ------- pandas.DataFrame A dataframe with comparison vectors.
[ "Generate", "random", "binary", "comparison", "vectors", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/datasets/generate.py#L5-L83
train
206,526
J535D165/recordlinkage
recordlinkage/classifiers.py
FellegiSunter._match_class_pos
def _match_class_pos(self): """Return the position of the match class.""" # TODO: add notfitted warnings if self.kernel.classes_.shape[0] != 2: raise ValueError("Number of classes is {}, expected 2.".format( self.kernel.classes_.shape[0])) # # get the position of match probabilities # classes = list(self.kernel.classes_) # return classes.index(1) return 1
python
def _match_class_pos(self): """Return the position of the match class.""" # TODO: add notfitted warnings if self.kernel.classes_.shape[0] != 2: raise ValueError("Number of classes is {}, expected 2.".format( self.kernel.classes_.shape[0])) # # get the position of match probabilities # classes = list(self.kernel.classes_) # return classes.index(1) return 1
[ "def", "_match_class_pos", "(", "self", ")", ":", "# TODO: add notfitted warnings", "if", "self", ".", "kernel", ".", "classes_", ".", "shape", "[", "0", "]", "!=", "2", ":", "raise", "ValueError", "(", "\"Number of classes is {}, expected 2.\"", ".", "format", ...
Return the position of the match class.
[ "Return", "the", "position", "of", "the", "match", "class", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/classifiers.py#L73-L84
train
206,527
J535D165/recordlinkage
recordlinkage/classifiers.py
FellegiSunter._nonmatch_class_pos
def _nonmatch_class_pos(self): """Return the position of the non-match class.""" # TODO: add notfitted warnings if self.kernel.classes_.shape[0] != 2: raise ValueError("Number of classes is {}, expected 2.".format( self.kernel.classes_.shape[0])) # # get the position of match probabilities # classes = list(self.kernel.classes_) # return classes.index(0) return 0
python
def _nonmatch_class_pos(self): """Return the position of the non-match class.""" # TODO: add notfitted warnings if self.kernel.classes_.shape[0] != 2: raise ValueError("Number of classes is {}, expected 2.".format( self.kernel.classes_.shape[0])) # # get the position of match probabilities # classes = list(self.kernel.classes_) # return classes.index(0) return 0
[ "def", "_nonmatch_class_pos", "(", "self", ")", ":", "# TODO: add notfitted warnings", "if", "self", ".", "kernel", ".", "classes_", ".", "shape", "[", "0", "]", "!=", "2", ":", "raise", "ValueError", "(", "\"Number of classes is {}, expected 2.\"", ".", "format",...
Return the position of the non-match class.
[ "Return", "the", "position", "of", "the", "non", "-", "match", "class", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/classifiers.py#L86-L97
train
206,528
J535D165/recordlinkage
recordlinkage/classifiers.py
FellegiSunter.log_weights
def log_weights(self): """Log weights as described in the FS framework.""" m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(m - u)
python
def log_weights(self): """Log weights as described in the FS framework.""" m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(m - u)
[ "def", "log_weights", "(", "self", ")", ":", "m", "=", "self", ".", "kernel", ".", "feature_log_prob_", "[", "self", ".", "_match_class_pos", "(", ")", "]", "u", "=", "self", ".", "kernel", ".", "feature_log_prob_", "[", "self", ".", "_nonmatch_class_pos",...
Log weights as described in the FS framework.
[ "Log", "weights", "as", "described", "in", "the", "FS", "framework", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/classifiers.py#L155-L160
train
206,529
J535D165/recordlinkage
recordlinkage/classifiers.py
FellegiSunter.weights
def weights(self): """Weights as described in the FS framework.""" m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(numpy.exp(m - u))
python
def weights(self): """Weights as described in the FS framework.""" m = self.kernel.feature_log_prob_[self._match_class_pos()] u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()] return self._prob_inverse_transform(numpy.exp(m - u))
[ "def", "weights", "(", "self", ")", ":", "m", "=", "self", ".", "kernel", ".", "feature_log_prob_", "[", "self", ".", "_match_class_pos", "(", ")", "]", "u", "=", "self", ".", "kernel", ".", "feature_log_prob_", "[", "self", ".", "_nonmatch_class_pos", "...
Weights as described in the FS framework.
[ "Weights", "as", "described", "in", "the", "FS", "framework", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/classifiers.py#L200-L205
train
206,530
J535D165/recordlinkage
recordlinkage/classifiers.py
KMeansClassifier._initialise_classifier
def _initialise_classifier(self, comparison_vectors): """Set the centers of the clusters.""" # Set the start point of the classifier. self.kernel.init = numpy.array( [[0.05] * len(list(comparison_vectors)), [0.95] * len(list(comparison_vectors))])
python
def _initialise_classifier(self, comparison_vectors): """Set the centers of the clusters.""" # Set the start point of the classifier. self.kernel.init = numpy.array( [[0.05] * len(list(comparison_vectors)), [0.95] * len(list(comparison_vectors))])
[ "def", "_initialise_classifier", "(", "self", ",", "comparison_vectors", ")", ":", "# Set the start point of the classifier.", "self", ".", "kernel", ".", "init", "=", "numpy", ".", "array", "(", "[", "[", "0.05", "]", "*", "len", "(", "list", "(", "comparison...
Set the centers of the clusters.
[ "Set", "the", "centers", "of", "the", "clusters", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/classifiers.py#L281-L287
train
206,531
J535D165/recordlinkage
recordlinkage/utils.py
is_label_dataframe
def is_label_dataframe(label, df): """check column label existance""" setdiff = set(label) - set(df.columns.tolist()) if len(setdiff) == 0: return True else: return False
python
def is_label_dataframe(label, df): """check column label existance""" setdiff = set(label) - set(df.columns.tolist()) if len(setdiff) == 0: return True else: return False
[ "def", "is_label_dataframe", "(", "label", ",", "df", ")", ":", "setdiff", "=", "set", "(", "label", ")", "-", "set", "(", "df", ".", "columns", ".", "tolist", "(", ")", ")", "if", "len", "(", "setdiff", ")", "==", "0", ":", "return", "True", "el...
check column label existance
[ "check", "column", "label", "existance" ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/utils.py#L81-L89
train
206,532
J535D165/recordlinkage
recordlinkage/utils.py
listify
def listify(x, none_value=[]): """Make a list of the argument if it is not a list.""" if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif x is None: return none_value else: return [x]
python
def listify(x, none_value=[]): """Make a list of the argument if it is not a list.""" if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif x is None: return none_value else: return [x]
[ "def", "listify", "(", "x", ",", "none_value", "=", "[", "]", ")", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "return", "x", "elif", "isinstance", "(", "x", ",", "tuple", ")", ":", "return", "list", "(", "x", ")", "elif", "x", "i...
Make a list of the argument if it is not a list.
[ "Make", "a", "list", "of", "the", "argument", "if", "it", "is", "not", "a", "list", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/utils.py#L101-L111
train
206,533
J535D165/recordlinkage
recordlinkage/utils.py
multi_index_to_frame
def multi_index_to_frame(index): """ Replicates MultiIndex.to_frame, which was introduced in pandas 0.21, for the sake of backwards compatibility. """ return pandas.DataFrame(index.tolist(), index=index, columns=index.names)
python
def multi_index_to_frame(index): """ Replicates MultiIndex.to_frame, which was introduced in pandas 0.21, for the sake of backwards compatibility. """ return pandas.DataFrame(index.tolist(), index=index, columns=index.names)
[ "def", "multi_index_to_frame", "(", "index", ")", ":", "return", "pandas", ".", "DataFrame", "(", "index", ".", "tolist", "(", ")", ",", "index", "=", "index", ",", "columns", "=", "index", ".", "names", ")" ]
Replicates MultiIndex.to_frame, which was introduced in pandas 0.21, for the sake of backwards compatibility.
[ "Replicates", "MultiIndex", ".", "to_frame", "which", "was", "introduced", "in", "pandas", "0", ".", "21", "for", "the", "sake", "of", "backwards", "compatibility", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/utils.py#L131-L136
train
206,534
J535D165/recordlinkage
recordlinkage/utils.py
index_split
def index_split(index, chunks): """Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pandas.Index, pandas.MultiIndex A pandas.Index or pandas.MultiIndex to split into chunks. chunks : int The number of parts to split the index into. Returns ------- list A list with chunked pandas.Index or pandas.MultiIndex objects. """ Ntotal = index.shape[0] Nsections = int(chunks) if Nsections <= 0: raise ValueError('number sections must be larger than 0.') Neach_section, extras = divmod(Ntotal, Nsections) section_sizes = ([0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_section]) div_points = numpy.array(section_sizes).cumsum() sub_ind = [] for i in range(Nsections): st = div_points[i] end = div_points[i + 1] sub_ind.append(index[st:end]) return sub_ind
python
def index_split(index, chunks): """Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pandas.Index, pandas.MultiIndex A pandas.Index or pandas.MultiIndex to split into chunks. chunks : int The number of parts to split the index into. Returns ------- list A list with chunked pandas.Index or pandas.MultiIndex objects. """ Ntotal = index.shape[0] Nsections = int(chunks) if Nsections <= 0: raise ValueError('number sections must be larger than 0.') Neach_section, extras = divmod(Ntotal, Nsections) section_sizes = ([0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_section]) div_points = numpy.array(section_sizes).cumsum() sub_ind = [] for i in range(Nsections): st = div_points[i] end = div_points[i + 1] sub_ind.append(index[st:end]) return sub_ind
[ "def", "index_split", "(", "index", ",", "chunks", ")", ":", "Ntotal", "=", "index", ".", "shape", "[", "0", "]", "Nsections", "=", "int", "(", "chunks", ")", "if", "Nsections", "<=", "0", ":", "raise", "ValueError", "(", "'number sections must be larger t...
Function to split pandas.Index and pandas.MultiIndex objects. Split :class:`pandas.Index` and :class:`pandas.MultiIndex` objects into chunks. This function is based on :func:`numpy.array_split`. Parameters ---------- index : pandas.Index, pandas.MultiIndex A pandas.Index or pandas.MultiIndex to split into chunks. chunks : int The number of parts to split the index into. Returns ------- list A list with chunked pandas.Index or pandas.MultiIndex objects.
[ "Function", "to", "split", "pandas", ".", "Index", "and", "pandas", ".", "MultiIndex", "objects", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/utils.py#L139-L174
train
206,535
J535D165/recordlinkage
recordlinkage/utils.py
frame_indexing
def frame_indexing(frame, multi_index, level_i, indexing_type='label'): """Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The level of the multiIndex to index on. indexing_type : str The type of indexing. The value can be 'label' or 'position'. Default 'label'. """ if indexing_type == "label": data = frame.loc[multi_index.get_level_values(level_i)] data.index = multi_index elif indexing_type == "position": data = frame.iloc[multi_index.get_level_values(level_i)] data.index = multi_index else: raise ValueError("indexing_type needs to be 'label' or 'position'") return data
python
def frame_indexing(frame, multi_index, level_i, indexing_type='label'): """Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The level of the multiIndex to index on. indexing_type : str The type of indexing. The value can be 'label' or 'position'. Default 'label'. """ if indexing_type == "label": data = frame.loc[multi_index.get_level_values(level_i)] data.index = multi_index elif indexing_type == "position": data = frame.iloc[multi_index.get_level_values(level_i)] data.index = multi_index else: raise ValueError("indexing_type needs to be 'label' or 'position'") return data
[ "def", "frame_indexing", "(", "frame", ",", "multi_index", ",", "level_i", ",", "indexing_type", "=", "'label'", ")", ":", "if", "indexing_type", "==", "\"label\"", ":", "data", "=", "frame", ".", "loc", "[", "multi_index", ".", "get_level_values", "(", "lev...
Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The level of the multiIndex to index on. indexing_type : str The type of indexing. The value can be 'label' or 'position'. Default 'label'.
[ "Index", "dataframe", "based", "on", "one", "level", "of", "MultiIndex", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/utils.py#L185-L212
train
206,536
J535D165/recordlinkage
recordlinkage/utils.py
fillna
def fillna(series_or_arr, missing_value=0.0): """Fill missing values in pandas objects and numpy arrays. Arguments --------- series_or_arr : pandas.Series, numpy.ndarray The numpy array or pandas series for which the missing values need to be replaced. missing_value : float, int, str The value to replace the missing value with. Default 0.0. Returns ------- pandas.Series, numpy.ndarray The numpy array or pandas series with the missing values filled. """ if pandas.notnull(missing_value): if isinstance(series_or_arr, (numpy.ndarray)): series_or_arr[numpy.isnan(series_or_arr)] = missing_value else: series_or_arr.fillna(missing_value, inplace=True) return series_or_arr
python
def fillna(series_or_arr, missing_value=0.0): """Fill missing values in pandas objects and numpy arrays. Arguments --------- series_or_arr : pandas.Series, numpy.ndarray The numpy array or pandas series for which the missing values need to be replaced. missing_value : float, int, str The value to replace the missing value with. Default 0.0. Returns ------- pandas.Series, numpy.ndarray The numpy array or pandas series with the missing values filled. """ if pandas.notnull(missing_value): if isinstance(series_or_arr, (numpy.ndarray)): series_or_arr[numpy.isnan(series_or_arr)] = missing_value else: series_or_arr.fillna(missing_value, inplace=True) return series_or_arr
[ "def", "fillna", "(", "series_or_arr", ",", "missing_value", "=", "0.0", ")", ":", "if", "pandas", ".", "notnull", "(", "missing_value", ")", ":", "if", "isinstance", "(", "series_or_arr", ",", "(", "numpy", ".", "ndarray", ")", ")", ":", "series_or_arr", ...
Fill missing values in pandas objects and numpy arrays. Arguments --------- series_or_arr : pandas.Series, numpy.ndarray The numpy array or pandas series for which the missing values need to be replaced. missing_value : float, int, str The value to replace the missing value with. Default 0.0. Returns ------- pandas.Series, numpy.ndarray The numpy array or pandas series with the missing values filled.
[ "Fill", "missing", "values", "in", "pandas", "objects", "and", "numpy", "arrays", "." ]
87a5f4af904e0834047cd07ff1c70146b1e6d693
https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/utils.py#L215-L239
train
206,537
chrisdev/django-pandas
django_pandas/utils.py
get_related_model
def get_related_model(field): """Gets the related model from a related field""" model = None if hasattr(field, 'related_model') and field.related_model: # pragma: no cover model = field.related_model # Django<1.8 doesn't have the related_model API, so we need to use rel, # which was removed in Django 2.0 elif hasattr(field, 'rel') and field.rel: # pragma: no cover model = field.rel.to return model
python
def get_related_model(field): """Gets the related model from a related field""" model = None if hasattr(field, 'related_model') and field.related_model: # pragma: no cover model = field.related_model # Django<1.8 doesn't have the related_model API, so we need to use rel, # which was removed in Django 2.0 elif hasattr(field, 'rel') and field.rel: # pragma: no cover model = field.rel.to return model
[ "def", "get_related_model", "(", "field", ")", ":", "model", "=", "None", "if", "hasattr", "(", "field", ",", "'related_model'", ")", "and", "field", ".", "related_model", ":", "# pragma: no cover", "model", "=", "field", ".", "related_model", "# Django<1.8 doe...
Gets the related model from a related field
[ "Gets", "the", "related", "model", "from", "a", "related", "field" ]
8276d699f25dca7da58e6c3fcebbd46e1c3e35e9
https://github.com/chrisdev/django-pandas/blob/8276d699f25dca7da58e6c3fcebbd46e1c3e35e9/django_pandas/utils.py#L86-L97
train
206,538
chrisdev/django-pandas
django_pandas/managers.py
DataFrameQuerySet.to_timeseries
def to_timeseries(self, fieldnames=(), verbose=True, index=None, storage='wide', values=None, pivot_columns=None, freq=None, coerce_float=True, rs_kwargs=None): """ A convenience method for creating a time series DataFrame i.e the DataFrame index will be an instance of DateTime or PeriodIndex Parameters ---------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name separated by double underscores and refer to a field in a related model. index: specify the field to use for the index. If the index field is not in fieldnames it will be appended. This is mandatory for timeseries. storage: Specify if the queryset uses the ``wide`` format date | col1| col2| col3| -----------|------|-----|-----| 2001-01-01-| 100.5| 23.3| 2.2| 2001-02-01-| 106.3| 17.0| 4.6| 2001-03-01-| 111.7| 11.1| 0.7| or the `long` format. date |values| names| -----------|------|------| 2001-01-01-| 100.5| col1| 2001-02-01-| 106.3| col1| 2001-03-01-| 111.7| col1| 2001-01-01-| 23.3| col2| 2001-02-01-| 17.0| col2| 2001-01-01-| 23.3| col2| 2001-02-01-| 2.2| col3| 2001-03-01-| 4.6| col3| 2001-03-01-| 0.7| col3| pivot_columns: Required once the you specify `long` format storage. This could either be a list or string identifying the field name or combination of field. If the pivot_column is a single column then the unique values in this column become a new columns in the DataFrame If the pivot column is a list the values in these columns are concatenated (using the '-' as a separator) and these values are used for the new timeseries columns values: Also required if you utilize the `long` storage the values column name is use for populating new frame values freq: The offset string or object representing a target conversion rs_kwargs: A dictonary of keyword arguments based on the ``pandas.DataFrame.resample`` method verbose: If this is ``True`` then populate the DataFrame with the human readable versions of any foreign key fields else use the primary keys values else use the actual values set in the model. coerce_float: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point. """ assert index is not None, 'You must supply an index field' assert storage in ('wide', 'long'), 'storage must be wide or long' if rs_kwargs is None: rs_kwargs = {} if storage == 'wide': df = self.to_dataframe(fieldnames, verbose=verbose, index=index, coerce_float=coerce_float, datetime_index=True) else: df = self.to_dataframe(fieldnames, verbose=verbose, coerce_float=coerce_float, datetime_index=True) assert values is not None, 'You must specify a values field' assert pivot_columns is not None, 'You must specify pivot_columns' if isinstance(pivot_columns, (tuple, list)): df['combined_keys'] = '' for c in pivot_columns: df['combined_keys'] += df[c].str.upper() + '.' df['combined_keys'] += values.lower() df = df.pivot(index=index, columns='combined_keys', values=values) else: df = df.pivot(index=index, columns=pivot_columns, values=values) if freq is not None: df = df.resample(freq, **rs_kwargs) return df
python
def to_timeseries(self, fieldnames=(), verbose=True, index=None, storage='wide', values=None, pivot_columns=None, freq=None, coerce_float=True, rs_kwargs=None): """ A convenience method for creating a time series DataFrame i.e the DataFrame index will be an instance of DateTime or PeriodIndex Parameters ---------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name separated by double underscores and refer to a field in a related model. index: specify the field to use for the index. If the index field is not in fieldnames it will be appended. This is mandatory for timeseries. storage: Specify if the queryset uses the ``wide`` format date | col1| col2| col3| -----------|------|-----|-----| 2001-01-01-| 100.5| 23.3| 2.2| 2001-02-01-| 106.3| 17.0| 4.6| 2001-03-01-| 111.7| 11.1| 0.7| or the `long` format. date |values| names| -----------|------|------| 2001-01-01-| 100.5| col1| 2001-02-01-| 106.3| col1| 2001-03-01-| 111.7| col1| 2001-01-01-| 23.3| col2| 2001-02-01-| 17.0| col2| 2001-01-01-| 23.3| col2| 2001-02-01-| 2.2| col3| 2001-03-01-| 4.6| col3| 2001-03-01-| 0.7| col3| pivot_columns: Required once the you specify `long` format storage. This could either be a list or string identifying the field name or combination of field. If the pivot_column is a single column then the unique values in this column become a new columns in the DataFrame If the pivot column is a list the values in these columns are concatenated (using the '-' as a separator) and these values are used for the new timeseries columns values: Also required if you utilize the `long` storage the values column name is use for populating new frame values freq: The offset string or object representing a target conversion rs_kwargs: A dictonary of keyword arguments based on the ``pandas.DataFrame.resample`` method verbose: If this is ``True`` then populate the DataFrame with the human readable versions of any foreign key fields else use the primary keys values else use the actual values set in the model. coerce_float: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point. """ assert index is not None, 'You must supply an index field' assert storage in ('wide', 'long'), 'storage must be wide or long' if rs_kwargs is None: rs_kwargs = {} if storage == 'wide': df = self.to_dataframe(fieldnames, verbose=verbose, index=index, coerce_float=coerce_float, datetime_index=True) else: df = self.to_dataframe(fieldnames, verbose=verbose, coerce_float=coerce_float, datetime_index=True) assert values is not None, 'You must specify a values field' assert pivot_columns is not None, 'You must specify pivot_columns' if isinstance(pivot_columns, (tuple, list)): df['combined_keys'] = '' for c in pivot_columns: df['combined_keys'] += df[c].str.upper() + '.' df['combined_keys'] += values.lower() df = df.pivot(index=index, columns='combined_keys', values=values) else: df = df.pivot(index=index, columns=pivot_columns, values=values) if freq is not None: df = df.resample(freq, **rs_kwargs) return df
[ "def", "to_timeseries", "(", "self", ",", "fieldnames", "=", "(", ")", ",", "verbose", "=", "True", ",", "index", "=", "None", ",", "storage", "=", "'wide'", ",", "values", "=", "None", ",", "pivot_columns", "=", "None", ",", "freq", "=", "None", ","...
A convenience method for creating a time series DataFrame i.e the DataFrame index will be an instance of DateTime or PeriodIndex Parameters ---------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name separated by double underscores and refer to a field in a related model. index: specify the field to use for the index. If the index field is not in fieldnames it will be appended. This is mandatory for timeseries. storage: Specify if the queryset uses the ``wide`` format date | col1| col2| col3| -----------|------|-----|-----| 2001-01-01-| 100.5| 23.3| 2.2| 2001-02-01-| 106.3| 17.0| 4.6| 2001-03-01-| 111.7| 11.1| 0.7| or the `long` format. date |values| names| -----------|------|------| 2001-01-01-| 100.5| col1| 2001-02-01-| 106.3| col1| 2001-03-01-| 111.7| col1| 2001-01-01-| 23.3| col2| 2001-02-01-| 17.0| col2| 2001-01-01-| 23.3| col2| 2001-02-01-| 2.2| col3| 2001-03-01-| 4.6| col3| 2001-03-01-| 0.7| col3| pivot_columns: Required once the you specify `long` format storage. This could either be a list or string identifying the field name or combination of field. If the pivot_column is a single column then the unique values in this column become a new columns in the DataFrame If the pivot column is a list the values in these columns are concatenated (using the '-' as a separator) and these values are used for the new timeseries columns values: Also required if you utilize the `long` storage the values column name is use for populating new frame values freq: The offset string or object representing a target conversion rs_kwargs: A dictonary of keyword arguments based on the ``pandas.DataFrame.resample`` method verbose: If this is ``True`` then populate the DataFrame with the human readable versions of any foreign key fields else use the primary keys values else use the actual values set in the model. coerce_float: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point.
[ "A", "convenience", "method", "for", "creating", "a", "time", "series", "DataFrame", "i", ".", "e", "the", "DataFrame", "index", "will", "be", "an", "instance", "of", "DateTime", "or", "PeriodIndex" ]
8276d699f25dca7da58e6c3fcebbd46e1c3e35e9
https://github.com/chrisdev/django-pandas/blob/8276d699f25dca7da58e6c3fcebbd46e1c3e35e9/django_pandas/managers.py#L135-L238
train
206,539
chrisdev/django-pandas
django_pandas/managers.py
DataFrameQuerySet.to_dataframe
def to_dataframe(self, fieldnames=(), verbose=True, index=None, coerce_float=False, datetime_index=False): """ Returns a DataFrame from the queryset Paramaters ----------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name separated by double underscores and refer to a field in a related model. index: specify the field to use for the index. If the index field is not in fieldnames it will be appended. This is mandatory for timeseries. verbose: If this is ``True`` then populate the DataFrame with the human readable versions for foreign key fields else use the actual values set in the model coerce_float: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point. datetime_index: specify whether index should be converted to a DateTimeIndex. """ return read_frame(self, fieldnames=fieldnames, verbose=verbose, index_col=index, coerce_float=coerce_float, datetime_index=datetime_index)
python
def to_dataframe(self, fieldnames=(), verbose=True, index=None, coerce_float=False, datetime_index=False): """ Returns a DataFrame from the queryset Paramaters ----------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name separated by double underscores and refer to a field in a related model. index: specify the field to use for the index. If the index field is not in fieldnames it will be appended. This is mandatory for timeseries. verbose: If this is ``True`` then populate the DataFrame with the human readable versions for foreign key fields else use the actual values set in the model coerce_float: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point. datetime_index: specify whether index should be converted to a DateTimeIndex. """ return read_frame(self, fieldnames=fieldnames, verbose=verbose, index_col=index, coerce_float=coerce_float, datetime_index=datetime_index)
[ "def", "to_dataframe", "(", "self", ",", "fieldnames", "=", "(", ")", ",", "verbose", "=", "True", ",", "index", "=", "None", ",", "coerce_float", "=", "False", ",", "datetime_index", "=", "False", ")", ":", "return", "read_frame", "(", "self", ",", "f...
Returns a DataFrame from the queryset Paramaters ----------- fieldnames: The model field names(columns) to utilise in creating the DataFrame. You can span a relationships in the usual Django ORM way by using the foreign key field name separated by double underscores and refer to a field in a related model. index: specify the field to use for the index. If the index field is not in fieldnames it will be appended. This is mandatory for timeseries. verbose: If this is ``True`` then populate the DataFrame with the human readable versions for foreign key fields else use the actual values set in the model coerce_float: Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point. datetime_index: specify whether index should be converted to a DateTimeIndex.
[ "Returns", "a", "DataFrame", "from", "the", "queryset" ]
8276d699f25dca7da58e6c3fcebbd46e1c3e35e9
https://github.com/chrisdev/django-pandas/blob/8276d699f25dca7da58e6c3fcebbd46e1c3e35e9/django_pandas/managers.py#L240-L272
train
206,540
chrisdev/django-pandas
django_pandas/io.py
read_frame
def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False, verbose=True, datetime_index=False): """ Returns a dataframe from a QuerySet Optionally specify the field names/columns to utilize and a field as the index Parameters ---------- qs: The Django QuerySet. fieldnames: The model field names to use in creating the frame. You can span a relationship in the usual Django way by using double underscores to specify a related field in another model You can span a relationship in the usual Django way by using double underscores to specify a related field in another model index_col: specify the field to use for the index. If the index field is not in the field list it will be appended coerce_float : boolean, default False Attempt to convert values to non-string, non-numeric data (like decimal.Decimal) to floating point, useful for SQL result sets verbose: boolean If this is ``True`` then populate the DataFrame with the human readable versions of any foreign key fields else use the primary keys values. The human readable version of the foreign key field is defined in the ``__unicode__`` or ``__str__`` methods of the related class definition datetime_index: specify whether index should be converted to a DateTimeIndex. """ if fieldnames: fieldnames = pd.unique(fieldnames) if index_col is not None and index_col not in fieldnames: # Add it to the field names if not already there fieldnames = tuple(fieldnames) + (index_col,) fields = to_fields(qs, fieldnames) elif is_values_queryset(qs): if django.VERSION < (1, 9): # pragma: no cover annotation_field_names = list(qs.query.annotation_select) if annotation_field_names is None: annotation_field_names = [] extra_field_names = qs.extra_names if extra_field_names is None: extra_field_names = [] select_field_names = qs.field_names else: # pragma: no cover annotation_field_names = list(qs.query.annotation_select) extra_field_names = list(qs.query.extra_select) select_field_names = list(qs.query.values_select) fieldnames = select_field_names + annotation_field_names + \ extra_field_names fields = [None if '__' in f else qs.model._meta.get_field(f) for f in select_field_names] + \ [None] * (len(annotation_field_names) + len(extra_field_names)) uniq_fields = set() fieldnames, fields = zip( *(f for f in zip(fieldnames, fields) if f[0] not in uniq_fields and not uniq_fields.add(f[0]))) else: fields = qs.model._meta.fields fieldnames = [f.name for f in fields] fieldnames += list(qs.query.annotation_select.keys()) if is_values_queryset(qs): recs = list(qs) else: recs = list(qs.values_list(*fieldnames)) df = pd.DataFrame.from_records(recs, columns=fieldnames, coerce_float=coerce_float) if verbose: update_with_verbose(df, fieldnames, fields) if index_col is not None: df.set_index(index_col, inplace=True) if datetime_index: df.index = pd.to_datetime(df.index, errors="ignore") return df
python
def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False, verbose=True, datetime_index=False): """ Returns a dataframe from a QuerySet Optionally specify the field names/columns to utilize and a field as the index Parameters ---------- qs: The Django QuerySet. fieldnames: The model field names to use in creating the frame. You can span a relationship in the usual Django way by using double underscores to specify a related field in another model You can span a relationship in the usual Django way by using double underscores to specify a related field in another model index_col: specify the field to use for the index. If the index field is not in the field list it will be appended coerce_float : boolean, default False Attempt to convert values to non-string, non-numeric data (like decimal.Decimal) to floating point, useful for SQL result sets verbose: boolean If this is ``True`` then populate the DataFrame with the human readable versions of any foreign key fields else use the primary keys values. The human readable version of the foreign key field is defined in the ``__unicode__`` or ``__str__`` methods of the related class definition datetime_index: specify whether index should be converted to a DateTimeIndex. """ if fieldnames: fieldnames = pd.unique(fieldnames) if index_col is not None and index_col not in fieldnames: # Add it to the field names if not already there fieldnames = tuple(fieldnames) + (index_col,) fields = to_fields(qs, fieldnames) elif is_values_queryset(qs): if django.VERSION < (1, 9): # pragma: no cover annotation_field_names = list(qs.query.annotation_select) if annotation_field_names is None: annotation_field_names = [] extra_field_names = qs.extra_names if extra_field_names is None: extra_field_names = [] select_field_names = qs.field_names else: # pragma: no cover annotation_field_names = list(qs.query.annotation_select) extra_field_names = list(qs.query.extra_select) select_field_names = list(qs.query.values_select) fieldnames = select_field_names + annotation_field_names + \ extra_field_names fields = [None if '__' in f else qs.model._meta.get_field(f) for f in select_field_names] + \ [None] * (len(annotation_field_names) + len(extra_field_names)) uniq_fields = set() fieldnames, fields = zip( *(f for f in zip(fieldnames, fields) if f[0] not in uniq_fields and not uniq_fields.add(f[0]))) else: fields = qs.model._meta.fields fieldnames = [f.name for f in fields] fieldnames += list(qs.query.annotation_select.keys()) if is_values_queryset(qs): recs = list(qs) else: recs = list(qs.values_list(*fieldnames)) df = pd.DataFrame.from_records(recs, columns=fieldnames, coerce_float=coerce_float) if verbose: update_with_verbose(df, fieldnames, fields) if index_col is not None: df.set_index(index_col, inplace=True) if datetime_index: df.index = pd.to_datetime(df.index, errors="ignore") return df
[ "def", "read_frame", "(", "qs", ",", "fieldnames", "=", "(", ")", ",", "index_col", "=", "None", ",", "coerce_float", "=", "False", ",", "verbose", "=", "True", ",", "datetime_index", "=", "False", ")", ":", "if", "fieldnames", ":", "fieldnames", "=", ...
Returns a dataframe from a QuerySet Optionally specify the field names/columns to utilize and a field as the index Parameters ---------- qs: The Django QuerySet. fieldnames: The model field names to use in creating the frame. You can span a relationship in the usual Django way by using double underscores to specify a related field in another model You can span a relationship in the usual Django way by using double underscores to specify a related field in another model index_col: specify the field to use for the index. If the index field is not in the field list it will be appended coerce_float : boolean, default False Attempt to convert values to non-string, non-numeric data (like decimal.Decimal) to floating point, useful for SQL result sets verbose: boolean If this is ``True`` then populate the DataFrame with the human readable versions of any foreign key fields else use the primary keys values. The human readable version of the foreign key field is defined in the ``__unicode__`` or ``__str__`` methods of the related class definition datetime_index: specify whether index should be converted to a DateTimeIndex.
[ "Returns", "a", "dataframe", "from", "a", "QuerySet" ]
8276d699f25dca7da58e6c3fcebbd46e1c3e35e9
https://github.com/chrisdev/django-pandas/blob/8276d699f25dca7da58e6c3fcebbd46e1c3e35e9/django_pandas/io.py#L35-L128
train
206,541
joowani/binarytree
binarytree/__init__.py
_is_balanced
def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1
python
def _is_balanced(root): """Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int """ if root is None: return 0 left = _is_balanced(root.left) if left < 0: return -1 right = _is_balanced(root.right) if right < 0: return -1 return -1 if abs(left - right) > 1 else max(left, right) + 1
[ "def", "_is_balanced", "(", "root", ")", ":", "if", "root", "is", "None", ":", "return", "0", "left", "=", "_is_balanced", "(", "root", ".", "left", ")", "if", "left", "<", "0", ":", "return", "-", "1", "right", "=", "_is_balanced", "(", "root", "....
Return the height if the binary tree is balanced, -1 otherwise. :param root: Root node of the binary tree. :type root: binarytree.Node | None :return: Height if the binary tree is balanced, -1 otherwise. :rtype: int
[ "Return", "the", "height", "if", "the", "binary", "tree", "is", "balanced", "-", "1", "otherwise", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L20-L36
train
206,542
joowani/binarytree
binarytree/__init__.py
_build_bst_from_sorted_values
def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root
python
def _build_bst_from_sorted_values(sorted_values): """Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node """ if len(sorted_values) == 0: return None mid_index = len(sorted_values) // 2 root = Node(sorted_values[mid_index]) root.left = _build_bst_from_sorted_values(sorted_values[:mid_index]) root.right = _build_bst_from_sorted_values(sorted_values[mid_index + 1:]) return root
[ "def", "_build_bst_from_sorted_values", "(", "sorted_values", ")", ":", "if", "len", "(", "sorted_values", ")", "==", "0", ":", "return", "None", "mid_index", "=", "len", "(", "sorted_values", ")", "//", "2", "root", "=", "Node", "(", "sorted_values", "[", ...
Recursively build a perfect BST from odd number of sorted values. :param sorted_values: Odd number of sorted values. :type sorted_values: [int | float] :return: Root node of the BST. :rtype: binarytree.Node
[ "Recursively", "build", "a", "perfect", "BST", "from", "odd", "number", "of", "sorted", "values", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L84-L98
train
206,543
joowani/binarytree
binarytree/__init__.py
_generate_random_leaf_count
def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count
python
def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naive way of mimicking normal distribution roll_1 = random.randint(0, half_leaf_count) roll_2 = random.randint(0, max_leaf_count - half_leaf_count) return roll_1 + roll_2 or half_leaf_count
[ "def", "_generate_random_leaf_count", "(", "height", ")", ":", "max_leaf_count", "=", "2", "**", "height", "half_leaf_count", "=", "max_leaf_count", "//", "2", "# A very naive way of mimicking normal distribution", "roll_1", "=", "random", ".", "randint", "(", "0", ",...
Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int
[ "Return", "a", "random", "leaf", "count", "for", "building", "binary", "trees", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L101-L115
train
206,544
joowani/binarytree
binarytree/__init__.py
_generate_random_node_values
def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values
python
def _generate_random_node_values(height): """Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int] """ max_node_count = 2 ** (height + 1) - 1 node_values = list(range(max_node_count)) random.shuffle(node_values) return node_values
[ "def", "_generate_random_node_values", "(", "height", ")", ":", "max_node_count", "=", "2", "**", "(", "height", "+", "1", ")", "-", "1", "node_values", "=", "list", "(", "range", "(", "max_node_count", ")", ")", "random", ".", "shuffle", "(", "node_values...
Return random node values for building binary trees. :param height: Height of the binary tree. :type height: int :return: Randomly generated node values. :rtype: [int]
[ "Return", "random", "node", "values", "for", "building", "binary", "trees", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L118-L129
train
206,545
joowani/binarytree
binarytree/__init__.py
_build_tree_string
def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end
python
def _build_tree_string(root, curr_index, index=False, delimiter='-'): """Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ if root is None: return [], 0, 0, 0 line1 = [] line2 = [] if index: node_repr = '{}{}{}'.format(curr_index, delimiter, root.value) else: node_repr = str(root.value) new_root_width = gap_size = len(node_repr) # Get the left and right sub-boxes, their widths, and root repr positions l_box, l_box_width, l_root_start, l_root_end = \ _build_tree_string(root.left, 2 * curr_index + 1, index, delimiter) r_box, r_box_width, r_root_start, r_root_end = \ _build_tree_string(root.right, 2 * curr_index + 2, index, delimiter) # Draw the branch connecting the current root node to the left sub-box # Pad the line with whitespaces where necessary if l_box_width > 0: l_root = (l_root_start + l_root_end) // 2 + 1 line1.append(' ' * (l_root + 1)) line1.append('_' * (l_box_width - l_root)) line2.append(' ' * l_root + '/') line2.append(' ' * (l_box_width - l_root)) new_root_start = l_box_width + 1 gap_size += 1 else: new_root_start = 0 # Draw the representation of the current root node line1.append(node_repr) line2.append(' ' * new_root_width) # Draw the branch connecting the current root node to the right sub-box # Pad the line with whitespaces where necessary if r_box_width > 0: r_root = (r_root_start + r_root_end) // 2 line1.append('_' * r_root) line1.append(' ' * (r_box_width - r_root + 1)) line2.append(' ' * r_root + '\\') line2.append(' ' * (r_box_width - r_root)) gap_size += 1 new_root_end = new_root_start + new_root_width - 1 # Combine the left and right sub-boxes with the branches drawn above gap = ' ' * gap_size new_box = [''.join(line1), ''.join(line2)] for i in range(max(len(l_box), len(r_box))): l_line = l_box[i] if i < len(l_box) else ' ' * l_box_width r_line = r_box[i] if i < len(r_box) else ' ' * r_box_width new_box.append(l_line + gap + r_line) # Return the new box, its width and its root repr positions return new_box, len(new_box[0]), new_root_start, new_root_end
[ "def", "_build_tree_string", "(", "root", ",", "curr_index", ",", "index", "=", "False", ",", "delimiter", "=", "'-'", ")", ":", "if", "root", "is", "None", ":", "return", "[", "]", ",", "0", ",", "0", ",", "0", "line1", "=", "[", "]", "line2", "...
Recursively walk down the binary tree and build a pretty-print string. In each recursive call, a "box" of characters visually representing the current (sub)tree is constructed line by line. Each line is padded with whitespaces to ensure all lines in the box have the same length. Then the box, its width, and start-end positions of its root node value repr string (required for drawing branches) are sent up to the parent call. The parent call then combines its left and right sub-boxes to build a larger box etc. :param root: Root node of the binary tree. :type root: binarytree.Node | None :param curr_index: Level-order_ index of the current node (root node is 0). :type curr_index: int :param index: If set to True, include the level-order_ node indexes using the following format: ``{index}{delimiter}{value}`` (default: False). :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: :return: Box of characters visually representing the current subtree, width of the box, and start-end positions of the repr string of the new root node value. :rtype: ([str], int, int, int) .. _Level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
[ "Recursively", "walk", "down", "the", "binary", "tree", "and", "build", "a", "pretty", "-", "print", "string", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L132-L215
train
206,546
joowani/binarytree
binarytree/__init__.py
build
def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None
python
def build(values): """Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0 """ nodes = [None if v is None else Node(v) for v in values] for index in range(1, len(nodes)): node = nodes[index] if node is not None: parent_index = (index - 1) // 2 parent = nodes[parent_index] if parent is None: raise NodeNotFoundError( 'parent node missing at index {}'.format(parent_index)) setattr(parent, 'left' if index % 2 else 'right', node) return nodes[0] if nodes else None
[ "def", "build", "(", "values", ")", ":", "nodes", "=", "[", "None", "if", "v", "is", "None", "else", "Node", "(", "v", ")", "for", "v", "in", "values", "]", "for", "index", "in", "range", "(", "1", ",", "len", "(", "nodes", ")", ")", ":", "no...
Build a tree from `list representation`_ and return its root node. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :param values: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :type values: [int | float | None] :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.NodeNotFoundError: If the list representation is malformed (e.g. a parent node is missing). **Example**: .. doctest:: >>> from binarytree import build >>> >>> root = build([1, 2, 3, None, 4]) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> .. doctest:: >>> from binarytree import build >>> >>> root = build([None, 2, 3]) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeNotFoundError: parent node missing at index 0
[ "Build", "a", "tree", "from", "list", "representation", "_", "and", "return", "its", "root", "node", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1654-L1709
train
206,547
joowani/binarytree
binarytree/__init__.py
tree
def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root
python
def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root
[ "def", "tree", "(", "height", "=", "3", ",", "is_perfect", "=", "False", ")", ":", "_validate_tree_height", "(", "height", ")", "values", "=", "_generate_random_node_values", "(", "height", ")", "if", "is_perfect", ":", "return", "build", "(", "values", ")",...
Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9
[ "Generate", "a", "random", "binary", "tree", "and", "return", "its", "root", "node", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1712-L1783
train
206,548
joowani/binarytree
binarytree/__init__.py
heap
def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
python
def heap(height=3, is_max=True, is_perfect=False): """Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if not is_perfect: # Randomly cut some of the leaf nodes away random_cut = random.randint(2 ** height, len(values)) values = values[:random_cut] if is_max: negated = [-v for v in values] heapq.heapify(negated) return build([-v for v in negated]) else: heapq.heapify(values) return build(values)
[ "def", "heap", "(", "height", "=", "3", ",", "is_max", "=", "True", ",", "is_perfect", "=", "False", ")", ":", "_validate_tree_height", "(", "height", ")", "values", "=", "_generate_random_node_values", "(", "height", ")", "if", "not", "is_perfect", ":", "...
Generate a random heap and return its root node. :param height: Height of the heap (default: 3, range: 0 - 9 inclusive). :type height: int :param is_max: If set to True (default: True), generate a max heap. If set to False, generate a min heap. A binary tree with only the root node is considered both a min and max heap. :type is_max: bool :param is_perfect: If set to True (default: False), a perfect heap with all levels filled is returned. If set to False, a perfect heap may still be generated by chance. :type is_perfect: bool :return: Root node of the heap. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import heap >>> >>> root = heap() >>> >>> root.height 3 >>> root.is_max_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(4, is_max=False) >>> >>> root.height 4 >>> root.is_min_heap True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(5, is_max=False, is_perfect=True) >>> >>> root.height 5 >>> root.is_min_heap True >>> root.is_perfect True .. doctest:: >>> from binarytree import heap >>> >>> root = heap(-1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9
[ "Generate", "a", "random", "heap", "and", "return", "its", "root", "node", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1852-L1929
train
206,549
joowani/binarytree
binarytree/__init__.py
Node.pprint
def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines)))
python
def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search """ lines = _build_tree_string(self, 0, index, delimiter)[0] print('\n' + '\n'.join((line.rstrip() for line in lines)))
[ "def", "pprint", "(", "self", ",", "index", "=", "False", ",", "delimiter", "=", "'-'", ")", ":", "lines", "=", "_build_tree_string", "(", "self", ",", "0", ",", "index", ",", "delimiter", ")", "[", "0", "]", "print", "(", "'\\n'", "+", "'\\n'", "....
Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). :type delimiter: str | unicode **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) # index: 0, value: 1 >>> root.left = Node(2) # index: 1, value: 2 >>> root.right = Node(3) # index: 2, value: 3 >>> root.left.right = Node(4) # index: 4, value: 4 >>> >>> root.pprint() <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.pprint(index=True) # Format: {index}-{value} <BLANKLINE> _____0-1_ / \\ 1-2_ 2-3 \\ 4-4 <BLANKLINE> .. note:: If you do not need level-order_ indexes in the output string, use :func:`binarytree.Node.__str__` instead. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
[ "Pretty", "-", "print", "the", "binary", "tree", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L700-L746
train
206,550
joowani/binarytree
binarytree/__init__.py
Node.validate
def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes
python
def validate(self): """Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0 """ has_more_nodes = True visited = set() to_visit = [self] index = 0 while has_more_nodes: has_more_nodes = False next_nodes = [] for node in to_visit: if node is None: next_nodes.extend((None, None)) else: if node in visited: raise NodeReferenceError( 'cyclic node reference at index {}'.format(index)) if not isinstance(node, Node): raise NodeTypeError( 'invalid node instance at index {}'.format(index)) if not isinstance(node.value, numbers.Number): raise NodeValueError( 'invalid node value at index {}'.format(index)) if node.left is not None or node.right is not None: has_more_nodes = True visited.add(node) next_nodes.extend((node.left, node.right)) index += 1 to_visit = next_nodes
[ "def", "validate", "(", "self", ")", ":", "has_more_nodes", "=", "True", "visited", "=", "set", "(", ")", "to_visit", "=", "[", "self", "]", "index", "=", "0", "while", "has_more_nodes", ":", "has_more_nodes", "=", "False", "next_nodes", "=", "[", "]", ...
Check if the binary tree is malformed. :raise binarytree.exceptions.NodeReferenceError: If there is a cyclic reference to a node in the binary tree. :raise binarytree.exceptions.NodeTypeError: If a node is not an instance of :class:`binarytree.Node`. :raise binarytree.exceptions.NodeValueError: If a node value is not a number (e.g. int, float). **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = root # Cyclic reference to root >>> >>> root.validate() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... NodeReferenceError: cyclic node reference at index 0
[ "Check", "if", "the", "binary", "tree", "is", "malformed", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L748-L801
train
206,551
joowani/binarytree
binarytree/__init__.py
Node.values
def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values
python
def values(self): """Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4] """ current_nodes = [self] has_more_nodes = True values = [] while has_more_nodes: has_more_nodes = False next_nodes = [] for node in current_nodes: if node is None: values.append(None) next_nodes.extend((None, None)) continue if node.left is not None or node.right is not None: has_more_nodes = True values.append(node.value) next_nodes.extend((node.left, node.right)) current_nodes = next_nodes # Get rid of trailing None's while values and values[-1] is None: values.pop() return values
[ "def", "values", "(", "self", ")", ":", "current_nodes", "=", "[", "self", "]", "has_more_nodes", "=", "True", "values", "=", "[", "]", "while", "has_more_nodes", ":", "has_more_nodes", "=", "False", "next_nodes", "=", "[", "]", "for", "node", "in", "cur...
Return the `list representation`_ of the binary tree. .. _list representation: https://en.wikipedia.org/wiki/Binary_tree#Arrays :return: List representation of the binary tree, which is a list of node values in breadth-first order starting from the root (current node). If a node is at index i, its left child is always at 2i + 1, right child at 2i + 2, and parent at index floor((i - 1) / 2). None indicates absence of a node at that index. See example below for an illustration. :rtype: [int | float | None] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> root.values [1, 2, 3, None, 4]
[ "Return", "the", "list", "representation", "_", "of", "the", "binary", "tree", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L804-L857
train
206,552
joowani/binarytree
binarytree/__init__.py
Node.leaves
def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves
python
def leaves(self): """Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)] """ current_nodes = [self] leaves = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: if node.left is None and node.right is None: leaves.append(node) continue if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return leaves
[ "def", "leaves", "(", "self", ")", ":", "current_nodes", "=", "[", "self", "]", "leaves", "=", "[", "]", "while", "len", "(", "current_nodes", ")", ">", "0", ":", "next_nodes", "=", "[", "]", "for", "node", "in", "current_nodes", ":", "if", "node", ...
Return the leaf nodes of the binary tree. A leaf node is any node that does not have child nodes. :return: List of leaf nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.right = Node(4) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 \\ 4 <BLANKLINE> >>> root.leaves [Node(3), Node(4)]
[ "Return", "the", "leaf", "nodes", "of", "the", "binary", "tree", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L860-L904
train
206,553
joowani/binarytree
binarytree/__init__.py
Node.properties
def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties
python
def properties(self): """Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True """ properties = _get_tree_properties(self) properties.update({ 'is_bst': _is_bst(self), 'is_balanced': _is_balanced(self) >= 0 }) return properties
[ "def", "properties", "(", "self", ")", ":", "properties", "=", "_get_tree_properties", "(", "self", ")", "properties", ".", "update", "(", "{", "'is_bst'", ":", "_is_bst", "(", "self", ")", ",", "'is_balanced'", ":", "_is_balanced", "(", "self", ")", ">=",...
Return various properties of the binary tree. :return: Binary tree properties. :rtype: dict **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> props = root.properties >>> >>> props['height'] # equivalent to root.height 2 >>> props['size'] # equivalent to root.size 5 >>> props['max_leaf_depth'] # equivalent to root.max_leaf_depth 2 >>> props['min_leaf_depth'] # equivalent to root.min_leaf_depth 1 >>> props['max_node_value'] # equivalent to root.max_node_value 5 >>> props['min_node_value'] # equivalent to root.min_node_value 1 >>> props['leaf_count'] # equivalent to root.leaf_count 3 >>> props['is_balanced'] # equivalent to root.is_balanced True >>> props['is_bst'] # equivalent to root.is_bst False >>> props['is_complete'] # equivalent to root.is_complete True >>> props['is_max_heap'] # equivalent to root.is_max_heap False >>> props['is_min_heap'] # equivalent to root.is_min_heap True >>> props['is_perfect'] # equivalent to root.is_perfect False >>> props['is_strict'] # equivalent to root.is_strict True
[ "Return", "various", "properties", "of", "the", "binary", "tree", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1388-L1441
train
206,554
joowani/binarytree
binarytree/__init__.py
Node.inorder
def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result
python
def inorder(self): """Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)] """ node_stack = [] result = [] node = self while True: if node is not None: node_stack.append(node) node = node.left elif len(node_stack) > 0: node = node_stack.pop() result.append(node) node = node.right else: break return result
[ "def", "inorder", "(", "self", ")", ":", "node_stack", "=", "[", "]", "result", "=", "[", "]", "node", "=", "self", "while", "True", ":", "if", "node", "is", "not", "None", ":", "node_stack", ".", "append", "(", "node", ")", "node", "=", "node", ...
Return the nodes in the binary tree using in-order_ traversal. An in-order_ traversal visits left subtree, root, then right subtree. .. _in-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.inorder [Node(4), Node(2), Node(5), Node(1), Node(3)]
[ "Return", "the", "nodes", "in", "the", "binary", "tree", "using", "in", "-", "order_", "traversal", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1444-L1492
train
206,555
joowani/binarytree
binarytree/__init__.py
Node.preorder
def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result
python
def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)] """ node_stack = [self] result = [] while len(node_stack) > 0: node = node_stack.pop() result.append(node) if node.right is not None: node_stack.append(node.right) if node.left is not None: node_stack.append(node.left) return result
[ "def", "preorder", "(", "self", ")", ":", "node_stack", "=", "[", "self", "]", "result", "=", "[", "]", "while", "len", "(", "node_stack", ")", ">", "0", ":", "node", "=", "node_stack", ".", "pop", "(", ")", "result", ".", "append", "(", "node", ...
Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.preorder [Node(1), Node(2), Node(4), Node(5), Node(3)]
[ "Return", "the", "nodes", "in", "the", "binary", "tree", "using", "pre", "-", "order_", "traversal", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1495-L1540
train
206,556
joowani/binarytree
binarytree/__init__.py
Node.postorder
def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result
python
def postorder(self): """Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)] """ node_stack = [] result = [] node = self while True: while node is not None: if node.right is not None: node_stack.append(node.right) node_stack.append(node) node = node.left node = node_stack.pop() if (node.right is not None and len(node_stack) > 0 and node_stack[-1] is node.right): node_stack.pop() node_stack.append(node) node = node.right else: result.append(node) node = None if len(node_stack) == 0: break return result
[ "def", "postorder", "(", "self", ")", ":", "node_stack", "=", "[", "]", "result", "=", "[", "]", "node", "=", "self", "while", "True", ":", "while", "node", "is", "not", "None", ":", "if", "node", ".", "right", "is", "not", "None", ":", "node_stack...
Return the nodes in the binary tree using post-order_ traversal. A post-order_ traversal visits left subtree, right subtree, then root. .. _post-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.postorder [Node(4), Node(5), Node(2), Node(3), Node(1)]
[ "Return", "the", "nodes", "in", "the", "binary", "tree", "using", "post", "-", "order_", "traversal", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1543-L1601
train
206,557
joowani/binarytree
binarytree/__init__.py
Node.levelorder
def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
python
def levelorder(self): """Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)] """ current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) if node.right is not None: next_nodes.append(node.right) current_nodes = next_nodes return result
[ "def", "levelorder", "(", "self", ")", ":", "current_nodes", "=", "[", "self", "]", "result", "=", "[", "]", "while", "len", "(", "current_nodes", ")", ">", "0", ":", "next_nodes", "=", "[", "]", "for", "node", "in", "current_nodes", ":", "result", "...
Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest:: >>> from binarytree import Node >>> >>> root = Node(1) >>> root.left = Node(2) >>> root.right = Node(3) >>> root.left.left = Node(4) >>> root.left.right = Node(5) >>> >>> print(root) <BLANKLINE> __1 / \\ 2 3 / \\ 4 5 <BLANKLINE> >>> root.levelorder [Node(1), Node(2), Node(3), Node(4), Node(5)]
[ "Return", "the", "nodes", "in", "the", "binary", "tree", "using", "level", "-", "order_", "traversal", "." ]
23cb6f1e60e66b96133259031e97ec03e932ba13
https://github.com/joowani/binarytree/blob/23cb6f1e60e66b96133259031e97ec03e932ba13/binarytree/__init__.py#L1604-L1651
train
206,558
bennylope/django-organizations
organizations/backends/__init__.py
invitation_backend
def invitation_backend(backend=None, namespace=None): # type: (Optional[Text], Optional[Text]) -> BaseBackend """ Returns a specified invitation backend Args: backend: dotted path to the invitation backend class namespace: URL namespace to use Returns: an instance of an InvitationBackend """ backend = backend or ORGS_INVITATION_BACKEND class_module, class_name = backend.rsplit(".", 1) mod = import_module(class_module) return getattr(mod, class_name)(namespace=namespace)
python
def invitation_backend(backend=None, namespace=None): # type: (Optional[Text], Optional[Text]) -> BaseBackend """ Returns a specified invitation backend Args: backend: dotted path to the invitation backend class namespace: URL namespace to use Returns: an instance of an InvitationBackend """ backend = backend or ORGS_INVITATION_BACKEND class_module, class_name = backend.rsplit(".", 1) mod = import_module(class_module) return getattr(mod, class_name)(namespace=namespace)
[ "def", "invitation_backend", "(", "backend", "=", "None", ",", "namespace", "=", "None", ")", ":", "# type: (Optional[Text], Optional[Text]) -> BaseBackend", "backend", "=", "backend", "or", "ORGS_INVITATION_BACKEND", "class_module", ",", "class_name", "=", "backend", "...
Returns a specified invitation backend Args: backend: dotted path to the invitation backend class namespace: URL namespace to use Returns: an instance of an InvitationBackend
[ "Returns", "a", "specified", "invitation", "backend" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/__init__.py#L36-L52
train
206,559
bennylope/django-organizations
organizations/backends/__init__.py
registration_backend
def registration_backend(backend=None, namespace=None): # type: (Optional[Text], Optional[Text]) -> BaseBackend """ Returns a specified registration backend Args: backend: dotted path to the registration backend class namespace: URL namespace to use Returns: an instance of an RegistrationBackend """ backend = backend or ORGS_REGISTRATION_BACKEND class_module, class_name = backend.rsplit(".", 1) mod = import_module(class_module) return getattr(mod, class_name)(namespace=namespace)
python
def registration_backend(backend=None, namespace=None): # type: (Optional[Text], Optional[Text]) -> BaseBackend """ Returns a specified registration backend Args: backend: dotted path to the registration backend class namespace: URL namespace to use Returns: an instance of an RegistrationBackend """ backend = backend or ORGS_REGISTRATION_BACKEND class_module, class_name = backend.rsplit(".", 1) mod = import_module(class_module) return getattr(mod, class_name)(namespace=namespace)
[ "def", "registration_backend", "(", "backend", "=", "None", ",", "namespace", "=", "None", ")", ":", "# type: (Optional[Text], Optional[Text]) -> BaseBackend", "backend", "=", "backend", "or", "ORGS_REGISTRATION_BACKEND", "class_module", ",", "class_name", "=", "backend",...
Returns a specified registration backend Args: backend: dotted path to the registration backend class namespace: URL namespace to use Returns: an instance of an RegistrationBackend
[ "Returns", "a", "specified", "registration", "backend" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/__init__.py#L55-L71
train
206,560
bennylope/django-organizations
organizations/backends/forms.py
org_registration_form
def org_registration_form(org_model): """ Generates a registration ModelForm for the given organization model class """ class OrganizationRegistrationForm(forms.ModelForm): """Form class for creating new organizations owned by new users.""" email = forms.EmailField() class Meta: model = org_model exclude = ("is_active", "users") def save(self, *args, **kwargs): self.instance.is_active = False super(OrganizationRegistrationForm, self).save(*args, **kwargs) return OrganizationRegistrationForm
python
def org_registration_form(org_model): """ Generates a registration ModelForm for the given organization model class """ class OrganizationRegistrationForm(forms.ModelForm): """Form class for creating new organizations owned by new users.""" email = forms.EmailField() class Meta: model = org_model exclude = ("is_active", "users") def save(self, *args, **kwargs): self.instance.is_active = False super(OrganizationRegistrationForm, self).save(*args, **kwargs) return OrganizationRegistrationForm
[ "def", "org_registration_form", "(", "org_model", ")", ":", "class", "OrganizationRegistrationForm", "(", "forms", ".", "ModelForm", ")", ":", "\"\"\"Form class for creating new organizations owned by new users.\"\"\"", "email", "=", "forms", ".", "EmailField", "(", ")", ...
Generates a registration ModelForm for the given organization model class
[ "Generates", "a", "registration", "ModelForm", "for", "the", "given", "organization", "model", "class" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/forms.py#L69-L86
train
206,561
bennylope/django-organizations
organizations/forms.py
OrganizationUserAddForm.save
def save(self, *args, **kwargs): """ The save method should create a new OrganizationUser linking the User matching the provided email address. If not matching User is found it should kick off the registration process. It needs to create a User in order to link it to the Organization. """ try: user = get_user_model().objects.get( email__iexact=self.cleaned_data["email"] ) except get_user_model().MultipleObjectsReturned: raise forms.ValidationError( _("This email address has been used multiple times.") ) except get_user_model().DoesNotExist: user = invitation_backend().invite_by_email( self.cleaned_data["email"], **{ "domain": get_current_site(self.request), "organization": self.organization, "sender": self.request.user, } ) # Send a notification email to this user to inform them that they # have been added to a new organization. invitation_backend().send_notification( user, **{ "domain": get_current_site(self.request), "organization": self.organization, "sender": self.request.user, } ) return OrganizationUser.objects.create( user=user, organization=self.organization, is_admin=self.cleaned_data["is_admin"], )
python
def save(self, *args, **kwargs): """ The save method should create a new OrganizationUser linking the User matching the provided email address. If not matching User is found it should kick off the registration process. It needs to create a User in order to link it to the Organization. """ try: user = get_user_model().objects.get( email__iexact=self.cleaned_data["email"] ) except get_user_model().MultipleObjectsReturned: raise forms.ValidationError( _("This email address has been used multiple times.") ) except get_user_model().DoesNotExist: user = invitation_backend().invite_by_email( self.cleaned_data["email"], **{ "domain": get_current_site(self.request), "organization": self.organization, "sender": self.request.user, } ) # Send a notification email to this user to inform them that they # have been added to a new organization. invitation_backend().send_notification( user, **{ "domain": get_current_site(self.request), "organization": self.organization, "sender": self.request.user, } ) return OrganizationUser.objects.create( user=user, organization=self.organization, is_admin=self.cleaned_data["is_admin"], )
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "get", "(", "email__iexact", "=", "self", ".", "cleaned_data", "[", "\"email\"", "]", ")", "e...
The save method should create a new OrganizationUser linking the User matching the provided email address. If not matching User is found it should kick off the registration process. It needs to create a User in order to link it to the Organization.
[ "The", "save", "method", "should", "create", "a", "new", "OrganizationUser", "linking", "the", "User", "matching", "the", "provided", "email", "address", ".", "If", "not", "matching", "User", "is", "found", "it", "should", "kick", "off", "the", "registration",...
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/forms.py#L98-L136
train
206,562
bennylope/django-organizations
organizations/forms.py
OrganizationAddForm.save
def save(self, **kwargs): """ Create the organization, then get the user, then make the owner. """ is_active = True try: user = get_user_model().objects.get(email=self.cleaned_data["email"]) except get_user_model().DoesNotExist: user = invitation_backend().invite_by_email( self.cleaned_data["email"], **{ "domain": get_current_site(self.request), "organization": self.cleaned_data["name"], "sender": self.request.user, "created": True, } ) is_active = False return create_organization( user, self.cleaned_data["name"], self.cleaned_data["slug"], is_active=is_active, )
python
def save(self, **kwargs): """ Create the organization, then get the user, then make the owner. """ is_active = True try: user = get_user_model().objects.get(email=self.cleaned_data["email"]) except get_user_model().DoesNotExist: user = invitation_backend().invite_by_email( self.cleaned_data["email"], **{ "domain": get_current_site(self.request), "organization": self.cleaned_data["name"], "sender": self.request.user, "created": True, } ) is_active = False return create_organization( user, self.cleaned_data["name"], self.cleaned_data["slug"], is_active=is_active, )
[ "def", "save", "(", "self", ",", "*", "*", "kwargs", ")", ":", "is_active", "=", "True", "try", ":", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "get", "(", "email", "=", "self", ".", "cleaned_data", "[", "\"email\"", "]", ")", "e...
Create the organization, then get the user, then make the owner.
[ "Create", "the", "organization", "then", "get", "the", "user", "then", "make", "the", "owner", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/forms.py#L164-L187
train
206,563
bennylope/django-organizations
organizations/backends/modeled.py
ModelInvitation.invite_by_email
def invite_by_email(self, email, user, organization, **kwargs): # type: (Text, AbstractUser, AbstractBaseOrganization) -> OrganizationInvitationBase """ Primary interface method by which one user invites another to join Args: email: request: **kwargs: Returns: an invitation instance Raises: MultipleObjectsReturned if multiple matching users are found """ try: invitee = self.user_model.objects.get(email__iexact=email) except self.user_model.DoesNotExist: invitee = None # TODO allow sending just the OrganizationUser instance user_invitation = self.invitation_model.objects.create( invitee=invitee, invitee_identifier=email.lower(), invited_by=user, organization=organization, ) self.send_invitation(user_invitation) return user_invitation
python
def invite_by_email(self, email, user, organization, **kwargs): # type: (Text, AbstractUser, AbstractBaseOrganization) -> OrganizationInvitationBase """ Primary interface method by which one user invites another to join Args: email: request: **kwargs: Returns: an invitation instance Raises: MultipleObjectsReturned if multiple matching users are found """ try: invitee = self.user_model.objects.get(email__iexact=email) except self.user_model.DoesNotExist: invitee = None # TODO allow sending just the OrganizationUser instance user_invitation = self.invitation_model.objects.create( invitee=invitee, invitee_identifier=email.lower(), invited_by=user, organization=organization, ) self.send_invitation(user_invitation) return user_invitation
[ "def", "invite_by_email", "(", "self", ",", "email", ",", "user", ",", "organization", ",", "*", "*", "kwargs", ")", ":", "# type: (Text, AbstractUser, AbstractBaseOrganization) -> OrganizationInvitationBase", "try", ":", "invitee", "=", "self", ".", "user_model", "."...
Primary interface method by which one user invites another to join Args: email: request: **kwargs: Returns: an invitation instance Raises: MultipleObjectsReturned if multiple matching users are found
[ "Primary", "interface", "method", "by", "which", "one", "user", "invites", "another", "to", "join" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/modeled.py#L141-L171
train
206,564
bennylope/django-organizations
organizations/backends/modeled.py
ModelInvitation.send_invitation
def send_invitation(self, invitation, **kwargs): # type: (OrganizationInvitationBase) -> bool """ Sends an invitation message for a specific invitation. This could be overridden to do other things, such as sending a confirmation email to the sender. Args: invitation: Returns: """ return self.email_message( invitation.invitee_identifier, self.invitation_subject, self.invitation_body, invitation.invited_by, **kwargs ).send()
python
def send_invitation(self, invitation, **kwargs): # type: (OrganizationInvitationBase) -> bool """ Sends an invitation message for a specific invitation. This could be overridden to do other things, such as sending a confirmation email to the sender. Args: invitation: Returns: """ return self.email_message( invitation.invitee_identifier, self.invitation_subject, self.invitation_body, invitation.invited_by, **kwargs ).send()
[ "def", "send_invitation", "(", "self", ",", "invitation", ",", "*", "*", "kwargs", ")", ":", "# type: (OrganizationInvitationBase) -> bool", "return", "self", ".", "email_message", "(", "invitation", ".", "invitee_identifier", ",", "self", ".", "invitation_subject", ...
Sends an invitation message for a specific invitation. This could be overridden to do other things, such as sending a confirmation email to the sender. Args: invitation: Returns:
[ "Sends", "an", "invitation", "message", "for", "a", "specific", "invitation", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/modeled.py#L173-L193
train
206,565
bennylope/django-organizations
organizations/backends/modeled.py
ModelInvitation.email_message
def email_message( self, recipient, # type: Text subject_template, # type: Text body_template, # type: Text sender=None, # type: Optional[AbstractUser] message_class=EmailMessage, **kwargs ): """ Returns an invitation email message. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent. """ from_email = "%s %s <%s>" % ( sender.first_name, sender.last_name, email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1], ) reply_to = "%s %s <%s>" % (sender.first_name, sender.last_name, sender.email) headers = {"Reply-To": reply_to} kwargs.update({"sender": sender, "recipient": recipient}) subject_template = loader.get_template(subject_template) body_template = loader.get_template(body_template) subject = subject_template.render( kwargs ).strip() # Remove stray newline characters body = body_template.render(kwargs) return message_class(subject, body, from_email, [recipient], headers=headers)
python
def email_message( self, recipient, # type: Text subject_template, # type: Text body_template, # type: Text sender=None, # type: Optional[AbstractUser] message_class=EmailMessage, **kwargs ): """ Returns an invitation email message. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent. """ from_email = "%s %s <%s>" % ( sender.first_name, sender.last_name, email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1], ) reply_to = "%s %s <%s>" % (sender.first_name, sender.last_name, sender.email) headers = {"Reply-To": reply_to} kwargs.update({"sender": sender, "recipient": recipient}) subject_template = loader.get_template(subject_template) body_template = loader.get_template(body_template) subject = subject_template.render( kwargs ).strip() # Remove stray newline characters body = body_template.render(kwargs) return message_class(subject, body, from_email, [recipient], headers=headers)
[ "def", "email_message", "(", "self", ",", "recipient", ",", "# type: Text", "subject_template", ",", "# type: Text", "body_template", ",", "# type: Text", "sender", "=", "None", ",", "# type: Optional[AbstractUser]", "message_class", "=", "EmailMessage", ",", "*", "*"...
Returns an invitation email message. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent.
[ "Returns", "an", "invitation", "email", "message", ".", "This", "can", "be", "easily", "overridden", ".", "For", "instance", "to", "send", "an", "HTML", "message", "use", "the", "EmailMultiAlternatives", "message_class", "and", "attach", "the", "additional", "co...
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/modeled.py#L195-L228
train
206,566
bennylope/django-organizations
organizations/base.py
OrgMeta.update_org
def update_org(cls, module): """ Adds the `users` field to the organization model """ try: cls.module_registry[module]["OrgModel"]._meta.get_field("users") except FieldDoesNotExist: cls.module_registry[module]["OrgModel"].add_to_class( "users", models.ManyToManyField( USER_MODEL, through=cls.module_registry[module]["OrgUserModel"].__name__, related_name="%(app_label)s_%(class)s", ), ) cls.module_registry[module]["OrgModel"].invitation_model = cls.module_registry[ module ][ "OrgInviteModel" ]
python
def update_org(cls, module): """ Adds the `users` field to the organization model """ try: cls.module_registry[module]["OrgModel"]._meta.get_field("users") except FieldDoesNotExist: cls.module_registry[module]["OrgModel"].add_to_class( "users", models.ManyToManyField( USER_MODEL, through=cls.module_registry[module]["OrgUserModel"].__name__, related_name="%(app_label)s_%(class)s", ), ) cls.module_registry[module]["OrgModel"].invitation_model = cls.module_registry[ module ][ "OrgInviteModel" ]
[ "def", "update_org", "(", "cls", ",", "module", ")", ":", "try", ":", "cls", ".", "module_registry", "[", "module", "]", "[", "\"OrgModel\"", "]", ".", "_meta", ".", "get_field", "(", "\"users\"", ")", "except", "FieldDoesNotExist", ":", "cls", ".", "mod...
Adds the `users` field to the organization model
[ "Adds", "the", "users", "field", "to", "the", "organization", "model" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/base.py#L112-L132
train
206,567
bennylope/django-organizations
organizations/base.py
OrgMeta.update_org_users
def update_org_users(cls, module): """ Adds the `user` field to the organization user model and the link to the specific organization model. """ try: cls.module_registry[module]["OrgUserModel"]._meta.get_field("user") except FieldDoesNotExist: cls.module_registry[module]["OrgUserModel"].add_to_class( "user", models.ForeignKey( USER_MODEL, related_name="%(app_label)s_%(class)s", on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgUserModel"]._meta.get_field("organization") except FieldDoesNotExist: cls.module_registry[module]["OrgUserModel"].add_to_class( "organization", models.ForeignKey( cls.module_registry[module]["OrgModel"], related_name="organization_users", on_delete=models.CASCADE, ), )
python
def update_org_users(cls, module): """ Adds the `user` field to the organization user model and the link to the specific organization model. """ try: cls.module_registry[module]["OrgUserModel"]._meta.get_field("user") except FieldDoesNotExist: cls.module_registry[module]["OrgUserModel"].add_to_class( "user", models.ForeignKey( USER_MODEL, related_name="%(app_label)s_%(class)s", on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgUserModel"]._meta.get_field("organization") except FieldDoesNotExist: cls.module_registry[module]["OrgUserModel"].add_to_class( "organization", models.ForeignKey( cls.module_registry[module]["OrgModel"], related_name="organization_users", on_delete=models.CASCADE, ), )
[ "def", "update_org_users", "(", "cls", ",", "module", ")", ":", "try", ":", "cls", ".", "module_registry", "[", "module", "]", "[", "\"OrgUserModel\"", "]", ".", "_meta", ".", "get_field", "(", "\"user\"", ")", "except", "FieldDoesNotExist", ":", "cls", "....
Adds the `user` field to the organization user model and the link to the specific organization model.
[ "Adds", "the", "user", "field", "to", "the", "organization", "user", "model", "and", "the", "link", "to", "the", "specific", "organization", "model", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/base.py#L134-L160
train
206,568
bennylope/django-organizations
organizations/base.py
OrgMeta.update_org_owner
def update_org_owner(cls, module): """ Creates the links to the organization and organization user for the owner. """ try: cls.module_registry[module]["OrgOwnerModel"]._meta.get_field( "organization_user" ) except FieldDoesNotExist: cls.module_registry[module]["OrgOwnerModel"].add_to_class( "organization_user", models.OneToOneField( cls.module_registry[module]["OrgUserModel"], on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgOwnerModel"]._meta.get_field("organization") except FieldDoesNotExist: cls.module_registry[module]["OrgOwnerModel"].add_to_class( "organization", models.OneToOneField( cls.module_registry[module]["OrgModel"], related_name="owner", on_delete=models.CASCADE, ), )
python
def update_org_owner(cls, module): """ Creates the links to the organization and organization user for the owner. """ try: cls.module_registry[module]["OrgOwnerModel"]._meta.get_field( "organization_user" ) except FieldDoesNotExist: cls.module_registry[module]["OrgOwnerModel"].add_to_class( "organization_user", models.OneToOneField( cls.module_registry[module]["OrgUserModel"], on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgOwnerModel"]._meta.get_field("organization") except FieldDoesNotExist: cls.module_registry[module]["OrgOwnerModel"].add_to_class( "organization", models.OneToOneField( cls.module_registry[module]["OrgModel"], related_name="owner", on_delete=models.CASCADE, ), )
[ "def", "update_org_owner", "(", "cls", ",", "module", ")", ":", "try", ":", "cls", ".", "module_registry", "[", "module", "]", "[", "\"OrgOwnerModel\"", "]", ".", "_meta", ".", "get_field", "(", "\"organization_user\"", ")", "except", "FieldDoesNotExist", ":",...
Creates the links to the organization and organization user for the owner.
[ "Creates", "the", "links", "to", "the", "organization", "and", "organization", "user", "for", "the", "owner", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/base.py#L162-L188
train
206,569
bennylope/django-organizations
organizations/base.py
OrgMeta.update_org_invite
def update_org_invite(cls, module): """ Adds the links to the organization and to the organization user """ try: cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invited_by") except FieldDoesNotExist: cls.module_registry[module]["OrgInviteModel"].add_to_class( "invited_by", models.ForeignKey( USER_MODEL, related_name="%(app_label)s_%(class)s_sent_invitations", on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invitee") except FieldDoesNotExist: cls.module_registry[module]["OrgInviteModel"].add_to_class( "invitee", models.ForeignKey( USER_MODEL, null=True, blank=True, related_name="%(app_label)s_%(class)s_invitations", on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgInviteModel"]._meta.get_field( "organization" ) except FieldDoesNotExist: cls.module_registry[module]["OrgInviteModel"].add_to_class( "organization", models.ForeignKey( cls.module_registry[module]["OrgModel"], related_name="organization_invites", on_delete=models.CASCADE, ), )
python
def update_org_invite(cls, module): """ Adds the links to the organization and to the organization user """ try: cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invited_by") except FieldDoesNotExist: cls.module_registry[module]["OrgInviteModel"].add_to_class( "invited_by", models.ForeignKey( USER_MODEL, related_name="%(app_label)s_%(class)s_sent_invitations", on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invitee") except FieldDoesNotExist: cls.module_registry[module]["OrgInviteModel"].add_to_class( "invitee", models.ForeignKey( USER_MODEL, null=True, blank=True, related_name="%(app_label)s_%(class)s_invitations", on_delete=models.CASCADE, ), ) try: cls.module_registry[module]["OrgInviteModel"]._meta.get_field( "organization" ) except FieldDoesNotExist: cls.module_registry[module]["OrgInviteModel"].add_to_class( "organization", models.ForeignKey( cls.module_registry[module]["OrgModel"], related_name="organization_invites", on_delete=models.CASCADE, ), )
[ "def", "update_org_invite", "(", "cls", ",", "module", ")", ":", "try", ":", "cls", ".", "module_registry", "[", "module", "]", "[", "\"OrgInviteModel\"", "]", ".", "_meta", ".", "get_field", "(", "\"invited_by\"", ")", "except", "FieldDoesNotExist", ":", "c...
Adds the links to the organization and to the organization user
[ "Adds", "the", "links", "to", "the", "organization", "and", "to", "the", "organization", "user" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/base.py#L190-L230
train
206,570
bennylope/django-organizations
organizations/base.py
AbstractBaseOrganization.user_relation_name
def user_relation_name(self): """ Returns the string name of the related name to the user. This provides a consistent interface across different organization model classes. """ return "{0}_{1}".format( self._meta.app_label.lower(), self.__class__.__name__.lower() )
python
def user_relation_name(self): """ Returns the string name of the related name to the user. This provides a consistent interface across different organization model classes. """ return "{0}_{1}".format( self._meta.app_label.lower(), self.__class__.__name__.lower() )
[ "def", "user_relation_name", "(", "self", ")", ":", "return", "\"{0}_{1}\"", ".", "format", "(", "self", ".", "_meta", ".", "app_label", ".", "lower", "(", ")", ",", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")", ")" ]
Returns the string name of the related name to the user. This provides a consistent interface across different organization model classes.
[ "Returns", "the", "string", "name", "of", "the", "related", "name", "to", "the", "user", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/base.py#L255-L264
train
206,571
bennylope/django-organizations
organizations/base.py
AbstractBaseInvitation.activate
def activate(self, user): """ Updates the `invitee` value and saves the instance Provided as a way of extending the behavior. Args: user: the newly created user Returns: the linking organization user """ org_user = self.organization.add_user(user, **self.activation_kwargs()) self.invitee = user self.save() return org_user
python
def activate(self, user): """ Updates the `invitee` value and saves the instance Provided as a way of extending the behavior. Args: user: the newly created user Returns: the linking organization user """ org_user = self.organization.add_user(user, **self.activation_kwargs()) self.invitee = user self.save() return org_user
[ "def", "activate", "(", "self", ",", "user", ")", ":", "org_user", "=", "self", ".", "organization", ".", "add_user", "(", "user", ",", "*", "*", "self", ".", "activation_kwargs", "(", ")", ")", "self", ".", "invitee", "=", "user", "self", ".", "save...
Updates the `invitee` value and saves the instance Provided as a way of extending the behavior. Args: user: the newly created user Returns: the linking organization user
[ "Updates", "the", "invitee", "value", "and", "saves", "the", "instance" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/base.py#L380-L396
train
206,572
bennylope/django-organizations
organizations/views/mixins.py
OrganizationUserMixin.get_object
def get_object(self): """ Returns the OrganizationUser object based on the primary keys for both the organization and the organization user. """ if hasattr(self, "organization_user"): return self.organization_user organization_pk = self.kwargs.get("organization_pk", None) user_pk = self.kwargs.get("user_pk", None) self.organization_user = get_object_or_404( self.get_user_model().objects.select_related(), user__pk=user_pk, organization__pk=organization_pk, ) return self.organization_user
python
def get_object(self): """ Returns the OrganizationUser object based on the primary keys for both the organization and the organization user. """ if hasattr(self, "organization_user"): return self.organization_user organization_pk = self.kwargs.get("organization_pk", None) user_pk = self.kwargs.get("user_pk", None) self.organization_user = get_object_or_404( self.get_user_model().objects.select_related(), user__pk=user_pk, organization__pk=organization_pk, ) return self.organization_user
[ "def", "get_object", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"organization_user\"", ")", ":", "return", "self", ".", "organization_user", "organization_pk", "=", "self", ".", "kwargs", ".", "get", "(", "\"organization_pk\"", ",", "None", ...
Returns the OrganizationUser object based on the primary keys for both the organization and the organization user.
[ "Returns", "the", "OrganizationUser", "object", "based", "on", "the", "primary", "keys", "for", "both", "the", "organization", "and", "the", "organization", "user", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/views/mixins.py#L78-L91
train
206,573
bennylope/django-organizations
organizations/backends/tokens.py
RegistrationTokenGenerator.check_token
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS: return False return True
python
def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ # Parse the token try: ts_b36, hash = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): return False # Check the timestamp is within limit if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS: return False return True
[ "def", "check_token", "(", "self", ",", "user", ",", "token", ")", ":", "# Parse the token", "try", ":", "ts_b36", ",", "hash", "=", "token", ".", "split", "(", "\"-\"", ")", "except", "ValueError", ":", "return", "False", "try", ":", "ts", "=", "base3...
Check that a password reset token is correct for a given user.
[ "Check", "that", "a", "password", "reset", "token", "is", "correct", "for", "a", "given", "user", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/tokens.py#L48-L71
train
206,574
bennylope/django-organizations
organizations/utils.py
create_organization
def create_organization( user, name, slug=None, is_active=None, org_defaults=None, org_user_defaults=None, **kwargs ): """ Returns a new organization, also creating an initial organization user who is the owner. The specific models can be specified if a custom organization app is used. The simplest way would be to use a partial. >>> from organizations.utils import create_organization >>> from myapp.models import Account >>> from functools import partial >>> create_account = partial(create_organization, model=Account) """ org_model = kwargs.pop("model", None) or kwargs.pop( "org_model", None ) or default_org_model() kwargs.pop("org_user_model", None) # Discard deprecated argument org_owner_model = org_model.owner.related.related_model try: # Django 1.9 org_user_model = org_model.organization_users.rel.related_model except AttributeError: # Django 1.8 org_user_model = org_model.organization_users.related.related_model if org_defaults is None: org_defaults = {} if org_user_defaults is None: if "is_admin" in model_field_names(org_user_model): org_user_defaults = {"is_admin": True} else: org_user_defaults = {} if slug is not None: org_defaults.update({"slug": slug}) if is_active is not None: org_defaults.update({"is_active": is_active}) org_defaults.update({"name": name}) organization = org_model.objects.create(**org_defaults) org_user_defaults.update({"organization": organization, "user": user}) new_user = org_user_model.objects.create(**org_user_defaults) org_owner_model.objects.create( organization=organization, organization_user=new_user ) return organization
python
def create_organization( user, name, slug=None, is_active=None, org_defaults=None, org_user_defaults=None, **kwargs ): """ Returns a new organization, also creating an initial organization user who is the owner. The specific models can be specified if a custom organization app is used. The simplest way would be to use a partial. >>> from organizations.utils import create_organization >>> from myapp.models import Account >>> from functools import partial >>> create_account = partial(create_organization, model=Account) """ org_model = kwargs.pop("model", None) or kwargs.pop( "org_model", None ) or default_org_model() kwargs.pop("org_user_model", None) # Discard deprecated argument org_owner_model = org_model.owner.related.related_model try: # Django 1.9 org_user_model = org_model.organization_users.rel.related_model except AttributeError: # Django 1.8 org_user_model = org_model.organization_users.related.related_model if org_defaults is None: org_defaults = {} if org_user_defaults is None: if "is_admin" in model_field_names(org_user_model): org_user_defaults = {"is_admin": True} else: org_user_defaults = {} if slug is not None: org_defaults.update({"slug": slug}) if is_active is not None: org_defaults.update({"is_active": is_active}) org_defaults.update({"name": name}) organization = org_model.objects.create(**org_defaults) org_user_defaults.update({"organization": organization, "user": user}) new_user = org_user_model.objects.create(**org_user_defaults) org_owner_model.objects.create( organization=organization, organization_user=new_user ) return organization
[ "def", "create_organization", "(", "user", ",", "name", ",", "slug", "=", "None", ",", "is_active", "=", "None", ",", "org_defaults", "=", "None", ",", "org_user_defaults", "=", "None", ",", "*", "*", "kwargs", ")", ":", "org_model", "=", "kwargs", ".", ...
Returns a new organization, also creating an initial organization user who is the owner. The specific models can be specified if a custom organization app is used. The simplest way would be to use a partial. >>> from organizations.utils import create_organization >>> from myapp.models import Account >>> from functools import partial >>> create_account = partial(create_organization, model=Account)
[ "Returns", "a", "new", "organization", "also", "creating", "an", "initial", "organization", "user", "who", "is", "the", "owner", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/utils.py#L55-L112
train
206,575
bennylope/django-organizations
organizations/utils.py
model_field_attr
def model_field_attr(model, model_field, attr): """ Returns the specified attribute for the specified field on the model class. """ fields = dict([(field.name, field) for field in model._meta.fields]) return getattr(fields[model_field], attr)
python
def model_field_attr(model, model_field, attr): """ Returns the specified attribute for the specified field on the model class. """ fields = dict([(field.name, field) for field in model._meta.fields]) return getattr(fields[model_field], attr)
[ "def", "model_field_attr", "(", "model", ",", "model_field", ",", "attr", ")", ":", "fields", "=", "dict", "(", "[", "(", "field", ".", "name", ",", "field", ")", "for", "field", "in", "model", ".", "_meta", ".", "fields", "]", ")", "return", "getatt...
Returns the specified attribute for the specified field on the model class.
[ "Returns", "the", "specified", "attribute", "for", "the", "specified", "field", "on", "the", "model", "class", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/utils.py#L115-L120
train
206,576
bennylope/django-organizations
organizations/backends/defaults.py
BaseBackend.get_form
def get_form(self, **kwargs): """Returns the form for registering or inviting a user""" if not hasattr(self, "form_class"): raise AttributeError(_("You must define a form_class")) return self.form_class(**kwargs)
python
def get_form(self, **kwargs): """Returns the form for registering or inviting a user""" if not hasattr(self, "form_class"): raise AttributeError(_("You must define a form_class")) return self.form_class(**kwargs)
[ "def", "get_form", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"form_class\"", ")", ":", "raise", "AttributeError", "(", "_", "(", "\"You must define a form_class\"", ")", ")", "return", "self", ".", "form_cl...
Returns the form for registering or inviting a user
[ "Returns", "the", "form", "for", "registering", "or", "inviting", "a", "user" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L85-L89
train
206,577
bennylope/django-organizations
organizations/backends/defaults.py
BaseBackend.activate_organizations
def activate_organizations(self, user): """ Activates the related organizations for the user. It only activates the related organizations by model type - that is, if there are multiple types of organizations then only organizations in the provided model class are activated. """ try: relation_name = self.org_model().user_relation_name except TypeError: # No org_model specified, raises a TypeError because NoneType is # not callable. This the most sensible default: relation_name = "organizations_organization" organization_set = getattr(user, relation_name) for org in organization_set.filter(is_active=False): org.is_active = True org.save()
python
def activate_organizations(self, user): """ Activates the related organizations for the user. It only activates the related organizations by model type - that is, if there are multiple types of organizations then only organizations in the provided model class are activated. """ try: relation_name = self.org_model().user_relation_name except TypeError: # No org_model specified, raises a TypeError because NoneType is # not callable. This the most sensible default: relation_name = "organizations_organization" organization_set = getattr(user, relation_name) for org in organization_set.filter(is_active=False): org.is_active = True org.save()
[ "def", "activate_organizations", "(", "self", ",", "user", ")", ":", "try", ":", "relation_name", "=", "self", ".", "org_model", "(", ")", ".", "user_relation_name", "except", "TypeError", ":", "# No org_model specified, raises a TypeError because NoneType is", "# not c...
Activates the related organizations for the user. It only activates the related organizations by model type - that is, if there are multiple types of organizations then only organizations in the provided model class are activated.
[ "Activates", "the", "related", "organizations", "for", "the", "user", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L105-L122
train
206,578
bennylope/django-organizations
organizations/backends/defaults.py
BaseBackend.activate_view
def activate_view(self, request, user_id, token): """ View function that activates the given User by setting `is_active` to true if the provided information is verified. """ try: user = self.user_model.objects.get(id=user_id, is_active=False) except self.user_model.DoesNotExist: raise Http404(_("Your URL may have expired.")) if not RegistrationTokenGenerator().check_token(user, token): raise Http404(_("Your URL may have expired.")) form = self.get_form( data=request.POST or None, files=request.FILES or None, instance=user ) if form.is_valid(): form.instance.is_active = True user = form.save() user.set_password(form.cleaned_data["password"]) user.save() self.activate_organizations(user) user = authenticate( username=form.cleaned_data["username"], password=form.cleaned_data["password"], ) login(request, user) return redirect(self.get_success_url()) return render(request, self.registration_form_template, {"form": form})
python
def activate_view(self, request, user_id, token): """ View function that activates the given User by setting `is_active` to true if the provided information is verified. """ try: user = self.user_model.objects.get(id=user_id, is_active=False) except self.user_model.DoesNotExist: raise Http404(_("Your URL may have expired.")) if not RegistrationTokenGenerator().check_token(user, token): raise Http404(_("Your URL may have expired.")) form = self.get_form( data=request.POST or None, files=request.FILES or None, instance=user ) if form.is_valid(): form.instance.is_active = True user = form.save() user.set_password(form.cleaned_data["password"]) user.save() self.activate_organizations(user) user = authenticate( username=form.cleaned_data["username"], password=form.cleaned_data["password"], ) login(request, user) return redirect(self.get_success_url()) return render(request, self.registration_form_template, {"form": form})
[ "def", "activate_view", "(", "self", ",", "request", ",", "user_id", ",", "token", ")", ":", "try", ":", "user", "=", "self", ".", "user_model", ".", "objects", ".", "get", "(", "id", "=", "user_id", ",", "is_active", "=", "False", ")", "except", "se...
View function that activates the given User by setting `is_active` to true if the provided information is verified.
[ "View", "function", "that", "activates", "the", "given", "User", "by", "setting", "is_active", "to", "true", "if", "the", "provided", "information", "is", "verified", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L124-L151
train
206,579
bennylope/django-organizations
organizations/backends/defaults.py
BaseBackend.send_reminder
def send_reminder(self, user, sender=None, **kwargs): """Sends a reminder email to the specified user""" if user.is_active: return False token = RegistrationTokenGenerator().make_token(user) kwargs.update({"token": token}) self.email_message( user, self.reminder_subject, self.reminder_body, sender, **kwargs ).send()
python
def send_reminder(self, user, sender=None, **kwargs): """Sends a reminder email to the specified user""" if user.is_active: return False token = RegistrationTokenGenerator().make_token(user) kwargs.update({"token": token}) self.email_message( user, self.reminder_subject, self.reminder_body, sender, **kwargs ).send()
[ "def", "send_reminder", "(", "self", ",", "user", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_active", ":", "return", "False", "token", "=", "RegistrationTokenGenerator", "(", ")", ".", "make_token", "(", "user",...
Sends a reminder email to the specified user
[ "Sends", "a", "reminder", "email", "to", "the", "specified", "user" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L153-L161
train
206,580
bennylope/django-organizations
organizations/backends/defaults.py
BaseBackend.email_message
def email_message( self, user, subject_template, body_template, sender=None, message_class=EmailMessage, **kwargs ): """ Returns an email message for a new user. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent. """ if sender: try: display_name = sender.get_full_name() except (AttributeError, TypeError): display_name = sender.get_username() from_email = "%s <%s>" % ( display_name, email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1] ) reply_to = "%s <%s>" % (display_name, sender.email) else: from_email = settings.DEFAULT_FROM_EMAIL reply_to = from_email headers = {"Reply-To": reply_to} kwargs.update({"sender": sender, "user": user}) subject_template = loader.get_template(subject_template) body_template = loader.get_template(body_template) subject = subject_template.render( kwargs ).strip() # Remove stray newline characters body = body_template.render(kwargs) return message_class(subject, body, from_email, [user.email], headers=headers)
python
def email_message( self, user, subject_template, body_template, sender=None, message_class=EmailMessage, **kwargs ): """ Returns an email message for a new user. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent. """ if sender: try: display_name = sender.get_full_name() except (AttributeError, TypeError): display_name = sender.get_username() from_email = "%s <%s>" % ( display_name, email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1] ) reply_to = "%s <%s>" % (display_name, sender.email) else: from_email = settings.DEFAULT_FROM_EMAIL reply_to = from_email headers = {"Reply-To": reply_to} kwargs.update({"sender": sender, "user": user}) subject_template = loader.get_template(subject_template) body_template = loader.get_template(body_template) subject = subject_template.render( kwargs ).strip() # Remove stray newline characters body = body_template.render(kwargs) return message_class(subject, body, from_email, [user.email], headers=headers)
[ "def", "email_message", "(", "self", ",", "user", ",", "subject_template", ",", "body_template", ",", "sender", "=", "None", ",", "message_class", "=", "EmailMessage", ",", "*", "*", "kwargs", ")", ":", "if", "sender", ":", "try", ":", "display_name", "=",...
Returns an email message for a new user. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent.
[ "Returns", "an", "email", "message", "for", "a", "new", "user", ".", "This", "can", "be", "easily", "overridden", ".", "For", "instance", "to", "send", "an", "HTML", "message", "use", "the", "EmailMultiAlternatives", "message_class", "and", "attach", "the", ...
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L163-L199
train
206,581
bennylope/django-organizations
organizations/backends/defaults.py
RegistrationBackend.register_by_email
def register_by_email(self, email, sender=None, request=None, **kwargs): """ Returns a User object filled with dummy data and not active, and sends an invitation email. """ try: user = self.user_model.objects.get(email=email) except self.user_model.DoesNotExist: user = self.user_model.objects.create( username=self.get_username(), email=email, password=self.user_model.objects.make_random_password(), ) user.is_active = False user.save() self.send_activation(user, sender, **kwargs) return user
python
def register_by_email(self, email, sender=None, request=None, **kwargs): """ Returns a User object filled with dummy data and not active, and sends an invitation email. """ try: user = self.user_model.objects.get(email=email) except self.user_model.DoesNotExist: user = self.user_model.objects.create( username=self.get_username(), email=email, password=self.user_model.objects.make_random_password(), ) user.is_active = False user.save() self.send_activation(user, sender, **kwargs) return user
[ "def", "register_by_email", "(", "self", ",", "email", ",", "sender", "=", "None", ",", "request", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "self", ".", "user_model", ".", "objects", ".", "get", "(", "email", "=", "e...
Returns a User object filled with dummy data and not active, and sends an invitation email.
[ "Returns", "a", "User", "object", "filled", "with", "dummy", "data", "and", "not", "active", "and", "sends", "an", "invitation", "email", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L233-L249
train
206,582
bennylope/django-organizations
organizations/backends/defaults.py
RegistrationBackend.send_activation
def send_activation(self, user, sender=None, **kwargs): """ Invites a user to join the site """ if user.is_active: return False token = self.get_token(user) kwargs.update({"token": token}) self.email_message( user, self.activation_subject, self.activation_body, sender, **kwargs ).send()
python
def send_activation(self, user, sender=None, **kwargs): """ Invites a user to join the site """ if user.is_active: return False token = self.get_token(user) kwargs.update({"token": token}) self.email_message( user, self.activation_subject, self.activation_body, sender, **kwargs ).send()
[ "def", "send_activation", "(", "self", ",", "user", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_active", ":", "return", "False", "token", "=", "self", ".", "get_token", "(", "user", ")", "kwargs", ".", "updat...
Invites a user to join the site
[ "Invites", "a", "user", "to", "join", "the", "site" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L251-L261
train
206,583
bennylope/django-organizations
organizations/backends/defaults.py
RegistrationBackend.create_view
def create_view(self, request): """ Initiates the organization and user account creation process """ try: if request.user.is_authenticated(): return redirect("organization_add") except TypeError: if request.user.is_authenticated: return redirect("organization_add") form = org_registration_form(self.org_model)(request.POST or None) if form.is_valid(): try: user = self.user_model.objects.get(email=form.cleaned_data["email"]) except self.user_model.DoesNotExist: user = self.user_model.objects.create( username=self.get_username(), email=form.cleaned_data["email"], password=self.user_model.objects.make_random_password(), ) user.is_active = False user.save() else: return redirect("organization_add") organization = create_organization( user, form.cleaned_data["name"], form.cleaned_data["slug"], is_active=False, ) return render( request, self.activation_success_template, {"user": user, "organization": organization}, ) return render(request, self.registration_form_template, {"form": form})
python
def create_view(self, request): """ Initiates the organization and user account creation process """ try: if request.user.is_authenticated(): return redirect("organization_add") except TypeError: if request.user.is_authenticated: return redirect("organization_add") form = org_registration_form(self.org_model)(request.POST or None) if form.is_valid(): try: user = self.user_model.objects.get(email=form.cleaned_data["email"]) except self.user_model.DoesNotExist: user = self.user_model.objects.create( username=self.get_username(), email=form.cleaned_data["email"], password=self.user_model.objects.make_random_password(), ) user.is_active = False user.save() else: return redirect("organization_add") organization = create_organization( user, form.cleaned_data["name"], form.cleaned_data["slug"], is_active=False, ) return render( request, self.activation_success_template, {"user": user, "organization": organization}, ) return render(request, self.registration_form_template, {"form": form})
[ "def", "create_view", "(", "self", ",", "request", ")", ":", "try", ":", "if", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "redirect", "(", "\"organization_add\"", ")", "except", "TypeError", ":", "if", "request", ".", "user",...
Initiates the organization and user account creation process
[ "Initiates", "the", "organization", "and", "user", "account", "creation", "process" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L263-L298
train
206,584
bennylope/django-organizations
organizations/backends/defaults.py
InvitationBackend.invite_by_email
def invite_by_email(self, email, sender=None, request=None, **kwargs): """Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration. If your project uses email in a different way then you should make to extend this method as it only checks the `email` attribute for Users. """ try: user = self.user_model.objects.get(email=email) except self.user_model.DoesNotExist: # TODO break out user creation process if "username" in inspect.getargspec( self.user_model.objects.create_user ).args: user = self.user_model.objects.create( username=self.get_username(), email=email, password=self.user_model.objects.make_random_password(), ) else: user = self.user_model.objects.create( email=email, password=self.user_model.objects.make_random_password() ) user.is_active = False user.save() self.send_invitation(user, sender, **kwargs) return user
python
def invite_by_email(self, email, sender=None, request=None, **kwargs): """Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration. If your project uses email in a different way then you should make to extend this method as it only checks the `email` attribute for Users. """ try: user = self.user_model.objects.get(email=email) except self.user_model.DoesNotExist: # TODO break out user creation process if "username" in inspect.getargspec( self.user_model.objects.create_user ).args: user = self.user_model.objects.create( username=self.get_username(), email=email, password=self.user_model.objects.make_random_password(), ) else: user = self.user_model.objects.create( email=email, password=self.user_model.objects.make_random_password() ) user.is_active = False user.save() self.send_invitation(user, sender, **kwargs) return user
[ "def", "invite_by_email", "(", "self", ",", "email", ",", "sender", "=", "None", ",", "request", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "self", ".", "user_model", ".", "objects", ".", "get", "(", "email", "=", "ema...
Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration. If your project uses email in a different way then you should make to extend this method as it only checks the `email` attribute for Users.
[ "Creates", "an", "inactive", "user", "with", "the", "information", "we", "know", "and", "then", "sends", "an", "invitation", "email", "for", "that", "user", "to", "complete", "registration", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L331-L357
train
206,585
bennylope/django-organizations
organizations/backends/defaults.py
InvitationBackend.send_invitation
def send_invitation(self, user, sender=None, **kwargs): """An intermediary function for sending an invitation email that selects the templates, generating the token, and ensuring that the user has not already joined the site. """ if user.is_active: return False token = self.get_token(user) kwargs.update({"token": token}) self.email_message( user, self.invitation_subject, self.invitation_body, sender, **kwargs ).send() return True
python
def send_invitation(self, user, sender=None, **kwargs): """An intermediary function for sending an invitation email that selects the templates, generating the token, and ensuring that the user has not already joined the site. """ if user.is_active: return False token = self.get_token(user) kwargs.update({"token": token}) self.email_message( user, self.invitation_subject, self.invitation_body, sender, **kwargs ).send() return True
[ "def", "send_invitation", "(", "self", ",", "user", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_active", ":", "return", "False", "token", "=", "self", ".", "get_token", "(", "user", ")", "kwargs", ".", "updat...
An intermediary function for sending an invitation email that selects the templates, generating the token, and ensuring that the user has not already joined the site.
[ "An", "intermediary", "function", "for", "sending", "an", "invitation", "email", "that", "selects", "the", "templates", "generating", "the", "token", "and", "ensuring", "that", "the", "user", "has", "not", "already", "joined", "the", "site", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L359-L371
train
206,586
bennylope/django-organizations
organizations/backends/defaults.py
InvitationBackend.send_notification
def send_notification(self, user, sender=None, **kwargs): """ An intermediary function for sending an notification email informing a pre-existing, active user that they have been added to a new organization. """ if not user.is_active: return False self.email_message( user, self.notification_subject, self.notification_body, sender, **kwargs ).send() return True
python
def send_notification(self, user, sender=None, **kwargs): """ An intermediary function for sending an notification email informing a pre-existing, active user that they have been added to a new organization. """ if not user.is_active: return False self.email_message( user, self.notification_subject, self.notification_body, sender, **kwargs ).send() return True
[ "def", "send_notification", "(", "self", ",", "user", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "user", ".", "is_active", ":", "return", "False", "self", ".", "email_message", "(", "user", ",", "self", ".", "notificati...
An intermediary function for sending an notification email informing a pre-existing, active user that they have been added to a new organization.
[ "An", "intermediary", "function", "for", "sending", "an", "notification", "email", "informing", "a", "pre", "-", "existing", "active", "user", "that", "they", "have", "been", "added", "to", "a", "new", "organization", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/backends/defaults.py#L373-L384
train
206,587
bennylope/django-organizations
organizations/abstract.py
AbstractOrganization.add_user
def add_user(self, user, is_admin=False): """ Adds a new user and if the first user makes the user an admin and the owner. """ users_count = self.users.all().count() if users_count == 0: is_admin = True # TODO get specific org user? org_user = self._org_user_model.objects.create( user=user, organization=self, is_admin=is_admin ) if users_count == 0: # TODO get specific org user? self._org_owner_model.objects.create( organization=self, organization_user=org_user ) # User added signal user_added.send(sender=self, user=user) return org_user
python
def add_user(self, user, is_admin=False): """ Adds a new user and if the first user makes the user an admin and the owner. """ users_count = self.users.all().count() if users_count == 0: is_admin = True # TODO get specific org user? org_user = self._org_user_model.objects.create( user=user, organization=self, is_admin=is_admin ) if users_count == 0: # TODO get specific org user? self._org_owner_model.objects.create( organization=self, organization_user=org_user ) # User added signal user_added.send(sender=self, user=user) return org_user
[ "def", "add_user", "(", "self", ",", "user", ",", "is_admin", "=", "False", ")", ":", "users_count", "=", "self", ".", "users", ".", "all", "(", ")", ".", "count", "(", ")", "if", "users_count", "==", "0", ":", "is_admin", "=", "True", "# TODO get sp...
Adds a new user and if the first user makes the user an admin and the owner.
[ "Adds", "a", "new", "user", "and", "if", "the", "first", "user", "makes", "the", "user", "an", "admin", "and", "the", "owner", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L117-L137
train
206,588
bennylope/django-organizations
organizations/abstract.py
AbstractOrganization.remove_user
def remove_user(self, user): """ Deletes a user from an organization. """ org_user = self._org_user_model.objects.get(user=user, organization=self) org_user.delete() # User removed signal user_removed.send(sender=self, user=user)
python
def remove_user(self, user): """ Deletes a user from an organization. """ org_user = self._org_user_model.objects.get(user=user, organization=self) org_user.delete() # User removed signal user_removed.send(sender=self, user=user)
[ "def", "remove_user", "(", "self", ",", "user", ")", ":", "org_user", "=", "self", ".", "_org_user_model", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "organization", "=", "self", ")", "org_user", ".", "delete", "(", ")", "# User removed s...
Deletes a user from an organization.
[ "Deletes", "a", "user", "from", "an", "organization", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L139-L147
train
206,589
bennylope/django-organizations
organizations/abstract.py
AbstractOrganization.get_or_add_user
def get_or_add_user(self, user, **kwargs): """ Adds a new user to the organization, and if it's the first user makes the user an admin and the owner. Uses the `get_or_create` method to create or return the existing user. `user` should be a user instance, e.g. `auth.User`. Returns the same tuple as the `get_or_create` method, the `OrganizationUser` and a boolean value indicating whether the OrganizationUser was created or not. """ is_admin = kwargs.pop("is_admin", False) users_count = self.users.all().count() if users_count == 0: is_admin = True org_user, created = self._org_user_model.objects.get_or_create( organization=self, user=user, defaults={"is_admin": is_admin} ) if users_count == 0: self._org_owner_model.objects.create( organization=self, organization_user=org_user ) if created: # User added signal user_added.send(sender=self, user=user) return org_user, created
python
def get_or_add_user(self, user, **kwargs): """ Adds a new user to the organization, and if it's the first user makes the user an admin and the owner. Uses the `get_or_create` method to create or return the existing user. `user` should be a user instance, e.g. `auth.User`. Returns the same tuple as the `get_or_create` method, the `OrganizationUser` and a boolean value indicating whether the OrganizationUser was created or not. """ is_admin = kwargs.pop("is_admin", False) users_count = self.users.all().count() if users_count == 0: is_admin = True org_user, created = self._org_user_model.objects.get_or_create( organization=self, user=user, defaults={"is_admin": is_admin} ) if users_count == 0: self._org_owner_model.objects.create( organization=self, organization_user=org_user ) if created: # User added signal user_added.send(sender=self, user=user) return org_user, created
[ "def", "get_or_add_user", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "is_admin", "=", "kwargs", ".", "pop", "(", "\"is_admin\"", ",", "False", ")", "users_count", "=", "self", ".", "users", ".", "all", "(", ")", ".", "count", "(", ...
Adds a new user to the organization, and if it's the first user makes the user an admin and the owner. Uses the `get_or_create` method to create or return the existing user. `user` should be a user instance, e.g. `auth.User`. Returns the same tuple as the `get_or_create` method, the `OrganizationUser` and a boolean value indicating whether the OrganizationUser was created or not.
[ "Adds", "a", "new", "user", "to", "the", "organization", "and", "if", "it", "s", "the", "first", "user", "makes", "the", "user", "an", "admin", "and", "the", "owner", ".", "Uses", "the", "get_or_create", "method", "to", "create", "or", "return", "the", ...
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L149-L176
train
206,590
bennylope/django-organizations
organizations/abstract.py
AbstractOrganization.change_owner
def change_owner(self, new_owner): """ Changes ownership of an organization. """ old_owner = self.owner.organization_user self.owner.organization_user = new_owner self.owner.save() # Owner changed signal owner_changed.send(sender=self, old=old_owner, new=new_owner)
python
def change_owner(self, new_owner): """ Changes ownership of an organization. """ old_owner = self.owner.organization_user self.owner.organization_user = new_owner self.owner.save() # Owner changed signal owner_changed.send(sender=self, old=old_owner, new=new_owner)
[ "def", "change_owner", "(", "self", ",", "new_owner", ")", ":", "old_owner", "=", "self", ".", "owner", ".", "organization_user", "self", ".", "owner", ".", "organization_user", "=", "new_owner", "self", ".", "owner", ".", "save", "(", ")", "# Owner changed ...
Changes ownership of an organization.
[ "Changes", "ownership", "of", "an", "organization", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L178-L187
train
206,591
bennylope/django-organizations
organizations/abstract.py
AbstractOrganization.is_admin
def is_admin(self, user): """ Returns True is user is an admin in the organization, otherwise false """ return True if self.organization_users.filter( user=user, is_admin=True ) else False
python
def is_admin(self, user): """ Returns True is user is an admin in the organization, otherwise false """ return True if self.organization_users.filter( user=user, is_admin=True ) else False
[ "def", "is_admin", "(", "self", ",", "user", ")", ":", "return", "True", "if", "self", ".", "organization_users", ".", "filter", "(", "user", "=", "user", ",", "is_admin", "=", "True", ")", "else", "False" ]
Returns True is user is an admin in the organization, otherwise false
[ "Returns", "True", "is", "user", "is", "an", "admin", "in", "the", "organization", "otherwise", "false" ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L189-L195
train
206,592
bennylope/django-organizations
organizations/abstract.py
AbstractOrganizationUser.delete
def delete(self, using=None): """ If the organization user is also the owner, this should not be deleted unless it's part of a cascade from the Organization. If there is no owner then the deletion should proceed. """ from organizations.exceptions import OwnershipRequired try: if self.organization.owner.organization_user.pk == self.pk: raise OwnershipRequired( _( "Cannot delete organization owner " "before organization or transferring ownership." ) ) # TODO This line presumes that OrgOwner model can't be modified except self._org_owner_model.DoesNotExist: pass super(AbstractBaseOrganizationUser, self).delete(using=using)
python
def delete(self, using=None): """ If the organization user is also the owner, this should not be deleted unless it's part of a cascade from the Organization. If there is no owner then the deletion should proceed. """ from organizations.exceptions import OwnershipRequired try: if self.organization.owner.organization_user.pk == self.pk: raise OwnershipRequired( _( "Cannot delete organization owner " "before organization or transferring ownership." ) ) # TODO This line presumes that OrgOwner model can't be modified except self._org_owner_model.DoesNotExist: pass super(AbstractBaseOrganizationUser, self).delete(using=using)
[ "def", "delete", "(", "self", ",", "using", "=", "None", ")", ":", "from", "organizations", ".", "exceptions", "import", "OwnershipRequired", "try", ":", "if", "self", ".", "organization", ".", "owner", ".", "organization_user", ".", "pk", "==", "self", "....
If the organization user is also the owner, this should not be deleted unless it's part of a cascade from the Organization. If there is no owner then the deletion should proceed.
[ "If", "the", "organization", "user", "is", "also", "the", "owner", "this", "should", "not", "be", "deleted", "unless", "it", "s", "part", "of", "a", "cascade", "from", "the", "Organization", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L223-L243
train
206,593
bennylope/django-organizations
organizations/abstract.py
AbstractOrganizationOwner.save
def save(self, *args, **kwargs): """ Extends the default save method by verifying that the chosen organization user is associated with the organization. Method validates against the primary key of the organization because when validating an inherited model it may be checking an instance of `Organization` against an instance of `CustomOrganization`. Mutli-table inheritence means the database keys will be identical though. """ from organizations.exceptions import OrganizationMismatch if self.organization_user.organization.pk != self.organization.pk: raise OrganizationMismatch else: super(AbstractBaseOrganizationOwner, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ Extends the default save method by verifying that the chosen organization user is associated with the organization. Method validates against the primary key of the organization because when validating an inherited model it may be checking an instance of `Organization` against an instance of `CustomOrganization`. Mutli-table inheritence means the database keys will be identical though. """ from organizations.exceptions import OrganizationMismatch if self.organization_user.organization.pk != self.organization.pk: raise OrganizationMismatch else: super(AbstractBaseOrganizationOwner, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "organizations", ".", "exceptions", "import", "OrganizationMismatch", "if", "self", ".", "organization_user", ".", "organization", ".", "pk", "!=", "self", ".", "organ...
Extends the default save method by verifying that the chosen organization user is associated with the organization. Method validates against the primary key of the organization because when validating an inherited model it may be checking an instance of `Organization` against an instance of `CustomOrganization`. Mutli-table inheritence means the database keys will be identical though.
[ "Extends", "the", "default", "save", "method", "by", "verifying", "that", "the", "chosen", "organization", "user", "is", "associated", "with", "the", "organization", "." ]
85f753a8f7a8f0f31636c9209fb69e7030a5c79a
https://github.com/bennylope/django-organizations/blob/85f753a8f7a8f0f31636c9209fb69e7030a5c79a/organizations/abstract.py#L264-L280
train
206,594
PX4/pyulog
pyulog/ulog2kml.py
_kml_default_colors
def _kml_default_colors(x): """ flight mode to color conversion """ x = max([x, 0]) colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue, simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange, simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue, simplekml.Color.lawngreen, simplekml.Color.indianred, simplekml.Color.hotpink] return colors_arr[x]
python
def _kml_default_colors(x): """ flight mode to color conversion """ x = max([x, 0]) colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue, simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange, simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue, simplekml.Color.lawngreen, simplekml.Color.indianred, simplekml.Color.hotpink] return colors_arr[x]
[ "def", "_kml_default_colors", "(", "x", ")", ":", "x", "=", "max", "(", "[", "x", ",", "0", "]", ")", "colors_arr", "=", "[", "simplekml", ".", "Color", ".", "red", ",", "simplekml", ".", "Color", ".", "green", ",", "simplekml", ".", "Color", ".", ...
flight mode to color conversion
[ "flight", "mode", "to", "color", "conversion" ]
3bc4f9338d30e2e0a0dfbed58f54d200967e5056
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L44-L51
train
206,595
PX4/pyulog
pyulog/ulog2kml.py
_kml_add_camera_triggers
def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset): """ Add camera trigger points to the map """ data = ulog.data_list topic_instance = 0 cur_dataset = [elem for elem in data if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) > 0: cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] sequence = cur_dataset.data['seq'] for i in range(len(pos_lon)): pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i])) pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)]
python
def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset): """ Add camera trigger points to the map """ data = ulog.data_list topic_instance = 0 cur_dataset = [elem for elem in data if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance] if len(cur_dataset) > 0: cur_dataset = cur_dataset[0] pos_lon = cur_dataset.data['lon'] pos_lat = cur_dataset.data['lat'] pos_alt = cur_dataset.data['alt'] sequence = cur_dataset.data['seq'] for i in range(len(pos_lon)): pnt = kml.newpoint(name='Camera Trigger '+str(sequence[i])) pnt.coords = [(pos_lon[i], pos_lat[i], pos_alt[i] + altitude_offset)]
[ "def", "_kml_add_camera_triggers", "(", "kml", ",", "ulog", ",", "camera_trigger_topic_name", ",", "altitude_offset", ")", ":", "data", "=", "ulog", ".", "data_list", "topic_instance", "=", "0", "cur_dataset", "=", "[", "elem", "for", "elem", "in", "data", "if...
Add camera trigger points to the map
[ "Add", "camera", "trigger", "points", "to", "the", "map" ]
3bc4f9338d30e2e0a0dfbed58f54d200967e5056
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/ulog2kml.py#L120-L140
train
206,596
PX4/pyulog
pyulog/core.py
ULog.get_dataset
def get_dataset(self, name, multi_instance=0): """ get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found """ return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0]
python
def get_dataset(self, name, multi_instance=0): """ get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found """ return [elem for elem in self._data_list if elem.name == name and elem.multi_id == multi_instance][0]
[ "def", "get_dataset", "(", "self", ",", "name", ",", "multi_instance", "=", "0", ")", ":", "return", "[", "elem", "for", "elem", "in", "self", ".", "_data_list", "if", "elem", ".", "name", "==", "name", "and", "elem", ".", "multi_id", "==", "multi_inst...
get a specific dataset. example: try: gyro_data = ulog.get_dataset('sensor_gyro') except (KeyError, IndexError, ValueError) as error: print(type(error), "(sensor_gyro):", error) :param name: name of the dataset :param multi_instance: the multi_id, defaults to the first :raises KeyError, IndexError, ValueError: if name or instance not found
[ "get", "a", "specific", "dataset", "." ]
3bc4f9338d30e2e0a0dfbed58f54d200967e5056
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L178-L192
train
206,597
PX4/pyulog
pyulog/core.py
ULog._add_message_info_multiple
def _add_message_info_multiple(self, msg_info): """ add a message info multiple to self._msg_info_multiple_dict """ if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_info.value]) else: self._msg_info_multiple_dict[msg_info.key] = [[msg_info.value]]
python
def _add_message_info_multiple(self, msg_info): """ add a message info multiple to self._msg_info_multiple_dict """ if msg_info.key in self._msg_info_multiple_dict: if msg_info.is_continued: self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value) else: self._msg_info_multiple_dict[msg_info.key].append([msg_info.value]) else: self._msg_info_multiple_dict[msg_info.key] = [[msg_info.value]]
[ "def", "_add_message_info_multiple", "(", "self", ",", "msg_info", ")", ":", "if", "msg_info", ".", "key", "in", "self", ".", "_msg_info_multiple_dict", ":", "if", "msg_info", ".", "is_continued", ":", "self", ".", "_msg_info_multiple_dict", "[", "msg_info", "."...
add a message info multiple to self._msg_info_multiple_dict
[ "add", "a", "message", "info", "multiple", "to", "self", ".", "_msg_info_multiple_dict" ]
3bc4f9338d30e2e0a0dfbed58f54d200967e5056
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L416-L424
train
206,598
PX4/pyulog
pyulog/core.py
ULog._load_file
def _load_file(self, log_file, message_name_filter_list): """ load and parse an ULog file into memory """ if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file # parse the whole file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_definitions() if self.has_data_appended and len(self._appended_offsets) > 0: if self._debug: print('This file has data appended') for offset in self._appended_offsets: self._read_file_data(message_name_filter_list, read_until=offset) self._file_handle.seek(offset) # read the whole file, or the rest if data appended self._read_file_data(message_name_filter_list) self._file_handle.close() del self._file_handle
python
def _load_file(self, log_file, message_name_filter_list): """ load and parse an ULog file into memory """ if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file # parse the whole file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_definitions() if self.has_data_appended and len(self._appended_offsets) > 0: if self._debug: print('This file has data appended') for offset in self._appended_offsets: self._read_file_data(message_name_filter_list, read_until=offset) self._file_handle.seek(offset) # read the whole file, or the rest if data appended self._read_file_data(message_name_filter_list) self._file_handle.close() del self._file_handle
[ "def", "_load_file", "(", "self", ",", "log_file", ",", "message_name_filter_list", ")", ":", "if", "isinstance", "(", "log_file", ",", "str", ")", ":", "self", ".", "_file_handle", "=", "open", "(", "log_file", ",", "\"rb\"", ")", "else", ":", "self", "...
load and parse an ULog file into memory
[ "load", "and", "parse", "an", "ULog", "file", "into", "memory" ]
3bc4f9338d30e2e0a0dfbed58f54d200967e5056
https://github.com/PX4/pyulog/blob/3bc4f9338d30e2e0a0dfbed58f54d200967e5056/pyulog/core.py#L426-L449
train
206,599