repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
juju/theblues
theblues/utils.py
_server_error_message
def _server_error_message(url, message): """Log and return a server error message.""" msg = _error_message.format(url=url, message=message) log.error(msg) return msg
python
def _server_error_message(url, message): """Log and return a server error message.""" msg = _error_message.format(url=url, message=message) log.error(msg) return msg
[ "def", "_server_error_message", "(", "url", ",", "message", ")", ":", "msg", "=", "_error_message", ".", "format", "(", "url", "=", "url", ",", "message", "=", "message", ")", "log", ".", "error", "(", "msg", ")", "return", "msg" ]
Log and return a server error message.
[ "Log", "and", "return", "a", "server", "error", "message", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/utils.py#L23-L27
train
Log and return a server error message.
juju/theblues
theblues/utils.py
make_request
def make_request( url, method='GET', query=None, body=None, auth=None, timeout=10, client=None, macaroons=None): """Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the q...
python
def make_request( url, method='GET', query=None, body=None, auth=None, timeout=10, client=None, macaroons=None): """Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the q...
[ "def", "make_request", "(", "url", ",", "method", "=", "'GET'", ",", "query", "=", "None", ",", "body", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "10", ",", "client", "=", "None", ",", "macaroons", "=", "None", ")", ":", "headers"...
Make a request with the provided data. @param url The url to make the request to. @param method The HTTP request method (defaulting to "GET"). @param query A dict of the query key and values. @param body The optional body as a string or as a JSON decoded dict. @param auth The optional username and ...
[ "Make", "a", "request", "with", "the", "provided", "data", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/utils.py#L30-L99
train
Make a request to the specified url with the provided data.
juju/theblues
theblues/plans.py
Plans.get_plans
def get_plans(self, reference): """Get the plans for a given charm. @param the Reference to a charm. @return a tuple of plans or an empty tuple if no plans. @raise ServerError """ response = make_request( '{}charm?charm-url={}'.format(self.url, ...
python
def get_plans(self, reference): """Get the plans for a given charm. @param the Reference to a charm. @return a tuple of plans or an empty tuple if no plans. @raise ServerError """ response = make_request( '{}charm?charm-url={}'.format(self.url, ...
[ "def", "get_plans", "(", "self", ",", "reference", ")", ":", "response", "=", "make_request", "(", "'{}charm?charm-url={}'", ".", "format", "(", "self", ".", "url", ",", "'cs:'", "+", "reference", ".", "path", "(", ")", ")", ",", "timeout", "=", "self", ...
Get the plans for a given charm. @param the Reference to a charm. @return a tuple of plans or an empty tuple if no plans. @raise ServerError
[ "Get", "the", "plans", "for", "a", "given", "charm", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L46-L72
train
Get the plans for a given charm.
juju/theblues
theblues/plans.py
Plans.list_wallets
def list_wallets(self): """Get the list of wallets. @return an dict containing a list of wallets, a total, and available credit. @raise ServerError """ response = make_request( '{}wallet'.format(self.url), timeout=self.timeout, cli...
python
def list_wallets(self): """Get the list of wallets. @return an dict containing a list of wallets, a total, and available credit. @raise ServerError """ response = make_request( '{}wallet'.format(self.url), timeout=self.timeout, cli...
[ "def", "list_wallets", "(", "self", ")", ":", "response", "=", "make_request", "(", "'{}wallet'", ".", "format", "(", "self", ".", "url", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "client", "=", "self", ".", "_client", ")", "try", ":", "...
Get the list of wallets. @return an dict containing a list of wallets, a total, and available credit. @raise ServerError
[ "Get", "the", "list", "of", "wallets", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L74-L112
train
Get the list of wallets.
juju/theblues
theblues/plans.py
Plans.get_wallet
def get_wallet(self, wallet_name): """Get a single wallet. @param the name of the wallet. @return the wallet's total. @raise ServerError """ response = make_request( '{}wallet/{}'.format(self.url, wallet_name), timeout=self.timeout, cl...
python
def get_wallet(self, wallet_name): """Get a single wallet. @param the name of the wallet. @return the wallet's total. @raise ServerError """ response = make_request( '{}wallet/{}'.format(self.url, wallet_name), timeout=self.timeout, cl...
[ "def", "get_wallet", "(", "self", ",", "wallet_name", ")", ":", "response", "=", "make_request", "(", "'{}wallet/{}'", ".", "format", "(", "self", ".", "url", ",", "wallet_name", ")", ",", "timeout", "=", "self", ".", "timeout", ",", "client", "=", "self...
Get a single wallet. @param the name of the wallet. @return the wallet's total. @raise ServerError
[ "Get", "a", "single", "wallet", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L114-L142
train
Get a single wallet.
juju/theblues
theblues/plans.py
Plans.update_wallet
def update_wallet(self, wallet_name, limit): """Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request. """ request = { 'u...
python
def update_wallet(self, wallet_name, limit): """Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request. """ request = { 'u...
[ "def", "update_wallet", "(", "self", ",", "wallet_name", ",", "limit", ")", ":", "request", "=", "{", "'update'", ":", "{", "'limit'", ":", "str", "(", "limit", ")", ",", "}", "}", "return", "make_request", "(", "'{}wallet/{}'", ".", "format", "(", "se...
Update a wallet with a new limit. @param the name of the wallet. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request.
[ "Update", "a", "wallet", "with", "a", "new", "limit", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L144-L162
train
Update a wallet with a new limit.
juju/theblues
theblues/plans.py
Plans.delete_wallet
def delete_wallet(self, wallet_name): """Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}wallet/{}'.format(self.url, wallet_name), met...
python
def delete_wallet(self, wallet_name): """Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}wallet/{}'.format(self.url, wallet_name), met...
[ "def", "delete_wallet", "(", "self", ",", "wallet_name", ")", ":", "return", "make_request", "(", "'{}wallet/{}'", ".", "format", "(", "self", ".", "url", ",", "wallet_name", ")", ",", "method", "=", "'DELETE'", ",", "timeout", "=", "self", ".", "timeout",...
Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request.
[ "Delete", "a", "wallet", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L183-L194
train
Delete a wallet.
juju/theblues
theblues/plans.py
Plans.create_budget
def create_budget(self, wallet_name, model_uuid, limit): """Create a new budget for a model and wallet. @param the name of the wallet. @param the model UUID. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_re...
python
def create_budget(self, wallet_name, model_uuid, limit): """Create a new budget for a model and wallet. @param the name of the wallet. @param the model UUID. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_re...
[ "def", "create_budget", "(", "self", ",", "wallet_name", ",", "model_uuid", ",", "limit", ")", ":", "request", "=", "{", "'model'", ":", "model_uuid", ",", "'limit'", ":", "limit", ",", "}", "return", "make_request", "(", "'{}wallet/{}/budget'", ".", "format...
Create a new budget for a model and wallet. @param the name of the wallet. @param the model UUID. @param the new value of the limit. @return a success string from the plans server. @raise ServerError via make_request.
[ "Create", "a", "new", "budget", "for", "a", "model", "and", "wallet", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L196-L214
train
Create a new budget for a model and wallet.
juju/theblues
theblues/plans.py
Plans.delete_budget
def delete_budget(self, model_uuid): """Delete a budget. @param the name of the wallet. @param the model UUID. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}model/{}/budget'.format(sel...
python
def delete_budget(self, model_uuid): """Delete a budget. @param the name of the wallet. @param the model UUID. @return a success string from the plans server. @raise ServerError via make_request. """ return make_request( '{}model/{}/budget'.format(sel...
[ "def", "delete_budget", "(", "self", ",", "model_uuid", ")", ":", "return", "make_request", "(", "'{}model/{}/budget'", ".", "format", "(", "self", ".", "url", ",", "model_uuid", ")", ",", "method", "=", "'DELETE'", ",", "timeout", "=", "self", ".", "timeo...
Delete a budget. @param the name of the wallet. @param the model UUID. @return a success string from the plans server. @raise ServerError via make_request.
[ "Delete", "a", "budget", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/plans.py#L238-L250
train
Delete a budget.
totalgood/pugnlp
src/pugnlp/stats.py
random_split
def random_split(df, first_portion=.1): """Randomly sample Dataframe rows. Typically for testset/training set cross-valication random_split(pd.DataFrame()) """ mask = np.random.binomial(1, first_portion, size=len(df)).astype(bool) return df[mask].copy(), df[~mask].copy()
python
def random_split(df, first_portion=.1): """Randomly sample Dataframe rows. Typically for testset/training set cross-valication random_split(pd.DataFrame()) """ mask = np.random.binomial(1, first_portion, size=len(df)).astype(bool) return df[mask].copy(), df[~mask].copy()
[ "def", "random_split", "(", "df", ",", "first_portion", "=", ".1", ")", ":", "mask", "=", "np", ".", "random", ".", "binomial", "(", "1", ",", "first_portion", ",", "size", "=", "len", "(", "df", ")", ")", ".", "astype", "(", "bool", ")", "return",...
Randomly sample Dataframe rows. Typically for testset/training set cross-valication random_split(pd.DataFrame())
[ "Randomly", "sample", "Dataframe", "rows", ".", "Typically", "for", "testset", "/", "training", "set", "cross", "-", "valication" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L40-L46
train
Randomly sample rows. Typically for testset or training set cross - valication random_split ( pd. DataFrame )
totalgood/pugnlp
src/pugnlp/stats.py
safe_div
def safe_div(a, b, inf=INF): """Safely divide by zero and inf and nan and produce floating point result Numerical results are equivalent to `from __future__ import division` Args: a (float or int): numerator b (float or int): denominator inf (float or object): value to return in place of d...
python
def safe_div(a, b, inf=INF): """Safely divide by zero and inf and nan and produce floating point result Numerical results are equivalent to `from __future__ import division` Args: a (float or int): numerator b (float or int): denominator inf (float or object): value to return in place of d...
[ "def", "safe_div", "(", "a", ",", "b", ",", "inf", "=", "INF", ")", ":", "with", "np", ".", "errstate", "(", "divide", "=", "'raise'", ",", "invalid", "=", "'raise'", ")", ":", "try", ":", "return", "1.", "*", "a", "/", "b", "except", "(", "Zer...
Safely divide by zero and inf and nan and produce floating point result Numerical results are equivalent to `from __future__ import division` Args: a (float or int): numerator b (float or int): denominator inf (float or object): value to return in place of division by zero errors none (f...
[ "Safely", "divide", "by", "zero", "and", "inf", "and", "nan", "and", "produce", "floating", "point", "result", "Numerical", "results", "are", "equivalent", "to", "from", "__future__", "import", "division", "Args", ":", "a", "(", "float", "or", "int", ")", ...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L49-L105
train
Safely divide a and b into a single object.
totalgood/pugnlp
src/pugnlp/stats.py
tptnfpfn_chi
def tptnfpfn_chi(*args, **kwargs): """Calculate Chi from True Positive (tp), True Negative (tn), False Positive/Negative counts. Assumes that the random variable being measured is continuous rather than discrete. Reference: https://en.wikipedia.org/wiki/Matthews_correlation_coefficient >>> round(t...
python
def tptnfpfn_chi(*args, **kwargs): """Calculate Chi from True Positive (tp), True Negative (tn), False Positive/Negative counts. Assumes that the random variable being measured is continuous rather than discrete. Reference: https://en.wikipedia.org/wiki/Matthews_correlation_coefficient >>> round(t...
[ "def", "tptnfpfn_chi", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "tp", ",", "tn", ",", "fp", ",", "fn", "=", "args_tptnfpfn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "tptnfpfn_mcc", "(", "tp", "=", "tp", ",", "tn", ...
Calculate Chi from True Positive (tp), True Negative (tn), False Positive/Negative counts. Assumes that the random variable being measured is continuous rather than discrete. Reference: https://en.wikipedia.org/wiki/Matthews_correlation_coefficient >>> round(tptnfpfn_chi(1000, 2000, 30, 40)) 2765....
[ "Calculate", "Chi", "from", "True", "Positive", "(", "tp", ")", "True", "Negative", "(", "tn", ")", "False", "Positive", "/", "Negative", "counts", ".", "Assumes", "that", "the", "random", "variable", "being", "measured", "is", "continuous", "rather", "than"...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L131-L140
train
Calculate Chi from True Positive TN and False Negative TN and FN.
totalgood/pugnlp
src/pugnlp/stats.py
args_tptnfpfn
def args_tptnfpfn(*args, **kwargs): """Convert kwargs for tp, tn, fp, fn to ordered tuple of args If a single tuple/list is passed as the first arg, it is assumed to be the desired tuple of args >>> args_tptnfpfn(1, 2, 3, 4) (1, 2, 3, 4) >>> args_tptnfpfn((1, 2, 3, 4)) (1, 2, 3, 4) >>> args_...
python
def args_tptnfpfn(*args, **kwargs): """Convert kwargs for tp, tn, fp, fn to ordered tuple of args If a single tuple/list is passed as the first arg, it is assumed to be the desired tuple of args >>> args_tptnfpfn(1, 2, 3, 4) (1, 2, 3, 4) >>> args_tptnfpfn((1, 2, 3, 4)) (1, 2, 3, 4) >>> args_...
[ "def", "args_tptnfpfn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "4", ":", "tp", ",", "tn", ",", "fp", ",", "fn", "=", "args", "elif", "len", "(", "kwargs", ")", "==", "0", ":", "if", "len", ...
Convert kwargs for tp, tn, fp, fn to ordered tuple of args If a single tuple/list is passed as the first arg, it is assumed to be the desired tuple of args >>> args_tptnfpfn(1, 2, 3, 4) (1, 2, 3, 4) >>> args_tptnfpfn((1, 2, 3, 4)) (1, 2, 3, 4) >>> args_tptnfpfn([1, 2, 3, 4]) (1, 2, 3, 4) ...
[ "Convert", "kwargs", "for", "tp", "tn", "fp", "fn", "to", "ordered", "tuple", "of", "args", "If", "a", "single", "tuple", "/", "list", "is", "passed", "as", "the", "first", "arg", "it", "is", "assumed", "to", "be", "the", "desired", "tuple", "of", "a...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L143-L173
train
Convert kwargs for tp tn fp fn to ordered tuple of args
totalgood/pugnlp
src/pugnlp/stats.py
dataframe_tptnfpfn
def dataframe_tptnfpfn(df, pos_label=True, labels=None): """Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2) >>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]] >>> columns=['Cat', 'Dog', 'Rabbit'] >>> x = np.array([[tc, pc] for (tc, row) in e...
python
def dataframe_tptnfpfn(df, pos_label=True, labels=None): """Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2) >>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]] >>> columns=['Cat', 'Dog', 'Rabbit'] >>> x = np.array([[tc, pc] for (tc, row) in e...
[ "def", "dataframe_tptnfpfn", "(", "df", ",", "pos_label", "=", "True", ",", "labels", "=", "None", ")", ":", "labels", "=", "df", ".", "columns", "if", "labels", "is", "None", "else", "labels", "neg_labels", "=", "[", "label", "for", "label", "in", "la...
Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2) >>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]] >>> columns=['Cat', 'Dog', 'Rabbit'] >>> x = np.array([[tc, pc] for (tc, row) in enumerate(matrix) for (pc, n) in enumerate(row) for i in range(n)...
[ "Count", "the", "True", "Pos", "True", "Neg", "False", "Pos", "False", "Neg", "samples", "within", "a", "confusions", "matrx", "(", "potentiall", "larger", "than", "2x2", ")", ">>>", "matrix", "=", "[[", "5", "3", "0", "]", "[", "2", "3", "1", "]", ...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L181-L206
train
Return the TPTN FPN and FPN samples within a confusions matrx.
totalgood/pugnlp
src/pugnlp/stats.py
confusion
def confusion(df, labels=['neg', 'pos']): """ Binary classification confusion """ c = pd.DataFrame(np.zeros((2, 2)), dtype=int) a, b = df.columns[:2] # labels[df.columns[:2]] c.columns = sorted(set(df[a]))[:2] c.columns.name = a c.index = list(c.columns) c.index.name = b c1, c2 = c.colu...
python
def confusion(df, labels=['neg', 'pos']): """ Binary classification confusion """ c = pd.DataFrame(np.zeros((2, 2)), dtype=int) a, b = df.columns[:2] # labels[df.columns[:2]] c.columns = sorted(set(df[a]))[:2] c.columns.name = a c.index = list(c.columns) c.index.name = b c1, c2 = c.colu...
[ "def", "confusion", "(", "df", ",", "labels", "=", "[", "'neg'", ",", "'pos'", "]", ")", ":", "c", "=", "pd", ".", "DataFrame", "(", "np", ".", "zeros", "(", "(", "2", ",", "2", ")", ")", ",", "dtype", "=", "int", ")", "a", ",", "b", "=", ...
Binary classification confusion
[ "Binary", "classification", "confusion" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L227-L240
train
Binary classification confusion
totalgood/pugnlp
src/pugnlp/stats.py
infer_pos_label
def infer_pos_label(neg_label=None): """Try to guess a positive classification label from a negative label Basis for an NLP function to find the "opposite" of a string yes->no, true->false, etc) >>> [infer_pos_label(x) for x in ('1', '-1', '0', '2', 1, 0, 'F', 'False', False, True)] ['0', '1', '1', ...
python
def infer_pos_label(neg_label=None): """Try to guess a positive classification label from a negative label Basis for an NLP function to find the "opposite" of a string yes->no, true->false, etc) >>> [infer_pos_label(x) for x in ('1', '-1', '0', '2', 1, 0, 'F', 'False', False, True)] ['0', '1', '1', ...
[ "def", "infer_pos_label", "(", "neg_label", "=", "None", ")", ":", "# A class label should be a None, bool, int, or str", "if", "neg_label", "is", "None", ":", "return", "True", "typ", "=", "type", "(", "neg_label", ")", "# If class label isn't a bool or None then make it...
Try to guess a positive classification label from a negative label Basis for an NLP function to find the "opposite" of a string yes->no, true->false, etc) >>> [infer_pos_label(x) for x in ('1', '-1', '0', '2', 1, 0, 'F', 'False', False, True)] ['0', '1', '1', '3', 0, 1, 'T', 'True', True, False]
[ "Try", "to", "guess", "a", "positive", "classification", "label", "from", "a", "negative", "label", "Basis", "for", "an", "NLP", "function", "to", "find", "the", "opposite", "of", "a", "string", "yes", "-", ">", "no", "true", "-", ">", "false", "etc", ...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L728-L768
train
Try to infer a positive classification label from a negative label
totalgood/pugnlp
src/pugnlp/stats.py
graph_from_cov_df
def graph_from_cov_df(df, threshold=.5, gain=2., n=None, class_dict=CLASSES): """Compose pair of lists of dicts (nodes, edges) for the graph described by a DataFrame""" n = n or len(df) nodes = [{'group': class_dict.get(name, 0), "name": name} for name in df.index.values][:n] edges = [] for i, (row_...
python
def graph_from_cov_df(df, threshold=.5, gain=2., n=None, class_dict=CLASSES): """Compose pair of lists of dicts (nodes, edges) for the graph described by a DataFrame""" n = n or len(df) nodes = [{'group': class_dict.get(name, 0), "name": name} for name in df.index.values][:n] edges = [] for i, (row_...
[ "def", "graph_from_cov_df", "(", "df", ",", "threshold", "=", ".5", ",", "gain", "=", "2.", ",", "n", "=", "None", ",", "class_dict", "=", "CLASSES", ")", ":", "n", "=", "n", "or", "len", "(", "df", ")", "nodes", "=", "[", "{", "'group'", ":", ...
Compose pair of lists of dicts (nodes, edges) for the graph described by a DataFrame
[ "Compose", "pair", "of", "lists", "of", "dicts", "(", "nodes", "edges", ")", "for", "the", "graph", "described", "by", "a", "DataFrame" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L776-L785
train
Compose a graph from a DataFrame
totalgood/pugnlp
src/pugnlp/stats.py
json_from_cov_df
def json_from_cov_df(df, threshold=.5, gain=2., n=None, indent=1): """Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix { "nodes": [{"group": 1, "name": "the"}, {"group": 1, "name": "and"}, {"group": 1, "name": "our"}, ...
python
def json_from_cov_df(df, threshold=.5, gain=2., n=None, indent=1): """Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix { "nodes": [{"group": 1, "name": "the"}, {"group": 1, "name": "and"}, {"group": 1, "name": "our"}, ...
[ "def", "json_from_cov_df", "(", "df", ",", "threshold", "=", ".5", ",", "gain", "=", "2.", ",", "n", "=", "None", ",", "indent", "=", "1", ")", ":", "nodes", ",", "edges", "=", "graph_from_cov_df", "(", "df", "=", "df", ",", "threshold", "=", "thre...
Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix { "nodes": [{"group": 1, "name": "the"}, {"group": 1, "name": "and"}, {"group": 1, "name": "our"}, {"group": 2, "name": "that"},... "links": [{"sour...
[ "Produce", "a", "json", "string", "describing", "the", "graph", "(", "list", "of", "edges", ")", "from", "a", "square", "auto", "-", "correlation", "/", "covariance", "matrix", "{", "nodes", ":", "[", "{", "group", ":", "1", "name", ":", "the", "}", ...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L788-L798
train
Produce a json string describing the graph from a square auto - correlation covariance matrix.
totalgood/pugnlp
src/pugnlp/stats.py
spec_from_thresh
def spec_from_thresh(thresh, labels, scores, *args, **kwargs): r"""Compute the specifity that a particular threshold on the scores can acheive specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) >>> scores = np.arange(0, 1, 0.1) >>> spec_from_thresh(0.5, labels=(scores > .5).astyp...
python
def spec_from_thresh(thresh, labels, scores, *args, **kwargs): r"""Compute the specifity that a particular threshold on the scores can acheive specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) >>> scores = np.arange(0, 1, 0.1) >>> spec_from_thresh(0.5, labels=(scores > .5).astyp...
[ "def", "spec_from_thresh", "(", "thresh", ",", "labels", ",", "scores", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "list", "(", "zip", "(", "labels", ",", "np", ".", "array", "(", "scores", ">", "...
r"""Compute the specifity that a particular threshold on the scores can acheive specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) >>> scores = np.arange(0, 1, 0.1) >>> spec_from_thresh(0.5, labels=(scores > .5).astype(int), scores=scores) 1.0 >>> spec_from_thresh(0.5, labels...
[ "r", "Compute", "the", "specifity", "that", "a", "particular", "threshold", "on", "the", "scores", "can", "acheive", "specificity", "=", "Num_True_Negative", "/", "(", "Num_True_Negative", "+", "Num_False_Positive", ")", ">>>", "scores", "=", "np", ".", "arange"...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L806-L819
train
r Compute the specifity that a particular threshold on the scores can acheive
totalgood/pugnlp
src/pugnlp/stats.py
sens_from_spec
def sens_from_spec(spec, labels, scores, *args, **kwargs): r"""Find the sensitivity that corresponds to the indicated specificity (ROC function) sensitivity = Num_True_Positive / (Num_True_Postive + Num_False_Negative) specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) """ th...
python
def sens_from_spec(spec, labels, scores, *args, **kwargs): r"""Find the sensitivity that corresponds to the indicated specificity (ROC function) sensitivity = Num_True_Positive / (Num_True_Postive + Num_False_Negative) specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) """ th...
[ "def", "sens_from_spec", "(", "spec", ",", "labels", ",", "scores", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thresh", "=", "thresh_from_spec", "(", "spec", ",", "labels", ",", "scores", ")", "df", "=", "pd", ".", "DataFrame", "(", "list"...
r"""Find the sensitivity that corresponds to the indicated specificity (ROC function) sensitivity = Num_True_Positive / (Num_True_Postive + Num_False_Negative) specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive)
[ "r", "Find", "the", "sensitivity", "that", "corresponds", "to", "the", "indicated", "specificity", "(", "ROC", "function", ")", "sensitivity", "=", "Num_True_Positive", "/", "(", "Num_True_Postive", "+", "Num_False_Negative", ")", "specificity", "=", "Num_True_Negat...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L836-L844
train
r Find the sensitivity that corresponds to the indicated specificity
totalgood/pugnlp
src/pugnlp/stats.py
cost_fun
def cost_fun(x, *args, **kwargs): """Enables minimization (root-finding) for non-zero targets Returns regularized absolute error between target and output of `fun`. Configurable state with function attributes. >>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to c...
python
def cost_fun(x, *args, **kwargs): """Enables minimization (root-finding) for non-zero targets Returns regularized absolute error between target and output of `fun`. Configurable state with function attributes. >>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to c...
[ "def", "cost_fun", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cost_fun", ".", "regularization_weight", "=", "kwargs", ".", "pop", "(", "'regularization_weight'", ",", "cost_fun", ".", "regularization_weight", ")", "cost_fun", ".", "verbo...
Enables minimization (root-finding) for non-zero targets Returns regularized absolute error between target and output of `fun`. Configurable state with function attributes. >>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to compute error >>> cost_fun.target = 1....
[ "Enables", "minimization", "(", "root", "-", "finding", ")", "for", "non", "-", "zero", "targets", "Returns", "regularized", "absolute", "error", "between", "target", "and", "output", "of", "fun", ".", "Configurable", "state", "with", "function", "attributes", ...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L847-L876
train
Enables minimization for non - zero targets Returns regularized absolute error between target and output of fun.
totalgood/pugnlp
src/pugnlp/stats.py
plot_cost
def plot_cost(scores=np.random.rand(100), thresh=0.5, noise=0): """Plot the cost function topology (contours for each of several targets)""" c = pd.DataFrame(index=np.arange(0, 1, 0.01)) if isinstance(thresh, (int, float)): thresh = [thresh] elif not isinstance(thresh, (pd.Series, np.ndarray, li...
python
def plot_cost(scores=np.random.rand(100), thresh=0.5, noise=0): """Plot the cost function topology (contours for each of several targets)""" c = pd.DataFrame(index=np.arange(0, 1, 0.01)) if isinstance(thresh, (int, float)): thresh = [thresh] elif not isinstance(thresh, (pd.Series, np.ndarray, li...
[ "def", "plot_cost", "(", "scores", "=", "np", ".", "random", ".", "rand", "(", "100", ")", ",", "thresh", "=", "0.5", ",", "noise", "=", "0", ")", ":", "c", "=", "pd", ".", "DataFrame", "(", "index", "=", "np", ".", "arange", "(", "0", ",", "...
Plot the cost function topology (contours for each of several targets)
[ "Plot", "the", "cost", "function", "topology", "(", "contours", "for", "each", "of", "several", "targets", ")" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L885-L898
train
Plot the cost function topology
totalgood/pugnlp
src/pugnlp/stats.py
fun_inverse
def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method='Nelder-Mead', **kwargs): r"""Find the threshold level that accomplishes the desired specificity Call indicated function repeatedly to find answer to the inverse function evaluation Arguments: fun (function): function to be calculate ...
python
def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method='Nelder-Mead', **kwargs): r"""Find the threshold level that accomplishes the desired specificity Call indicated function repeatedly to find answer to the inverse function evaluation Arguments: fun (function): function to be calculate ...
[ "def", "fun_inverse", "(", "fun", "=", "None", ",", "y", "=", "0", ",", "x0", "=", "None", ",", "args", "=", "(", ")", ",", "disp", "=", "False", ",", "method", "=", "'Nelder-Mead'", ",", "*", "*", "kwargs", ")", ":", "fun_inverse", ".", "fun", ...
r"""Find the threshold level that accomplishes the desired specificity Call indicated function repeatedly to find answer to the inverse function evaluation Arguments: fun (function): function to be calculate an inverse for y (float): desired output of fun x0 (float): initial guess at input to ...
[ "r", "Find", "the", "threshold", "level", "that", "accomplishes", "the", "desired", "specificity", "Call", "indicated", "function", "repeatedly", "to", "find", "answer", "to", "the", "inverse", "function", "evaluation", "Arguments", ":", "fun", "(", "function", ...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L901-L935
train
r Finds the threshold level that accomplishes the desired specificity of a function at a given target y and x0.
totalgood/pugnlp
src/pugnlp/stats.py
thresh_from_spec
def thresh_from_spec(spec, labels, scores, **kwargs): r"""Find the threshold level that accomplishes the desired specificity""" cost_fun.verbose = kwargs.pop('verbose', cost_fun.verbose) cost_fun.target = spec return minimize(cost_fun, x0=[.5], args=(labels, score...
python
def thresh_from_spec(spec, labels, scores, **kwargs): r"""Find the threshold level that accomplishes the desired specificity""" cost_fun.verbose = kwargs.pop('verbose', cost_fun.verbose) cost_fun.target = spec return minimize(cost_fun, x0=[.5], args=(labels, score...
[ "def", "thresh_from_spec", "(", "spec", ",", "labels", ",", "scores", ",", "*", "*", "kwargs", ")", ":", "cost_fun", ".", "verbose", "=", "kwargs", ".", "pop", "(", "'verbose'", ",", "cost_fun", ".", "verbose", ")", "cost_fun", ".", "target", "=", "spe...
r"""Find the threshold level that accomplishes the desired specificity
[ "r", "Find", "the", "threshold", "level", "that", "accomplishes", "the", "desired", "specificity" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L938-L951
train
r Find the threshold level that accomplishes the desired specificity.
totalgood/pugnlp
src/pugnlp/stats.py
dyno_hist
def dyno_hist(x, window=None, probability=True, edge_weight=1.): """ Probability Distribution function from values Arguments: probability (bool): whether the values should be min/max scaled to lie on the range [0, 1] Like `hist` but smoother, more accurate/useful Double-Normalization: The x ...
python
def dyno_hist(x, window=None, probability=True, edge_weight=1.): """ Probability Distribution function from values Arguments: probability (bool): whether the values should be min/max scaled to lie on the range [0, 1] Like `hist` but smoother, more accurate/useful Double-Normalization: The x ...
[ "def", "dyno_hist", "(", "x", ",", "window", "=", "None", ",", "probability", "=", "True", ",", "edge_weight", "=", "1.", ")", ":", "x", "=", "np", ".", "sort", "(", "x", ")", "if", "probability", ":", "# normalize x first", "x", "=", "x", "-", "x"...
Probability Distribution function from values Arguments: probability (bool): whether the values should be min/max scaled to lie on the range [0, 1] Like `hist` but smoother, more accurate/useful Double-Normalization: The x values are min/max normalized to lie in the range 0-1 inclusive The...
[ "Probability", "Distribution", "function", "from", "values", "Arguments", ":", "probability", "(", "bool", ")", ":", "whether", "the", "values", "should", "be", "min", "/", "max", "scaled", "to", "lie", "on", "the", "range", "[", "0", "1", "]", "Like", "...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L962-L997
train
Returns the probability distribution function from values
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.refresh_meta
def refresh_meta(self): """Calculations that only depend on aggregate counts in Confusion Matrix go here""" # these calcs are duplicated in __init__() setattr(self, '_num_classes', len(self.index)) setattr(self, '_colnums', np.arange(0, self._num_classes)) try: setat...
python
def refresh_meta(self): """Calculations that only depend on aggregate counts in Confusion Matrix go here""" # these calcs are duplicated in __init__() setattr(self, '_num_classes', len(self.index)) setattr(self, '_colnums', np.arange(0, self._num_classes)) try: setat...
[ "def", "refresh_meta", "(", "self", ")", ":", "# these calcs are duplicated in __init__()", "setattr", "(", "self", ",", "'_num_classes'", ",", "len", "(", "self", ".", "index", ")", ")", "setattr", "(", "self", ",", "'_colnums'", ",", "np", ".", "arange", "...
Calculations that only depend on aggregate counts in Confusion Matrix go here
[ "Calculations", "that", "only", "depend", "on", "aggregate", "counts", "in", "Confusion", "Matrix", "go", "here" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L487-L529
train
Refreshes the meta data for the current instance of the class.
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.from_existing
def from_existing(cls, confusion, *args, **kwargs): """Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats) >>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred']) >>> c = Confusion(df) ...
python
def from_existing(cls, confusion, *args, **kwargs): """Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats) >>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred']) >>> c = Confusion(df) ...
[ "def", "from_existing", "(", "cls", ",", "confusion", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extremely brute-force to recreate data from a confusion matrix!", "df", "=", "[", "]", "for", "t", ",", "p", "in", "product", "(", "confusion", ".", ...
Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats) >>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred']) >>> c = Confusion(df) >>> c2 = pd.DataFrame(c) >>> hasattr(c2, '_binary_sens...
[ "Creates", "a", "confusion", "matrix", "from", "a", "DataFrame", "that", "already", "contains", "confusion", "counts", "(", "but", "not", "meta", "stats", ")", ">>>", "df", "=", "pd", ".", "DataFrame", "(", "np", ".", "matrix", "(", "[[", "0", "1", "2"...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L536-L562
train
Creates a new confusion matrix from an existing DataFrame.
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.get_accuracy
def get_accuracy(self, scalar=None): """Num_True_Positive / Num_Samples""" # to get a Series instead of a dict: # (np.diag(c).astype(float) / c.T.sum()) # == pd.Series(self.sensitivity) if ((not self._scalar_stats and not scalar and self._num_classes > 2) or (...
python
def get_accuracy(self, scalar=None): """Num_True_Positive / Num_Samples""" # to get a Series instead of a dict: # (np.diag(c).astype(float) / c.T.sum()) # == pd.Series(self.sensitivity) if ((not self._scalar_stats and not scalar and self._num_classes > 2) or (...
[ "def", "get_accuracy", "(", "self", ",", "scalar", "=", "None", ")", ":", "# to get a Series instead of a dict:", "# (np.diag(c).astype(float) / c.T.sum())", "# == pd.Series(self.sensitivity)", "if", "(", "(", "not", "self", ".", "_scalar_stats", "and", "not", "scalar...
Num_True_Positive / Num_Samples
[ "Num_True_Positive", "/", "Num_Samples" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L564-L572
train
get the accuracy of the class
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.get_sensitivity
def get_sensitivity(self, scalar=None): """True Positive Rate = TP / P = Num_True_Positive / (Num_True_Postive + Num_False_Negative)""" # to get a Series instead of a dict: # (np.diag(c).astype(float) / c.T.sum()) # == pd.Series(self.sensitivity) if ((not self._scalar_stats a...
python
def get_sensitivity(self, scalar=None): """True Positive Rate = TP / P = Num_True_Positive / (Num_True_Postive + Num_False_Negative)""" # to get a Series instead of a dict: # (np.diag(c).astype(float) / c.T.sum()) # == pd.Series(self.sensitivity) if ((not self._scalar_stats a...
[ "def", "get_sensitivity", "(", "self", ",", "scalar", "=", "None", ")", ":", "# to get a Series instead of a dict:", "# (np.diag(c).astype(float) / c.T.sum())", "# == pd.Series(self.sensitivity)", "if", "(", "(", "not", "self", ".", "_scalar_stats", "and", "not", "sca...
True Positive Rate = TP / P = Num_True_Positive / (Num_True_Postive + Num_False_Negative)
[ "True", "Positive", "Rate", "=", "TP", "/", "P", "=", "Num_True_Positive", "/", "(", "Num_True_Postive", "+", "Num_False_Negative", ")" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L575-L583
train
Returns the sensitivity of the class.
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.get_specificity
def get_specificity(self, scalar=None): """True_Negative / (True_Negative + False_Positive)""" if ((not self._scalar_stats and not scalar and self._num_classes > 2) or ((scalar is False or self._scalar_stats is False) and self._num_classes > 1)): spec = PrettyDict() ...
python
def get_specificity(self, scalar=None): """True_Negative / (True_Negative + False_Positive)""" if ((not self._scalar_stats and not scalar and self._num_classes > 2) or ((scalar is False or self._scalar_stats is False) and self._num_classes > 1)): spec = PrettyDict() ...
[ "def", "get_specificity", "(", "self", ",", "scalar", "=", "None", ")", ":", "if", "(", "(", "not", "self", ".", "_scalar_stats", "and", "not", "scalar", "and", "self", ".", "_num_classes", ">", "2", ")", "or", "(", "(", "scalar", "is", "False", "or"...
True_Negative / (True_Negative + False_Positive)
[ "True_Negative", "/", "(", "True_Negative", "+", "False_Positive", ")" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L586-L599
train
Returns a pandas Series of specificity of the binary class.
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.get_phi
def get_phi(self, scalar=None): """Phi (φ) Coefficient -- lack of confusion Arguments: scalar (bool or None): Whether to return a scalar Phi coefficient (assume binary classification) rather than a multiclass vector Measure of the lack of confusion in a single value R...
python
def get_phi(self, scalar=None): """Phi (φ) Coefficient -- lack of confusion Arguments: scalar (bool or None): Whether to return a scalar Phi coefficient (assume binary classification) rather than a multiclass vector Measure of the lack of confusion in a single value R...
[ "def", "get_phi", "(", "self", ",", "scalar", "=", "None", ")", ":", "# If requested, compute the phi coeffients for all possible 'positive' and 'negative' class labels", "# (multiclass problem)", "if", "(", "(", "not", "self", ".", "_scalar_stats", "and", "not", "scalar", ...
Phi (φ) Coefficient -- lack of confusion Arguments: scalar (bool or None): Whether to return a scalar Phi coefficient (assume binary classification) rather than a multiclass vector Measure of the lack of confusion in a single value References: [MCC on wikipedia](htt...
[ "Phi", "(", "φ", ")", "Coefficient", "--", "lack", "of", "confusion", "Arguments", ":", "scalar", "(", "bool", "or", "None", ")", ":", "Whether", "to", "return", "a", "scalar", "Phi", "coefficient", "(", "assume", "binary", "classification", ")", "rather",...
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L602-L626
train
Returns the phi coefficient for the class with respect to the class labels.
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.get_chi
def get_chi(self, scalar=None): """sqrt(Chi_Squared) statistic (see `mcc`, `phi`, or google 'Matthews Correlation Coefficient'""" phi = self.get_phi(scalar=scalar) return mcc_chi(phi, self._num_samples)
python
def get_chi(self, scalar=None): """sqrt(Chi_Squared) statistic (see `mcc`, `phi`, or google 'Matthews Correlation Coefficient'""" phi = self.get_phi(scalar=scalar) return mcc_chi(phi, self._num_samples)
[ "def", "get_chi", "(", "self", ",", "scalar", "=", "None", ")", ":", "phi", "=", "self", ".", "get_phi", "(", "scalar", "=", "scalar", ")", "return", "mcc_chi", "(", "phi", ",", "self", ".", "_num_samples", ")" ]
sqrt(Chi_Squared) statistic (see `mcc`, `phi`, or google 'Matthews Correlation Coefficient
[ "sqrt", "(", "Chi_Squared", ")", "statistic", "(", "see", "mcc", "phi", "or", "google", "Matthews", "Correlation", "Coefficient" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L632-L635
train
get the Chi_Squared statistic
totalgood/pugnlp
src/pugnlp/stats.py
Confusion.get_false_negative
def get_false_negative(self, scalar=True): """Normalized false positive rate (0 <= fp <= 1)""" ans = pd.Series(PrettyDict([(k, safe_div(np.sum(self.loc[k]) - self[k][k], np.sum(self.sum() - self.loc[k]))) for k in self.columns])) if (not self._sca...
python
def get_false_negative(self, scalar=True): """Normalized false positive rate (0 <= fp <= 1)""" ans = pd.Series(PrettyDict([(k, safe_div(np.sum(self.loc[k]) - self[k][k], np.sum(self.sum() - self.loc[k]))) for k in self.columns])) if (not self._sca...
[ "def", "get_false_negative", "(", "self", ",", "scalar", "=", "True", ")", ":", "ans", "=", "pd", ".", "Series", "(", "PrettyDict", "(", "[", "(", "k", ",", "safe_div", "(", "np", ".", "sum", "(", "self", ".", "loc", "[", "k", "]", ")", "-", "s...
Normalized false positive rate (0 <= fp <= 1)
[ "Normalized", "false", "positive", "rate", "(", "0", "<", "=", "fp", "<", "=", "1", ")" ]
c43445b14afddfdeadc5f3076675c9e8fc1ee67c
https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/stats.py#L660-L666
train
Returns the normalized false positive rate.
DarkEnergySurvey/ugali
ugali/preprocess/padova.py
Download.download
def download(self,age,metallicity,outdir=None,force=False): """ Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd """ if outdir is None: outdir = './' basename = self.isochrone.params2filename(age,metallicity) outfile =...
python
def download(self,age,metallicity,outdir=None,force=False): """ Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd """ if outdir is None: outdir = './' basename = self.isochrone.params2filename(age,metallicity) outfile =...
[ "def", "download", "(", "self", ",", "age", ",", "metallicity", ",", "outdir", "=", "None", ",", "force", "=", "False", ")", ":", "if", "outdir", "is", "None", ":", "outdir", "=", "'./'", "basename", "=", "self", ".", "isochrone", ".", "params2filename...
Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd
[ "Check", "valid", "parameter", "range", "and", "download", "isochrones", "from", ":", "http", ":", "//", "stev", ".", "oapd", ".", "inaf", ".", "it", "/", "cgi", "-", "bin", "/", "cmd" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/preprocess/padova.py#L128-L168
train
Download isochrone from the server and return the path to the downloaded file.
stevearc/dynamo3
dynamo3/result.py
add_dicts
def add_dicts(d1, d2): """ Merge two dicts of addable values """ if d1 is None: return d2 if d2 is None: return d1 keys = set(d1) keys.update(set(d2)) ret = {} for key in keys: v1 = d1.get(key) v2 = d2.get(key) if v1 is None: ret[key] = v2 ...
python
def add_dicts(d1, d2): """ Merge two dicts of addable values """ if d1 is None: return d2 if d2 is None: return d1 keys = set(d1) keys.update(set(d2)) ret = {} for key in keys: v1 = d1.get(key) v2 = d2.get(key) if v1 is None: ret[key] = v2 ...
[ "def", "add_dicts", "(", "d1", ",", "d2", ")", ":", "if", "d1", "is", "None", ":", "return", "d2", "if", "d2", "is", "None", ":", "return", "d1", "keys", "=", "set", "(", "d1", ")", "keys", ".", "update", "(", "set", "(", "d2", ")", ")", "ret...
Merge two dicts of addable values
[ "Merge", "two", "dicts", "of", "addable", "values" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L7-L25
train
Merge two dicts of addable values
stevearc/dynamo3
dynamo3/result.py
PagedIterator._update_capacity
def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consumed = data['ConsumedCapacity'] if not isinstance(consumed, list): consumed = [consumed] ...
python
def _update_capacity(self, data): """ Update the consumed capacity metrics """ if 'ConsumedCapacity' in data: # This is all for backwards compatibility consumed = data['ConsumedCapacity'] if not isinstance(consumed, list): consumed = [consumed] ...
[ "def", "_update_capacity", "(", "self", ",", "data", ")", ":", "if", "'ConsumedCapacity'", "in", "data", ":", "# This is all for backwards compatibility", "consumed", "=", "data", "[", "'ConsumedCapacity'", "]", "if", "not", "isinstance", "(", "consumed", ",", "li...
Update the consumed capacity metrics
[ "Update", "the", "consumed", "capacity", "metrics" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L233-L251
train
Update the consumed capacity metrics
stevearc/dynamo3
dynamo3/result.py
ResultSet.fetch
def fetch(self): """ Fetch more results from Dynamo """ self.limit.set_request_args(self.kwargs) data = self.connection.call(*self.args, **self.kwargs) self.limit.post_fetch(data) self.last_evaluated_key = data.get('LastEvaluatedKey') if self.last_evaluated_key is None: ...
python
def fetch(self): """ Fetch more results from Dynamo """ self.limit.set_request_args(self.kwargs) data = self.connection.call(*self.args, **self.kwargs) self.limit.post_fetch(data) self.last_evaluated_key = data.get('LastEvaluatedKey') if self.last_evaluated_key is None: ...
[ "def", "fetch", "(", "self", ")", ":", "self", ".", "limit", ".", "set_request_args", "(", "self", ".", "kwargs", ")", "data", "=", "self", ".", "connection", ".", "call", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")", ...
Fetch more results from Dynamo
[ "Fetch", "more", "results", "from", "Dynamo" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L288-L304
train
Fetch more results from Dynamo
stevearc/dynamo3
dynamo3/result.py
GetResultSet.build_kwargs
def build_kwargs(self): """ Construct the kwargs to pass to batch_get_item """ keys, self.keys = self.keys[:MAX_GET_BATCH], self.keys[MAX_GET_BATCH:] query = {'ConsistentRead': self.consistent} if self.attributes is not None: query['ProjectionExpression'] = self.attributes ...
python
def build_kwargs(self): """ Construct the kwargs to pass to batch_get_item """ keys, self.keys = self.keys[:MAX_GET_BATCH], self.keys[MAX_GET_BATCH:] query = {'ConsistentRead': self.consistent} if self.attributes is not None: query['ProjectionExpression'] = self.attributes ...
[ "def", "build_kwargs", "(", "self", ")", ":", "keys", ",", "self", ".", "keys", "=", "self", ".", "keys", "[", ":", "MAX_GET_BATCH", "]", ",", "self", ".", "keys", "[", "MAX_GET_BATCH", ":", "]", "query", "=", "{", "'ConsistentRead'", ":", "self", "....
Construct the kwargs to pass to batch_get_item
[ "Construct", "the", "kwargs", "to", "pass", "to", "batch_get_item" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L331-L345
train
Construct the kwargs to pass to batch_get_item
stevearc/dynamo3
dynamo3/result.py
GetResultSet.fetch
def fetch(self): """ Fetch a set of items from their keys """ kwargs = self.build_kwargs() data = self.connection.call('batch_get_item', **kwargs) if 'UnprocessedKeys' in data: for items in six.itervalues(data['UnprocessedKeys']): self.keys.extend(items['Keys'...
python
def fetch(self): """ Fetch a set of items from their keys """ kwargs = self.build_kwargs() data = self.connection.call('batch_get_item', **kwargs) if 'UnprocessedKeys' in data: for items in six.itervalues(data['UnprocessedKeys']): self.keys.extend(items['Keys'...
[ "def", "fetch", "(", "self", ")", ":", "kwargs", "=", "self", ".", "build_kwargs", "(", ")", "data", "=", "self", ".", "connection", ".", "call", "(", "'batch_get_item'", ",", "*", "*", "kwargs", ")", "if", "'UnprocessedKeys'", "in", "data", ":", "for"...
Fetch a set of items from their keys
[ "Fetch", "a", "set", "of", "items", "from", "their", "keys" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L347-L367
train
Fetch a set of items from their keys
stevearc/dynamo3
dynamo3/result.py
Limit.copy
def copy(self): """ Return a copy of the limit """ return Limit(self.scan_limit, self.item_limit, self.min_scan_limit, self.strict, self.filter)
python
def copy(self): """ Return a copy of the limit """ return Limit(self.scan_limit, self.item_limit, self.min_scan_limit, self.strict, self.filter)
[ "def", "copy", "(", "self", ")", ":", "return", "Limit", "(", "self", ".", "scan_limit", ",", "self", ".", "item_limit", ",", "self", ".", "min_scan_limit", ",", "self", ".", "strict", ",", "self", ".", "filter", ")" ]
Return a copy of the limit
[ "Return", "a", "copy", "of", "the", "limit" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L494-L497
train
Return a copy of the limit
stevearc/dynamo3
dynamo3/result.py
Limit.set_request_args
def set_request_args(self, args): """ Set the Limit parameter into the request args """ if self.scan_limit is not None: args['Limit'] = self.scan_limit elif self.item_limit is not None: args['Limit'] = max(self.item_limit, self.min_scan_limit) else: ar...
python
def set_request_args(self, args): """ Set the Limit parameter into the request args """ if self.scan_limit is not None: args['Limit'] = self.scan_limit elif self.item_limit is not None: args['Limit'] = max(self.item_limit, self.min_scan_limit) else: ar...
[ "def", "set_request_args", "(", "self", ",", "args", ")", ":", "if", "self", ".", "scan_limit", "is", "not", "None", ":", "args", "[", "'Limit'", "]", "=", "self", ".", "scan_limit", "elif", "self", ".", "item_limit", "is", "not", "None", ":", "args", ...
Set the Limit parameter into the request args
[ "Set", "the", "Limit", "parameter", "into", "the", "request", "args" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L499-L506
train
Set the Limit parameter into the request args
stevearc/dynamo3
dynamo3/result.py
Limit.complete
def complete(self): """ Return True if the limit has been reached """ if self.scan_limit is not None and self.scan_limit == 0: return True if self.item_limit is not None and self.item_limit == 0: return True return False
python
def complete(self): """ Return True if the limit has been reached """ if self.scan_limit is not None and self.scan_limit == 0: return True if self.item_limit is not None and self.item_limit == 0: return True return False
[ "def", "complete", "(", "self", ")", ":", "if", "self", ".", "scan_limit", "is", "not", "None", "and", "self", ".", "scan_limit", "==", "0", ":", "return", "True", "if", "self", ".", "item_limit", "is", "not", "None", "and", "self", ".", "item_limit", ...
Return True if the limit has been reached
[ "Return", "True", "if", "the", "limit", "has", "been", "reached" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L509-L515
train
Return True if the limit has been reached False otherwise.
stevearc/dynamo3
dynamo3/result.py
Limit.accept
def accept(self, item): """ Apply the filter and item_limit, and return True to accept """ accept = self.filter(item) if accept and self.item_limit is not None: if self.item_limit > 0: self.item_limit -= 1 elif self.strict: return False ...
python
def accept(self, item): """ Apply the filter and item_limit, and return True to accept """ accept = self.filter(item) if accept and self.item_limit is not None: if self.item_limit > 0: self.item_limit -= 1 elif self.strict: return False ...
[ "def", "accept", "(", "self", ",", "item", ")", ":", "accept", "=", "self", ".", "filter", "(", "item", ")", "if", "accept", "and", "self", ".", "item_limit", "is", "not", "None", ":", "if", "self", ".", "item_limit", ">", "0", ":", "self", ".", ...
Apply the filter and item_limit, and return True to accept
[ "Apply", "the", "filter", "and", "item_limit", "and", "return", "True", "to", "accept" ]
f897c40ece28586272dbcab8f0d99a14a1831dda
https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/result.py#L522-L530
train
Apply the filter and item_limit and return True if the item is acceptable False otherwise.
aht/stream.py
example/randwalk.py
returned
def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return...
python
def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return...
[ "def", "returned", "(", "n", ")", ":", "## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk", "for", "pos", "in", "randwalk", "(", ")", ">>", "drop", "(", "1", ")", ">>", "takei", "(", "xrange", "(", "n", "-", "1", ")", ")", ...
Generate a random walk and return True if the walker has returned to the origin after taking `n` steps.
[ "Generate", "a", "random", "walk", "and", "return", "True", "if", "the", "walker", "has", "returned", "to", "the", "origin", "after", "taking", "n", "steps", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/example/randwalk.py#L16-L24
train
Generate a random walk and return True if the walker has returned to the origin after taking n steps.
aht/stream.py
example/randwalk.py
first_return
def first_return(): """Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of ...
python
def first_return(): """Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of ...
[ "def", "first_return", "(", ")", ":", "walk", "=", "randwalk", "(", ")", ">>", "drop", "(", "1", ")", ">>", "takewhile", "(", "lambda", "v", ":", "v", "!=", "Origin", ")", ">>", "list", "return", "len", "(", "walk", ")" ]
Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of memory! Thus, try this ...
[ "Generate", "a", "random", "walk", "and", "return", "its", "length", "upto", "the", "moment", "that", "the", "walker", "first", "returns", "to", "the", "origin", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/example/randwalk.py#L26-L36
train
Generate a random walk and return its length upto the moment that the walker first returns to the origin.
aht/stream.py
stream.py
seq
def seq(start=0, step=1): """An arithmetic sequence generator. Works with any type with + defined. >>> seq(1, 0.25) >> item[:10] [1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25] """ def seq(a, d): while 1: yield a a += d return seq(start, step)
python
def seq(start=0, step=1): """An arithmetic sequence generator. Works with any type with + defined. >>> seq(1, 0.25) >> item[:10] [1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25] """ def seq(a, d): while 1: yield a a += d return seq(start, step)
[ "def", "seq", "(", "start", "=", "0", ",", "step", "=", "1", ")", ":", "def", "seq", "(", "a", ",", "d", ")", ":", "while", "1", ":", "yield", "a", "a", "+=", "d", "return", "seq", "(", "start", ",", "step", ")" ]
An arithmetic sequence generator. Works with any type with + defined. >>> seq(1, 0.25) >> item[:10] [1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25]
[ "An", "arithmetic", "sequence", "generator", ".", "Works", "with", "any", "type", "with", "+", "defined", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1194-L1204
train
An arithmetic sequence generator.
aht/stream.py
stream.py
reduce
def reduce(function, initval=None): """ Curried version of the built-in reduce. >>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] ) 15 """ if initval is None: return lambda s: __builtin__.reduce(function, s) else: return lambda s: __builtin__.reduce(function, s, initval)
python
def reduce(function, initval=None): """ Curried version of the built-in reduce. >>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] ) 15 """ if initval is None: return lambda s: __builtin__.reduce(function, s) else: return lambda s: __builtin__.reduce(function, s, initval)
[ "def", "reduce", "(", "function", ",", "initval", "=", "None", ")", ":", "if", "initval", "is", "None", ":", "return", "lambda", "s", ":", "__builtin__", ".", "reduce", "(", "function", ",", "s", ")", "else", ":", "return", "lambda", "s", ":", "__bui...
Curried version of the built-in reduce. >>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] ) 15
[ "Curried", "version", "of", "the", "built", "-", "in", "reduce", ".", ">>>", "reduce", "(", "lambda", "x", "y", ":", "x", "+", "y", ")", "(", "[", "1", "2", "3", "4", "5", "]", ")", "15" ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1263-L1273
train
Function to reduce the elements of a sequence.
aht/stream.py
stream.py
Stream.pipe
def pipe(inpipe, outpipe): """Connect inpipe and outpipe. If outpipe is not a Stream instance, it should be an function callable on an iterable. """ if hasattr(outpipe, '__pipe__'): return outpipe.__pipe__(inpipe) elif hasattr(outpipe, '__call__'): return outpipe(inpipe) else: raise BrokenPipe('No...
python
def pipe(inpipe, outpipe): """Connect inpipe and outpipe. If outpipe is not a Stream instance, it should be an function callable on an iterable. """ if hasattr(outpipe, '__pipe__'): return outpipe.__pipe__(inpipe) elif hasattr(outpipe, '__call__'): return outpipe(inpipe) else: raise BrokenPipe('No...
[ "def", "pipe", "(", "inpipe", ",", "outpipe", ")", ":", "if", "hasattr", "(", "outpipe", ",", "'__pipe__'", ")", ":", "return", "outpipe", ".", "__pipe__", "(", "inpipe", ")", "elif", "hasattr", "(", "outpipe", ",", "'__call__'", ")", ":", "return", "o...
Connect inpipe and outpipe. If outpipe is not a Stream instance, it should be an function callable on an iterable.
[ "Connect", "inpipe", "and", "outpipe", ".", "If", "outpipe", "is", "not", "a", "Stream", "instance", "it", "should", "be", "an", "function", "callable", "on", "an", "iterable", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L170-L179
train
Connect inpipe and outpipe.
aht/stream.py
stream.py
Stream.extend
def extend(self, outpipe): """Similar to __pipe__, except that outpipe must be a Stream, in which case self.iterator will be modified in-place by calling outpipe.__call__ on it. """ self.iterator = outpipe.__call__(self.iterator) return self
python
def extend(self, outpipe): """Similar to __pipe__, except that outpipe must be a Stream, in which case self.iterator will be modified in-place by calling outpipe.__call__ on it. """ self.iterator = outpipe.__call__(self.iterator) return self
[ "def", "extend", "(", "self", ",", "outpipe", ")", ":", "self", ".", "iterator", "=", "outpipe", ".", "__call__", "(", "self", ".", "iterator", ")", "return", "self" ]
Similar to __pipe__, except that outpipe must be a Stream, in which case self.iterator will be modified in-place by calling outpipe.__call__ on it.
[ "Similar", "to", "__pipe__", "except", "that", "outpipe", "must", "be", "a", "Stream", "in", "which", "case", "self", ".", "iterator", "will", "be", "modified", "in", "-", "place", "by", "calling", "outpipe", ".", "__call__", "on", "it", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L187-L193
train
Extend the current Stream with the contents of another Stream.
aht/stream.py
stream.py
Executor.submit
def submit(self, *items): """Return job ids assigned to the submitted items.""" with self.lock: if self.closed: raise BrokenPipe('Job submission has been closed.') id = self.jobcount self._status += ['SUBMITTED'] * len(items) self.jobcount += len(items) for item in items: self.waitqueue.put((...
python
def submit(self, *items): """Return job ids assigned to the submitted items.""" with self.lock: if self.closed: raise BrokenPipe('Job submission has been closed.') id = self.jobcount self._status += ['SUBMITTED'] * len(items) self.jobcount += len(items) for item in items: self.waitqueue.put((...
[ "def", "submit", "(", "self", ",", "*", "items", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "closed", ":", "raise", "BrokenPipe", "(", "'Job submission has been closed.'", ")", "id", "=", "self", ".", "jobcount", "self", ".", "_status...
Return job ids assigned to the submitted items.
[ "Return", "job", "ids", "assigned", "to", "the", "submitted", "items", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L980-L994
train
Submit the given items.
aht/stream.py
stream.py
Executor.cancel
def cancel(self, *ids): """Try to cancel jobs with associated ids. Return the actual number of jobs cancelled. """ ncancelled = 0 with self.lock: for id in ids: try: if self._status[id] == 'SUBMITTED': self._status[id] = 'CANCELLED' ncancelled += 1 except IndexError: pass ...
python
def cancel(self, *ids): """Try to cancel jobs with associated ids. Return the actual number of jobs cancelled. """ ncancelled = 0 with self.lock: for id in ids: try: if self._status[id] == 'SUBMITTED': self._status[id] = 'CANCELLED' ncancelled += 1 except IndexError: pass ...
[ "def", "cancel", "(", "self", ",", "*", "ids", ")", ":", "ncancelled", "=", "0", "with", "self", ".", "lock", ":", "for", "id", "in", "ids", ":", "try", ":", "if", "self", ".", "_status", "[", "id", "]", "==", "'SUBMITTED'", ":", "self", ".", "...
Try to cancel jobs with associated ids. Return the actual number of jobs cancelled.
[ "Try", "to", "cancel", "jobs", "with", "associated", "ids", ".", "Return", "the", "actual", "number", "of", "jobs", "cancelled", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L996-L1010
train
Try to cancel jobs with associated ids. Returns the actual number of jobs cancelled.
aht/stream.py
stream.py
Executor.status
def status(self, *ids): """Return the statuses of jobs with associated ids at the time of call: either 'SUBMITED', 'CANCELLED', 'RUNNING', 'COMPLETED' or 'FAILED'. """ with self.lock: if len(ids) > 1: return [self._status[i] for i in ids] else: return self._status[ids[0]]
python
def status(self, *ids): """Return the statuses of jobs with associated ids at the time of call: either 'SUBMITED', 'CANCELLED', 'RUNNING', 'COMPLETED' or 'FAILED'. """ with self.lock: if len(ids) > 1: return [self._status[i] for i in ids] else: return self._status[ids[0]]
[ "def", "status", "(", "self", ",", "*", "ids", ")", ":", "with", "self", ".", "lock", ":", "if", "len", "(", "ids", ")", ">", "1", ":", "return", "[", "self", ".", "_status", "[", "i", "]", "for", "i", "in", "ids", "]", "else", ":", "return",...
Return the statuses of jobs with associated ids at the time of call: either 'SUBMITED', 'CANCELLED', 'RUNNING', 'COMPLETED' or 'FAILED'.
[ "Return", "the", "statuses", "of", "jobs", "with", "associated", "ids", "at", "the", "time", "of", "call", ":", "either", "SUBMITED", "CANCELLED", "RUNNING", "COMPLETED", "or", "FAILED", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1012-L1021
train
Return the statuses of the jobs with associated ids at the time of call.
aht/stream.py
stream.py
Executor.close
def close(self): """Signal that the executor will no longer accept job submission. Worker threads/processes are now allowed to terminate after all jobs have been are completed. Without a call to close(), they will stay around forever waiting for more jobs to come. """ with self.lock: if self.closed: ...
python
def close(self): """Signal that the executor will no longer accept job submission. Worker threads/processes are now allowed to terminate after all jobs have been are completed. Without a call to close(), they will stay around forever waiting for more jobs to come. """ with self.lock: if self.closed: ...
[ "def", "close", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "closed", ":", "return", "self", ".", "waitqueue", ".", "put", "(", "StopIteration", ")", "self", ".", "closed", "=", "True" ]
Signal that the executor will no longer accept job submission. Worker threads/processes are now allowed to terminate after all jobs have been are completed. Without a call to close(), they will stay around forever waiting for more jobs to come.
[ "Signal", "that", "the", "executor", "will", "no", "longer", "accept", "job", "submission", ".", "Worker", "threads", "/", "processes", "are", "now", "allowed", "to", "terminate", "after", "all", "jobs", "have", "been", "are", "completed", ".", "Without", "a...
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1023-L1034
train
Signal that the executor will no longer accept jobs.
aht/stream.py
stream.py
Executor.join
def join(self): """Note that the Executor must be close()'d elsewhere, or join() will never return. """ self.inputfeeder_thread.join() self.pool.join() self.resulttracker_thread.join() self.failuretracker_thread.join()
python
def join(self): """Note that the Executor must be close()'d elsewhere, or join() will never return. """ self.inputfeeder_thread.join() self.pool.join() self.resulttracker_thread.join() self.failuretracker_thread.join()
[ "def", "join", "(", "self", ")", ":", "self", ".", "inputfeeder_thread", ".", "join", "(", ")", "self", ".", "pool", ".", "join", "(", ")", "self", ".", "resulttracker_thread", ".", "join", "(", ")", "self", ".", "failuretracker_thread", ".", "join", "...
Note that the Executor must be close()'d elsewhere, or join() will never return.
[ "Note", "that", "the", "Executor", "must", "be", "close", "()", "d", "elsewhere", "or", "join", "()", "will", "never", "return", "." ]
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1036-L1043
train
Join the threads that are waiting for the executor to finish.
aht/stream.py
stream.py
Executor.shutdown
def shutdown(self): """Shut down the Executor. Suspend all waiting jobs. Running workers will terminate after finishing their current job items. The call will block until all workers are terminated. """ with self.lock: self.pool.inqueue.put(StopIteration) # Stop the pool workers self.waitqueue.put...
python
def shutdown(self): """Shut down the Executor. Suspend all waiting jobs. Running workers will terminate after finishing their current job items. The call will block until all workers are terminated. """ with self.lock: self.pool.inqueue.put(StopIteration) # Stop the pool workers self.waitqueue.put...
[ "def", "shutdown", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "pool", ".", "inqueue", ".", "put", "(", "StopIteration", ")", "# Stop the pool workers", "self", ".", "waitqueue", ".", "put", "(", "StopIteration", ")", "# Stop the ...
Shut down the Executor. Suspend all waiting jobs. Running workers will terminate after finishing their current job items. The call will block until all workers are terminated.
[ "Shut", "down", "the", "Executor", ".", "Suspend", "all", "waiting", "jobs", ".", "Running", "workers", "will", "terminate", "after", "finishing", "their", "current", "job", "items", ".", "The", "call", "will", "block", "until", "all", "workers", "are", "ter...
6a4945cbddaf74138eee5ba33eee3988cfceb84d
https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/stream.py#L1045-L1056
train
Shut down the Executor.
Zephrys/monica
monica/monica.py
main
def main(): '''monica helps you order food from the timeline''' arguments = docopt(__doc__, version=__version__) if arguments['configure'] and flag: configure() if arguments['cuisine']: if arguments['list']: cuisine('list') else: cuisine(arguments['<cuisine-id>']) elif arguments['surp...
python
def main(): '''monica helps you order food from the timeline''' arguments = docopt(__doc__, version=__version__) if arguments['configure'] and flag: configure() if arguments['cuisine']: if arguments['list']: cuisine('list') else: cuisine(arguments['<cuisine-id>']) elif arguments['surp...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", "(", "__doc__", ",", "version", "=", "__version__", ")", "if", "arguments", "[", "'configure'", "]", "and", "flag", ":", "configure", "(", ")", "if", "arguments", "[", "'cuisine'", "]", ":", "if...
monica helps you order food from the timeline
[ "monica", "helps", "you", "order", "food", "from", "the", "timeline" ]
ff0bc7df18d86ad66af6c655cdd292ddceb84fd7
https://github.com/Zephrys/monica/blob/ff0bc7df18d86ad66af6c655cdd292ddceb84fd7/monica/monica.py#L214-L241
train
monica helps you order food from the timeline
alphagov/performanceplatform-collector
setup.py
_get_requirements
def _get_requirements(fname): """ Create a list of requirements from the output of the pip freeze command saved in a text file. """ packages = _read(fname).split('\n') packages = (p.strip() for p in packages) packages = (p for p in packages if p and not p.startswith('#')) return list(pac...
python
def _get_requirements(fname): """ Create a list of requirements from the output of the pip freeze command saved in a text file. """ packages = _read(fname).split('\n') packages = (p.strip() for p in packages) packages = (p for p in packages if p and not p.startswith('#')) return list(pac...
[ "def", "_get_requirements", "(", "fname", ")", ":", "packages", "=", "_read", "(", "fname", ")", ".", "split", "(", "'\\n'", ")", "packages", "=", "(", "p", ".", "strip", "(", ")", "for", "p", "in", "packages", ")", "packages", "=", "(", "p", "for"...
Create a list of requirements from the output of the pip freeze command saved in a text file.
[ "Create", "a", "list", "of", "requirements", "from", "the", "output", "of", "the", "pip", "freeze", "command", "saved", "in", "a", "text", "file", "." ]
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/setup.py#L41-L49
train
Get a list of requirements from a pip freeze command.
BertrandBordage/django-terms
terms/cms_plugin_processors.py
TermsProcessor
def TermsProcessor(instance, placeholder, rendered_content, original_context): """ Adds links all placeholders plugins except django-terms plugins """ if 'terms' in original_context: return rendered_content return mark_safe(replace_terms(rendered_content))
python
def TermsProcessor(instance, placeholder, rendered_content, original_context): """ Adds links all placeholders plugins except django-terms plugins """ if 'terms' in original_context: return rendered_content return mark_safe(replace_terms(rendered_content))
[ "def", "TermsProcessor", "(", "instance", ",", "placeholder", ",", "rendered_content", ",", "original_context", ")", ":", "if", "'terms'", "in", "original_context", ":", "return", "rendered_content", "return", "mark_safe", "(", "replace_terms", "(", "rendered_content"...
Adds links all placeholders plugins except django-terms plugins
[ "Adds", "links", "all", "placeholders", "plugins", "except", "django", "-", "terms", "plugins" ]
2555c2cf5abf14adef9a8e2dd22c4a9076396a10
https://github.com/BertrandBordage/django-terms/blob/2555c2cf5abf14adef9a8e2dd22c4a9076396a10/terms/cms_plugin_processors.py#L7-L14
train
Processes the terms template.
DarkEnergySurvey/ugali
setup.py
install.install_isochrones
def install_isochrones(self): """ Call to isochrone install command: http://stackoverflow.com/a/24353921/4075339 """ cmd_obj = self.distribution.get_command_obj('isochrones') cmd_obj.force = self.force if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir ...
python
def install_isochrones(self): """ Call to isochrone install command: http://stackoverflow.com/a/24353921/4075339 """ cmd_obj = self.distribution.get_command_obj('isochrones') cmd_obj.force = self.force if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir ...
[ "def", "install_isochrones", "(", "self", ")", ":", "cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "'isochrones'", ")", "cmd_obj", ".", "force", "=", "self", ".", "force", "if", "self", ".", "ugali_dir", ":", "cmd_obj", ".", "uga...
Call to isochrone install command: http://stackoverflow.com/a/24353921/4075339
[ "Call", "to", "isochrone", "install", "command", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "24353921", "/", "4075339" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/setup.py#L250-L258
train
Install isochrone packages
DarkEnergySurvey/ugali
setup.py
install.install_catalogs
def install_catalogs(self): """ Call to catalog install command: http://stackoverflow.com/a/24353921/4075339 """ cmd_obj = self.distribution.get_command_obj('catalogs') cmd_obj.force = self.force if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir self.r...
python
def install_catalogs(self): """ Call to catalog install command: http://stackoverflow.com/a/24353921/4075339 """ cmd_obj = self.distribution.get_command_obj('catalogs') cmd_obj.force = self.force if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir self.r...
[ "def", "install_catalogs", "(", "self", ")", ":", "cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "'catalogs'", ")", "cmd_obj", ".", "force", "=", "self", ".", "force", "if", "self", ".", "ugali_dir", ":", "cmd_obj", ".", "ugali_d...
Call to catalog install command: http://stackoverflow.com/a/24353921/4075339
[ "Call", "to", "catalog", "install", "command", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "24353921", "/", "4075339" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/setup.py#L260-L268
train
Install the nagios catalogs
alphagov/performanceplatform-collector
performanceplatform/utils/http_with_backoff.py
parse_reason
def parse_reason(response, content): """ Google return a JSON document describing the error. We should parse this and extract the error reason. See https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors """ def first_error(data): errors = data['error']['errors'] ...
python
def parse_reason(response, content): """ Google return a JSON document describing the error. We should parse this and extract the error reason. See https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors """ def first_error(data): errors = data['error']['errors'] ...
[ "def", "parse_reason", "(", "response", ",", "content", ")", ":", "def", "first_error", "(", "data", ")", ":", "errors", "=", "data", "[", "'error'", "]", "[", "'errors'", "]", "if", "len", "(", "errors", ")", ">", "1", ":", "# we have more than one erro...
Google return a JSON document describing the error. We should parse this and extract the error reason. See https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors
[ "Google", "return", "a", "JSON", "document", "describing", "the", "error", ".", "We", "should", "parse", "this", "and", "extract", "the", "error", "reason", ".", "See", "https", ":", "//", "developers", ".", "google", ".", "com", "/", "analytics", "/", "...
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/utils/http_with_backoff.py#L29-L46
train
Parse the error reason from the response.
consbio/ncdjango
ncdjango/models.py
Variable.time_stops
def time_stops(self): """ Valid time steps for this service as a list of datetime objects. """ if not self.supports_time: return [] if self.service.calendar == 'standard': units = self.service.time_interval_units interval = self.service.time_interval ...
python
def time_stops(self): """ Valid time steps for this service as a list of datetime objects. """ if not self.supports_time: return [] if self.service.calendar == 'standard': units = self.service.time_interval_units interval = self.service.time_interval ...
[ "def", "time_stops", "(", "self", ")", ":", "if", "not", "self", ".", "supports_time", ":", "return", "[", "]", "if", "self", ".", "service", ".", "calendar", "==", "'standard'", ":", "units", "=", "self", ".", "service", ".", "time_interval_units", "int...
Valid time steps for this service as a list of datetime objects.
[ "Valid", "time", "steps", "for", "this", "service", "as", "a", "list", "of", "datetime", "objects", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/models.py#L98-L155
train
Returns a list of datetime objects that represent the time steps for this service.
DarkEnergySurvey/ugali
ugali/utils/parser.py
Parser._parse_coords
def _parse_coords(self,opts): """ Parse target coordinates in various ways... """ # The coordinates are mutually exclusive, so # shouldn't have to worry about over-writing them. if 'coords' in vars(opts): return radius = vars(opts).get('radius',0) gal = None ...
python
def _parse_coords(self,opts): """ Parse target coordinates in various ways... """ # The coordinates are mutually exclusive, so # shouldn't have to worry about over-writing them. if 'coords' in vars(opts): return radius = vars(opts).get('radius',0) gal = None ...
[ "def", "_parse_coords", "(", "self", ",", "opts", ")", ":", "# The coordinates are mutually exclusive, so", "# shouldn't have to worry about over-writing them.", "if", "'coords'", "in", "vars", "(", "opts", ")", ":", "return", "radius", "=", "vars", "(", "opts", ")", ...
Parse target coordinates in various ways...
[ "Parse", "target", "coordinates", "in", "various", "ways", "..." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parser.py#L87-L112
train
Parse target coordinates in various ways...
DarkEnergySurvey/ugali
ugali/utils/parser.py
Parser.parse_targets
def parse_targets(filename): """ Load a text file with target coordinates. Returns an array of target locations in Galactic coordinates. File description: [NAME] [LON] [LAT] [RADIUS] [COORD] The values of LON and LAT will depend on COORD: COORD = [GAL | ...
python
def parse_targets(filename): """ Load a text file with target coordinates. Returns an array of target locations in Galactic coordinates. File description: [NAME] [LON] [LAT] [RADIUS] [COORD] The values of LON and LAT will depend on COORD: COORD = [GAL | ...
[ "def", "parse_targets", "(", "filename", ")", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "(", "ext", "==", "'.fits'", ")", ":", "import", "fitsio", "data", "=", "fitsio", ".", "read", "(", "filename"...
Load a text file with target coordinates. Returns an array of target locations in Galactic coordinates. File description: [NAME] [LON] [LAT] [RADIUS] [COORD] The values of LON and LAT will depend on COORD: COORD = [GAL | CEL | HPX ], LON = [GLON | RA | NSIDE...
[ "Load", "a", "text", "file", "with", "target", "coordinates", ".", "Returns", "an", "array", "of", "target", "locations", "in", "Galactic", "coordinates", ".", "File", "description", ":", "[", "NAME", "]", "[", "LON", "]", "[", "LAT", "]", "[", "RADIUS",...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/parser.py#L115-L169
train
Load a text file with target coordinates. Returns an array of target locations in Galactic coordinates.
alphagov/performanceplatform-collector
performanceplatform/utils/data_parser.py
DataParser.get_data
def get_data(self, special_fields=None): """ special_fields: "a dict of data specific to collector type that should be added to the data returned by the parser. This will also be and operated on by idMapping, mappings and plugins" This method loops through th...
python
def get_data(self, special_fields=None): """ special_fields: "a dict of data specific to collector type that should be added to the data returned by the parser. This will also be and operated on by idMapping, mappings and plugins" This method loops through th...
[ "def", "get_data", "(", "self", ",", "special_fields", "=", "None", ")", ":", "docs", "=", "build_document_set", "(", "self", ".", "data", ",", "self", ".", "data_type", ",", "self", ".", "mappings", ",", "special_fields", ",", "self", ".", "idMapping", ...
special_fields: "a dict of data specific to collector type that should be added to the data returned by the parser. This will also be and operated on by idMapping, mappings and plugins" This method loops through the data provided to the instance. For each item it wil...
[ "special_fields", ":", "a", "dict", "of", "data", "specific", "to", "collector", "type", "that", "should", "be", "added", "to", "the", "data", "returned", "by", "the", "parser", ".", "This", "will", "also", "be", "and", "operated", "on", "by", "idMapping",...
de68ab4aa500c31e436e050fa1268fa928c522a5
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/utils/data_parser.py#L45-L82
train
This method builds the data for the collector type and returns a dict of data that can be used to parse the data into the instance.
DarkEnergySurvey/ugali
ugali/scratch/simulation/simulate_population.py
meanFracdet
def meanFracdet(map_fracdet, lon_population, lat_population, radius_population): """ Compute the mean fracdet within circular aperture (radius specified in decimal degrees) lon, lat, and radius are taken to be arrays of the same length """ nside_fracdet = healpy.npix2nside(len(map_fracdet)) map...
python
def meanFracdet(map_fracdet, lon_population, lat_population, radius_population): """ Compute the mean fracdet within circular aperture (radius specified in decimal degrees) lon, lat, and radius are taken to be arrays of the same length """ nside_fracdet = healpy.npix2nside(len(map_fracdet)) map...
[ "def", "meanFracdet", "(", "map_fracdet", ",", "lon_population", ",", "lat_population", ",", "radius_population", ")", ":", "nside_fracdet", "=", "healpy", ".", "npix2nside", "(", "len", "(", "map_fracdet", ")", ")", "map_fracdet_zero", "=", "np", ".", "where", ...
Compute the mean fracdet within circular aperture (radius specified in decimal degrees) lon, lat, and radius are taken to be arrays of the same length
[ "Compute", "the", "mean", "fracdet", "within", "circular", "aperture", "(", "radius", "specified", "in", "decimal", "degrees", ")" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/simulate_population.py#L84-L99
train
Compute the mean fracdet within a circular aperture
DarkEnergySurvey/ugali
ugali/scratch/simulation/simulate_population.py
catsimSatellite
def catsimSatellite(config, lon_centroid, lat_centroid, distance, stellar_mass, r_physical, m_maglim_1, m_maglim_2, m_ebv, plot=False, title='test'): """ Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthall...
python
def catsimSatellite(config, lon_centroid, lat_centroid, distance, stellar_mass, r_physical, m_maglim_1, m_maglim_2, m_ebv, plot=False, title='test'): """ Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthall...
[ "def", "catsimSatellite", "(", "config", ",", "lon_centroid", ",", "lat_centroid", ",", "distance", ",", "stellar_mass", ",", "r_physical", ",", "m_maglim_1", ",", "m_maglim_2", ",", "m_ebv", ",", "plot", "=", "False", ",", "title", "=", "'test'", ")", ":", ...
Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r. r_physical is azimuthally averaged half-light radius, kpc
[ "Simulate", "a", "single", "satellite", ".", "This", "is", "currently", "only", "valid", "for", "band_1", "=", "g", "and", "band_2", "=", "r", ".", "r_physical", "is", "azimuthally", "averaged", "half", "-", "light", "radius", "kpc" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/simulate_population.py#L103-L241
train
Simulate a single satellite.
DarkEnergySurvey/ugali
ugali/scratch/simulation/simulate_population.py
catsimPopulation
def catsimPopulation(tag, mc_source_id_start=1, n=5000, n_chunk=100, config='simulate_population.yaml'): """ n = Number of satellites to simulation n_chunk = Number of satellites in a file chunk """ assert mc_source_id_start >= 1, "Starting mc_source_id must be >= 1" assert n % n_chunk == 0, "...
python
def catsimPopulation(tag, mc_source_id_start=1, n=5000, n_chunk=100, config='simulate_population.yaml'): """ n = Number of satellites to simulation n_chunk = Number of satellites in a file chunk """ assert mc_source_id_start >= 1, "Starting mc_source_id must be >= 1" assert n % n_chunk == 0, "...
[ "def", "catsimPopulation", "(", "tag", ",", "mc_source_id_start", "=", "1", ",", "n", "=", "5000", ",", "n_chunk", "=", "100", ",", "config", "=", "'simulate_population.yaml'", ")", ":", "assert", "mc_source_id_start", ">=", "1", ",", "\"Starting mc_source_id mu...
n = Number of satellites to simulation n_chunk = Number of satellites in a file chunk
[ "n", "=", "Number", "of", "satellites", "to", "simulation", "n_chunk", "=", "Number", "of", "satellites", "in", "a", "file", "chunk" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/simulate_population.py#L247-L642
train
Create a population of a single MCMC source.
Genida/django-appsettings
src/appsettings/settings.py
Setting.default_value
def default_value(self): """ Property to return the default value. If the default value is callable and call_default is True, return the result of default(). Else return default. Returns: object: the default value. """ if callable(self.default) and s...
python
def default_value(self): """ Property to return the default value. If the default value is callable and call_default is True, return the result of default(). Else return default. Returns: object: the default value. """ if callable(self.default) and s...
[ "def", "default_value", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "default", ")", "and", "self", ".", "call_default", ":", "return", "self", ".", "default", "(", ")", "return", "self", ".", "default" ]
Property to return the default value. If the default value is callable and call_default is True, return the result of default(). Else return default. Returns: object: the default value.
[ "Property", "to", "return", "the", "default", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L446-L458
train
Property to return the default value.
Genida/django-appsettings
src/appsettings/settings.py
Setting.raw_value
def raw_value(self): """ Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from...
python
def raw_value(self): """ Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from...
[ "def", "raw_value", "(", "self", ")", ":", "if", "self", ".", "parent_setting", "is", "not", "None", ":", "return", "self", ".", "parent_setting", ".", "raw_value", "[", "self", ".", "full_name", "]", "else", ":", "return", "getattr", "(", "settings", ",...
Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from nested setting.
[ "Property", "to", "return", "the", "variable", "defined", "in", "django", ".", "conf", ".", "settings", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L461-L475
train
Property to return the value defined in django. conf. settings.
Genida/django-appsettings
src/appsettings/settings.py
Setting.get_value
def get_value(self): """ Return the transformed raw or default value. If the variable is missing from the project settings, and the setting is required, re-raise an AttributeError. If it is not required, return the (optionally transformed) default value. Returns: ...
python
def get_value(self): """ Return the transformed raw or default value. If the variable is missing from the project settings, and the setting is required, re-raise an AttributeError. If it is not required, return the (optionally transformed) default value. Returns: ...
[ "def", "get_value", "(", "self", ")", ":", "try", ":", "value", "=", "self", ".", "raw_value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "err", ":", "self", ".", "_reraise_if_required", "(", "err", ")", "default_value", "=", "self", "....
Return the transformed raw or default value. If the variable is missing from the project settings, and the setting is required, re-raise an AttributeError. If it is not required, return the (optionally transformed) default value. Returns: object: the transformed raw value.
[ "Return", "the", "transformed", "raw", "or", "default", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L489-L509
train
Returns the transformed raw or default value.
Genida/django-appsettings
src/appsettings/settings.py
Setting.run_validators
def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(value) except ValidationError as error: errors.extend(error.messages) if errors: ...
python
def run_validators(self, value): """Run the validators on the setting value.""" errors = [] for validator in self.validators: try: validator(value) except ValidationError as error: errors.extend(error.messages) if errors: ...
[ "def", "run_validators", "(", "self", ",", "value", ")", ":", "errors", "=", "[", "]", "for", "validator", "in", "self", ".", "validators", ":", "try", ":", "validator", "(", "value", ")", "except", "ValidationError", "as", "error", ":", "errors", ".", ...
Run the validators on the setting value.
[ "Run", "the", "validators", "on", "the", "setting", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L522-L531
train
Run the validators on the setting value.
Genida/django-appsettings
src/appsettings/settings.py
Setting.check
def check(self): """ Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: if the raw value is invalid. """ try: value = self.raw_value except (AttributeError...
python
def check(self): """ Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: if the raw value is invalid. """ try: value = self.raw_value except (AttributeError...
[ "def", "check", "(", "self", ")", ":", "try", ":", "value", "=", "self", ".", "raw_value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "err", ":", "self", ".", "_reraise_if_required", "(", "err", ")", "else", ":", "if", "self", ".", ...
Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: if the raw value is invalid.
[ "Run", "the", "setting", "checker", "against", "the", "setting", "raw", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L533-L552
train
Run the checker against the raw value.
Genida/django-appsettings
src/appsettings/settings.py
ObjectSetting.transform
def transform(self, path): """ Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ...
python
def transform(self, path): """ Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ...
[ "def", "transform", "(", "self", ",", "path", ")", ":", "if", "path", "is", "None", "or", "not", "path", ":", "return", "None", "obj_parent_modules", "=", "path", ".", "split", "(", "\".\"", ")", "objects", "=", "[", "obj_parent_modules", ".", "pop", "...
Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ``importlib.import_module`` and each object is ...
[ "Transform", "a", "path", "into", "an", "actual", "Python", "object", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L1085-L1120
train
Transform a path into an actual Python object.
Genida/django-appsettings
src/appsettings/settings.py
NestedSetting.get_value
def get_value(self): """ Return dictionary with values of subsettings. Returns: dict: values of subsettings. """ try: self.raw_value except (AttributeError, KeyError) as err: self._reraise_if_required(err) default_value = s...
python
def get_value(self): """ Return dictionary with values of subsettings. Returns: dict: values of subsettings. """ try: self.raw_value except (AttributeError, KeyError) as err: self._reraise_if_required(err) default_value = s...
[ "def", "get_value", "(", "self", ")", ":", "try", ":", "self", ".", "raw_value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "err", ":", "self", ".", "_reraise_if_required", "(", "err", ")", "default_value", "=", "self", ".", "default_valu...
Return dictionary with values of subsettings. Returns: dict: values of subsettings.
[ "Return", "dictionary", "with", "values", "of", "subsettings", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L1154-L1174
train
Get the value of the attribute in the current object.
Genida/django-appsettings
src/appsettings/settings.py
NestedSetting.check
def check(self): """ Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: (or other Exception) if the raw value is invalid. """ super(NestedSetting, self).check() errors...
python
def check(self): """ Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: (or other Exception) if the raw value is invalid. """ super(NestedSetting, self).check() errors...
[ "def", "check", "(", "self", ")", ":", "super", "(", "NestedSetting", ",", "self", ")", ".", "check", "(", ")", "errors", "=", "[", "]", "for", "subsetting", "in", "self", ".", "settings", ".", "values", "(", ")", ":", "try", ":", "subsetting", "."...
Run the setting checker against the setting raw value. Raises: AttributeError: if the setting is missing and required. ValueError: (or other Exception) if the raw value is invalid.
[ "Run", "the", "setting", "checker", "against", "the", "setting", "raw", "value", "." ]
f98867d133558af7dc067f12b44fc1ee4edd4239
https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/settings.py#L1176-L1192
train
Run the setting checker against the raw value.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
sum_mags
def sum_mags(mags, weights=None): """ Sum an array of magnitudes in flux space. Parameters: ----------- mags : array of magnitudes weights : array of weights for each magnitude (i.e. from a pdf) Returns: -------- sum_mag : the summed magnitude of all the stars """ fl...
python
def sum_mags(mags, weights=None): """ Sum an array of magnitudes in flux space. Parameters: ----------- mags : array of magnitudes weights : array of weights for each magnitude (i.e. from a pdf) Returns: -------- sum_mag : the summed magnitude of all the stars """ fl...
[ "def", "sum_mags", "(", "mags", ",", "weights", "=", "None", ")", ":", "flux", "=", "10", "**", "(", "-", "np", ".", "asarray", "(", "mags", ")", "/", "2.5", ")", "if", "weights", "is", "None", ":", "return", "-", "2.5", "*", "np", ".", "log10"...
Sum an array of magnitudes in flux space. Parameters: ----------- mags : array of magnitudes weights : array of weights for each magnitude (i.e. from a pdf) Returns: -------- sum_mag : the summed magnitude of all the stars
[ "Sum", "an", "array", "of", "magnitudes", "in", "flux", "space", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L57-L74
train
Sum an array of magnitudes in flux space.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
absolute_magnitude
def absolute_magnitude(distance_modulus,g,r,prob=None): """ Calculate the absolute magnitude from a set of bands """ V = g - 0.487*(g - r) - 0.0249 flux = np.sum(10**(-(V-distance_modulus)/2.5)) Mv = -2.5*np.log10(flux) return Mv
python
def absolute_magnitude(distance_modulus,g,r,prob=None): """ Calculate the absolute magnitude from a set of bands """ V = g - 0.487*(g - r) - 0.0249 flux = np.sum(10**(-(V-distance_modulus)/2.5)) Mv = -2.5*np.log10(flux) return Mv
[ "def", "absolute_magnitude", "(", "distance_modulus", ",", "g", ",", "r", ",", "prob", "=", "None", ")", ":", "V", "=", "g", "-", "0.487", "*", "(", "g", "-", "r", ")", "-", "0.0249", "flux", "=", "np", ".", "sum", "(", "10", "**", "(", "-", ...
Calculate the absolute magnitude from a set of bands
[ "Calculate", "the", "absolute", "magnitude", "from", "a", "set", "of", "bands" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L1208-L1214
train
Calculate the absolute magnitude of a single node in a set of bands.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.sample
def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False): """Sample the isochrone in steps of mass interpolating between the originally defined isochrone points. Parameters: ----------- mode : mass_steps : mass_min : Minimum mass [Msu...
python
def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False): """Sample the isochrone in steps of mass interpolating between the originally defined isochrone points. Parameters: ----------- mode : mass_steps : mass_min : Minimum mass [Msu...
[ "def", "sample", "(", "self", ",", "mode", "=", "'data'", ",", "mass_steps", "=", "1000", ",", "mass_min", "=", "0.1", ",", "full_data_range", "=", "False", ")", ":", "if", "full_data_range", ":", "# ADW: Might be depricated 02/10/2015", "# Generate points over fu...
Sample the isochrone in steps of mass interpolating between the originally defined isochrone points. Parameters: ----------- mode : mass_steps : mass_min : Minimum mass [Msun] full_data_range : Returns: -------- mass_init : Init...
[ "Sample", "the", "isochrone", "in", "steps", "of", "mass", "interpolating", "between", "the", "originally", "defined", "isochrone", "points", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L160-L263
train
Sample the isochrone in steps of mass interpolating between the isochrone points.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.stellar_mass
def stellar_mass(self, mass_min=0.1, steps=10000): """ Compute the stellar mass (Msun; average per star). PDF comes from IMF, but weight by actual stellar mass. Parameters: ----------- mass_min : Minimum mass to integrate the IMF steps : Number of steps to sam...
python
def stellar_mass(self, mass_min=0.1, steps=10000): """ Compute the stellar mass (Msun; average per star). PDF comes from IMF, but weight by actual stellar mass. Parameters: ----------- mass_min : Minimum mass to integrate the IMF steps : Number of steps to sam...
[ "def", "stellar_mass", "(", "self", ",", "mass_min", "=", "0.1", ",", "steps", "=", "10000", ")", ":", "mass_max", "=", "self", ".", "mass_init_upper_bound", "d_log_mass", "=", "(", "np", ".", "log10", "(", "mass_max", ")", "-", "np", ".", "log10", "("...
Compute the stellar mass (Msun; average per star). PDF comes from IMF, but weight by actual stellar mass. Parameters: ----------- mass_min : Minimum mass to integrate the IMF steps : Number of steps to sample the isochrone Returns: -------- mass :...
[ "Compute", "the", "stellar", "mass", "(", "Msun", ";", "average", "per", "star", ")", ".", "PDF", "comes", "from", "IMF", "but", "weight", "by", "actual", "stellar", "mass", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L265-L292
train
Compute the stellar mass of the isochrone.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.stellar_luminosity
def stellar_luminosity(self, steps=10000): """ Compute the stellar luminosity (Lsun; average per star). PDF comes from IMF. The range of integration only covers the input isochrone data (no extrapolation used), but this seems like a sub-percent effect if the isochrone goes to 0....
python
def stellar_luminosity(self, steps=10000): """ Compute the stellar luminosity (Lsun; average per star). PDF comes from IMF. The range of integration only covers the input isochrone data (no extrapolation used), but this seems like a sub-percent effect if the isochrone goes to 0....
[ "def", "stellar_luminosity", "(", "self", ",", "steps", "=", "10000", ")", ":", "mass_min", "=", "np", ".", "min", "(", "self", ".", "mass_init", ")", "mass_max", "=", "self", ".", "mass_init_upper_bound", "d_log_mass", "=", "(", "np", ".", "log10", "(",...
Compute the stellar luminosity (Lsun; average per star). PDF comes from IMF. The range of integration only covers the input isochrone data (no extrapolation used), but this seems like a sub-percent effect if the isochrone goes to 0.15 Msun for the old and metal-poor stellar populations ...
[ "Compute", "the", "stellar", "luminosity", "(", "Lsun", ";", "average", "per", "star", ")", ".", "PDF", "comes", "from", "IMF", ".", "The", "range", "of", "integration", "only", "covers", "the", "input", "isochrone", "data", "(", "no", "extrapolation", "us...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L294-L323
train
Compute the stellar luminosity of the isochrone.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.stellar_luminosity2
def stellar_luminosity2(self, steps=10000): """ DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but...
python
def stellar_luminosity2(self, steps=10000): """ DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but...
[ "def", "stellar_luminosity2", "(", "self", ",", "steps", "=", "10000", ")", ":", "msg", "=", "\"'%s.stellar_luminosity2': ADW 2017-09-20\"", "%", "self", ".", "__class__", ".", "__name__", "DeprecationWarning", "(", "msg", ")", "mass_init", ",", "mass_pdf", ",", ...
DEPRECATED: ADW 2017-09-20 Compute the stellar luminosity (L_Sol; average per star). Uses "sample" to generate mass sample and pdf. The range of integration only covers the input isochrone data (no extrapolation used), but this seems like a sub-percent effect if the isochrone g...
[ "DEPRECATED", ":", "ADW", "2017", "-", "09", "-", "20" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L325-L344
train
Compute the stellar luminosity of the current species.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.absolute_magnitude
def absolute_magnitude(self, richness=1, steps=1e4): """ Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: -...
python
def absolute_magnitude(self, richness=1, steps=1e4): """ Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: -...
[ "def", "absolute_magnitude", "(", "self", ",", "richness", "=", "1", ",", "steps", "=", "1e4", ")", ":", "# Using the SDSS g,r -> V from Jester 2005 [astro-ph/0506022]", "# for stars with R-I < 1.15", "# V = g_sdss - 0.59*(g_sdss - r_sdss) - 0.01", "# Create a copy of the isochrone...
Calculate the absolute visual magnitude (Mv) from the richness by transforming the isochrone in the SDSS system and using the g,r -> V transform equations from Jester 2005 [astro-ph/0506022]. Parameters: ----------- richness : isochrone normalization parameter s...
[ "Calculate", "the", "absolute", "visual", "magnitude", "(", "Mv", ")", "from", "the", "richness", "by", "transforming", "the", "isochrone", "in", "the", "SDSS", "system", "and", "using", "the", "g", "r", "-", ">", "V", "transform", "equations", "from", "Je...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L350-L381
train
Calculate the absolute visual magnitude from the isochrone in the SDSS system and using the Jester 2005
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.absolute_magnitude_martin
def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None): """ Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits ...
python
def absolute_magnitude_martin(self, richness=1, steps=1e4, n_trials=1000, mag_bright=None, mag_faint=23., alpha=0.32, seed=None): """ Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits ...
[ "def", "absolute_magnitude_martin", "(", "self", ",", "richness", "=", "1", ",", "steps", "=", "1e4", ",", "n_trials", "=", "1000", ",", "mag_bright", "=", "None", ",", "mag_faint", "=", "23.", ",", "alpha", "=", "0.32", ",", "seed", "=", "None", ")", ...
Calculate the absolute magnitude (Mv) of the isochrone using the prescription of Martin et al. 2008. ADW: Seems like the faint and bright limits should depend on the survey maglim? Parameters: ----------- richness : Isochrone nomalization factor steps : N...
[ "Calculate", "the", "absolute", "magnitude", "(", "Mv", ")", "of", "the", "isochrone", "using", "the", "prescription", "of", "Martin", "et", "al", ".", "2008", ".", "ADW", ":", "Seems", "like", "the", "faint", "and", "bright", "limits", "should", "depend",...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L389-L444
train
This function calculates the absolute magnitude of the isochrone using the Martin et al. 2008.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.simulate
def simulate(self, stellar_mass, distance_modulus=None, **kwargs): """ Simulate a set of stellar magnitudes (no uncertainty) for a satellite of a given stellar mass and distance. Parameters: ----------- stellar_mass : the total stellar mass of the system (Msun) d...
python
def simulate(self, stellar_mass, distance_modulus=None, **kwargs): """ Simulate a set of stellar magnitudes (no uncertainty) for a satellite of a given stellar mass and distance. Parameters: ----------- stellar_mass : the total stellar mass of the system (Msun) d...
[ "def", "simulate", "(", "self", ",", "stellar_mass", ",", "distance_modulus", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "distance_modulus", "is", "None", ":", "distance_modulus", "=", "self", ".", "distance_modulus", "# Total number of stars in system"...
Simulate a set of stellar magnitudes (no uncertainty) for a satellite of a given stellar mass and distance. Parameters: ----------- stellar_mass : the total stellar mass of the system (Msun) distance_modulus : distance modulus of the system (if None takes from isochrone) ...
[ "Simulate", "a", "set", "of", "stellar", "magnitudes", "(", "no", "uncertainty", ")", "for", "a", "satellite", "of", "a", "given", "stellar", "mass", "and", "distance", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L446-L468
train
Simulate a set of stellar magnitudes for a given satellite and distance modulus.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.observableFractionCMDX
def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the sam...
python
def observableFractionCMDX(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the sam...
[ "def", "observableFractionCMDX", "(", "self", ",", "mask", ",", "distance_modulus", ",", "mass_min", "=", "0.1", ")", ":", "mass_init_array", ",", "mass_pdf_array", ",", "mass_act_array", ",", "mag_1_array", ",", "mag_2_array", "=", "self", ".", "sample", "(", ...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable space. However, for technical reasons it ...
[ "Compute", "observable", "fraction", "of", "stars", "with", "masses", "greater", "than", "mass_min", "in", "each", "pixel", "in", "the", "interior", "region", "of", "the", "mask", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L470-L503
train
Compute observable fraction of stars with mass greater than mass_min in each pixel in the interior region of the mask.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.observableFractionCMD
def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same...
python
def observableFractionCMD(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same...
[ "def", "observableFractionCMD", "(", "self", ",", "mask", ",", "distance_modulus", ",", "mass_min", "=", "0.1", ")", ":", "if", "distance_modulus", "is", "None", ":", "distance_modulus", "=", "self", ".", "distance_modulus", "mass_init", ",", "mass_pdf", ",", ...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable space. However, for technical reasons it ...
[ "Compute", "observable", "fraction", "of", "stars", "with", "masses", "greater", "than", "mass_min", "in", "each", "pixel", "in", "the", "interior", "region", "of", "the", "mask", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L505-L541
train
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.observableFractionCDF
def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile...
python
def observableFractionCDF(self, mask, distance_modulus, mass_min=0.1): """ Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile...
[ "def", "observableFractionCDF", "(", "self", ",", "mask", ",", "distance_modulus", ",", "mass_min", "=", "0.1", ")", ":", "method", "=", "'step'", "mass_init", ",", "mass_pdf", ",", "mass_act", ",", "mag_1", ",", "mag_2", "=", "self", ".", "sample", "(", ...
Compute observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask. Incorporates simplistic photometric errors. ADW: Careful, this function is fragile! The selection here should be the same as mask.restrictCatalogToObservable sp...
[ "Compute", "observable", "fraction", "of", "stars", "with", "masses", "greater", "than", "mass_min", "in", "each", "pixel", "in", "the", "interior", "region", "of", "the", "mask", ".", "Incorporates", "simplistic", "photometric", "errors", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L544-L595
train
Compute the observable fraction of stars with masses greater than mass_min in each pixel in the interior region of the mask.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.histogram2d
def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000): """ Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : num...
python
def histogram2d(self,distance_modulus=None,delta_mag=0.03,steps=10000): """ Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : num...
[ "def", "histogram2d", "(", "self", ",", "distance_modulus", "=", "None", ",", "delta_mag", "=", "0.03", ",", "steps", "=", "10000", ")", ":", "if", "distance_modulus", "is", "not", "None", ":", "self", ".", "distance_modulus", "=", "distance_modulus", "# Iso...
Return a 2D histogram the isochrone in mag-mag space. Parameters: ----------- distance_modulus : distance modulus to calculate histogram at delta_mag : magnitude bin size mass_steps : number of steps to sample isochrone at Returns: -------- bins_mag_1 : ...
[ "Return", "a", "2D", "histogram", "the", "isochrone", "in", "mag", "-", "mag", "space", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L746-L786
train
Return a 2D histogram of the isochrone in mag - mag space.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.pdf_mmd
def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000): """ Ok, now here comes the beauty of having the signal MMD. """ logger.info('Running MMD pdf') roi = mask.roi mmd = self.signalMMD(mask,distance_modulus,delta_mag=delta_mag,ma...
python
def pdf_mmd(self, lon, lat, mag_1, mag_2, distance_modulus, mask, delta_mag=0.03, steps=1000): """ Ok, now here comes the beauty of having the signal MMD. """ logger.info('Running MMD pdf') roi = mask.roi mmd = self.signalMMD(mask,distance_modulus,delta_mag=delta_mag,ma...
[ "def", "pdf_mmd", "(", "self", ",", "lon", ",", "lat", ",", "mag_1", ",", "mag_2", ",", "distance_modulus", ",", "mask", ",", "delta_mag", "=", "0.03", ",", "steps", "=", "1000", ")", ":", "logger", ".", "info", "(", "'Running MMD pdf'", ")", "roi", ...
Ok, now here comes the beauty of having the signal MMD.
[ "Ok", "now", "here", "comes", "the", "beauty", "of", "having", "the", "signal", "MMD", "." ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L788-L817
train
This function is used to compute the MMD of a single object.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.pdf
def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2, distance_modulus=None, delta_mag=0.03, steps=10000): """ Compute isochrone probability for each catalog object. ADW: This is a memory intensive function, so try as much as possible to keep array types at `float32` or smalle...
python
def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2, distance_modulus=None, delta_mag=0.03, steps=10000): """ Compute isochrone probability for each catalog object. ADW: This is a memory intensive function, so try as much as possible to keep array types at `float32` or smalle...
[ "def", "pdf", "(", "self", ",", "mag_1", ",", "mag_2", ",", "mag_err_1", ",", "mag_err_2", ",", "distance_modulus", "=", "None", ",", "delta_mag", "=", "0.03", ",", "steps", "=", "10000", ")", ":", "nsigma", "=", "5.0", "#pad = 1. # mag", "if", "distance...
Compute isochrone probability for each catalog object. ADW: This is a memory intensive function, so try as much as possible to keep array types at `float32` or smaller (maybe using add.at would be good?) ADW: Still a little speed to be gained here (broadcasting) ADW: Units? [ma...
[ "Compute", "isochrone", "probability", "for", "each", "catalog", "object", ".", "ADW", ":", "This", "is", "a", "memory", "intensive", "function", "so", "try", "as", "much", "as", "possible", "to", "keep", "array", "types", "at", "float32", "or", "smaller", ...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L821-L926
train
Compute the pdf of the given magnitude and error of the given stars.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.raw_separation
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
python
def raw_separation(self,mag_1,mag_2,steps=10000): """ Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : T...
[ "def", "raw_separation", "(", "self", ",", "mag_1", ",", "mag_2", ",", "steps", "=", "10000", ")", ":", "# http://stackoverflow.com/q/12653120/", "mag_1", "=", "np", ".", "array", "(", "mag_1", ",", "copy", "=", "False", ",", "ndmin", "=", "1", ")", "mag...
Calculate the separation in magnitude-magnitude space between points and isochrone. Uses a dense sampling of the isochrone and calculates the metric distance from any isochrone sample point. Parameters: ----------- mag_1 : The magnitude of the test points in the first band mag_2 : The m...
[ "Calculate", "the", "separation", "in", "magnitude", "-", "magnitude", "space", "between", "points", "and", "isochrone", ".", "Uses", "a", "dense", "sampling", "of", "the", "isochrone", "and", "calculates", "the", "metric", "distance", "from", "any", "isochrone"...
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L929-L960
train
Calculates the raw separation between two test points.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
IsochroneModel.separation
def separation(self, mag_1, mag_2): """ Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the f...
python
def separation(self, mag_1, mag_2): """ Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the f...
[ "def", "separation", "(", "self", ",", "mag_1", ",", "mag_2", ")", ":", "iso_mag_1", "=", "self", ".", "mag_1", "+", "self", ".", "distance_modulus", "iso_mag_2", "=", "self", ".", "mag_2", "+", "self", ".", "distance_modulus", "def", "interp_iso", "(", ...
Calculate the separation between a specific point and the isochrone in magnitude-magnitude space. Uses an interpolation ADW: Could speed this up... Parameters: ----------- mag_1 : The magnitude of the test points in the first band mag_2 : The magnitude of the test point...
[ "Calculate", "the", "separation", "between", "a", "specific", "point", "and", "the", "isochrone", "in", "magnitude", "-", "magnitude", "space", ".", "Uses", "an", "interpolation" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L963-L1017
train
Calculates the separation between two test points in magnitude - magnitude space.
DarkEnergySurvey/ugali
ugali/isochrone/model.py
Isochrone.download
def download(self,age=None,metallicity=None,outdir=None,force=False): """ Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd """ try: from urllib.error import URLError except ImportError: from urllib2 imp...
python
def download(self,age=None,metallicity=None,outdir=None,force=False): """ Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd """ try: from urllib.error import URLError except ImportError: from urllib2 imp...
[ "def", "download", "(", "self", ",", "age", "=", "None", ",", "metallicity", "=", "None", ",", "outdir", "=", "None", ",", "force", "=", "False", ")", ":", "try", ":", "from", "urllib", ".", "error", "import", "URLError", "except", "ImportError", ":", ...
Check valid parameter range and download isochrones from: http://stev.oapd.inaf.it/cgi-bin/cmd
[ "Check", "valid", "parameter", "range", "and", "download", "isochrones", "from", ":", "http", ":", "//", "stev", ".", "oapd", ".", "inaf", ".", "it", "/", "cgi", "-", "bin", "/", "cmd" ]
21e890b4117fc810afb6fb058e8055d564f03382
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/model.py#L1158-L1203
train
Download isochrones from the server.
akx/lepo
lepo/router.py
Router.get_urls
def get_urls( self, root_view_name=None, optional_trailing_slash=False, decorate=(), name_template='{name}', ): """ Get the router's URLs, ready to be installed in `urlpatterns` (directly or via `include`). :param root_view_name: The optional url name...
python
def get_urls( self, root_view_name=None, optional_trailing_slash=False, decorate=(), name_template='{name}', ): """ Get the router's URLs, ready to be installed in `urlpatterns` (directly or via `include`). :param root_view_name: The optional url name...
[ "def", "get_urls", "(", "self", ",", "root_view_name", "=", "None", ",", "optional_trailing_slash", "=", "False", ",", "decorate", "=", "(", ")", ",", "name_template", "=", "'{name}'", ",", ")", ":", "if", "isinstance", "(", "decorate", ",", "Iterable", ")...
Get the router's URLs, ready to be installed in `urlpatterns` (directly or via `include`). :param root_view_name: The optional url name for an API root view. This may be useful for projects that do not explicitly know where the router is mounted; th...
[ "Get", "the", "router", "s", "URLs", "ready", "to", "be", "installed", "in", "urlpatterns", "(", "directly", "or", "via", "include", ")", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/router.py#L54-L103
train
Get the router s URLs ready to be installed in urlpatterns.
akx/lepo
lepo/router.py
Router.get_handler
def get_handler(self, operation_id): """ Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. ...
python
def get_handler(self, operation_id): """ Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. ...
[ "def", "get_handler", "(", "self", ",", "operation_id", ")", ":", "handler", "=", "(", "self", ".", "handlers", ".", "get", "(", "operation_id", ")", "or", "self", ".", "handlers", ".", "get", "(", "snake_case", "(", "operation_id", ")", ")", ")", "if"...
Get the handler function for a given operation. To remain Pythonic, both the original and the snake_cased version of the operation ID are supported. This could be overridden in a subclass. :param operation_id: Operation ID. :return: Handler function :rtype: function
[ "Get", "the", "handler", "function", "for", "a", "given", "operation", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/router.py#L105-L126
train
Get the handler function for a given operation ID.
akx/lepo
lepo/router.py
Router.add_handlers
def add_handlers(self, namespace): """ Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-pref...
python
def add_handlers(self, namespace): """ Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-pref...
[ "def", "add_handlers", "(", "self", ",", "namespace", ")", ":", "if", "isinstance", "(", "namespace", ",", "str", ")", ":", "namespace", "=", "import_module", "(", "namespace", ")", "if", "isinstance", "(", "namespace", ",", "dict", ")", ":", "namespace", ...
Add handler functions from the given `namespace`, for instance a module. The namespace may be a string, in which case it is expected to be a name of a module. It may also be a dictionary mapping names to functions. Only non-underscore-prefixed functions and methods are imported. :para...
[ "Add", "handler", "functions", "from", "the", "given", "namespace", "for", "instance", "a", "module", "." ]
34cfb24a40f18ea40f672c1ea9a0734ee1816b7d
https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/router.py#L128-L152
train
Adds handler functions from the given namespace for instance a module.
consbio/ncdjango
ncdjango/geoprocessing/tasks/raster.py
SingleArrayExpressionBase.get_context
def get_context(self, arr, expr, context): """ Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context. """ expression_names = [x for x in self.get_expr...
python
def get_context(self, arr, expr, context): """ Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context. """ expression_names = [x for x in self.get_expr...
[ "def", "get_context", "(", "self", ",", "arr", ",", "expr", ",", "context", ")", ":", "expression_names", "=", "[", "x", "for", "x", "in", "self", ".", "get_expression_names", "(", "expr", ")", "if", "x", "not", "in", "set", "(", "context", ".", "key...
Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context.
[ "Returns", "a", "context", "dictionary", "for", "use", "in", "evaluating", "the", "expression", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/tasks/raster.py#L82-L96
train
Returns a dictionary that can be used in evaluating the expression.
consbio/ncdjango
ncdjango/geoprocessing/tasks/raster.py
MaskByExpression.execute
def execute(self, array_in, expression, **kwargs): """Creates and returns a masked view of the input array.""" context = self.get_context(array_in, expression, kwargs) context.update(kwargs) return ma.masked_where(self.evaluate_expression(expression, context), array_in)
python
def execute(self, array_in, expression, **kwargs): """Creates and returns a masked view of the input array.""" context = self.get_context(array_in, expression, kwargs) context.update(kwargs) return ma.masked_where(self.evaluate_expression(expression, context), array_in)
[ "def", "execute", "(", "self", ",", "array_in", ",", "expression", ",", "*", "*", "kwargs", ")", ":", "context", "=", "self", ".", "get_context", "(", "array_in", ",", "expression", ",", "kwargs", ")", "context", ".", "update", "(", "kwargs", ")", "ret...
Creates and returns a masked view of the input array.
[ "Creates", "and", "returns", "a", "masked", "view", "of", "the", "input", "array", "." ]
f807bfd1e4083ab29fbc3c4d4418be108383a710
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/tasks/raster.py#L104-L109
train
Creates and returns a masked view of the input array.
juju/theblues
theblues/errors.py
timeout_error
def timeout_error(url, timeout): """Raise a server error indicating a request timeout to the given URL.""" msg = 'Request timed out: {} timeout: {}s'.format(url, timeout) log.warning(msg) return ServerError(msg)
python
def timeout_error(url, timeout): """Raise a server error indicating a request timeout to the given URL.""" msg = 'Request timed out: {} timeout: {}s'.format(url, timeout) log.warning(msg) return ServerError(msg)
[ "def", "timeout_error", "(", "url", ",", "timeout", ")", ":", "msg", "=", "'Request timed out: {} timeout: {}s'", ".", "format", "(", "url", ",", "timeout", ")", "log", ".", "warning", "(", "msg", ")", "return", "ServerError", "(", "msg", ")" ]
Raise a server error indicating a request timeout to the given URL.
[ "Raise", "a", "server", "error", "indicating", "a", "request", "timeout", "to", "the", "given", "URL", "." ]
f4431f29e43d04fc32f38f4f86cea45cd4e6ae98
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/errors.py#L19-L23
train
Raise a server error indicating a request timed out.