hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35673d22447611ef4fab0da1732296c4802e0136 | bohaohuang/ersa | nn/nn_utils.py | [
"MIT"
] | Python | iou_metric | <not_specific> | def iou_metric(truth, pred, truth_val=1, divide_flag=False):
"""
calculate iou with given truth and prediction map
:param truth: truth image
:param pred: prediction map
:param truth_val: truth value, default to 1
:param divide_flag: if False, numerator and denominator will be returned separately... |
calculate iou with given truth and prediction map
:param truth: truth image
:param pred: prediction map
:param truth_val: truth value, default to 1
:param divide_flag: if False, numerator and denominator will be returned separately
:return: iou scalar value or numerator and denominator list
... | calculate iou with given truth and prediction map | [
"calculate",
"iou",
"with",
"given",
"truth",
"and",
"prediction",
"map"
] | def iou_metric(truth, pred, truth_val=1, divide_flag=False):
truth = truth / truth_val
pred = pred / truth_val
truth = truth.flatten()
pred = pred.flatten()
intersect = truth*pred
if divide_flag:
return np.sum(intersect == 1), np.sum(truth+pred >= 1)
else:
return np.sum(inter... | [
"def",
"iou_metric",
"(",
"truth",
",",
"pred",
",",
"truth_val",
"=",
"1",
",",
"divide_flag",
"=",
"False",
")",
":",
"truth",
"=",
"truth",
"/",
"truth_val",
"pred",
"=",
"pred",
"/",
"truth_val",
"truth",
"=",
"truth",
".",
"flatten",
"(",
")",
"... | calculate iou with given truth and prediction map | [
"calculate",
"iou",
"with",
"given",
"truth",
"and",
"prediction",
"map"
] | [
"\"\"\"\n calculate iou with given truth and prediction map\n :param truth: truth image\n :param pred: prediction map\n :param truth_val: truth value, default to 1\n :param divide_flag: if False, numerator and denominator will be returned separately\n :return: iou scalar value or numerator and den... | [
{
"param": "truth",
"type": null
},
{
"param": "pred",
"type": null
},
{
"param": "truth_val",
"type": null
},
{
"param": "divide_flag",
"type": null
}
] | {
"returns": [
{
"docstring": "iou scalar value or numerator and denominator list",
"docstring_tokens": [
"iou",
"scalar",
"value",
"or",
"numerator",
"and",
"denominator",
"list"
],
"type": null
}
],
"raises": [],
"... |
35673d22447611ef4fab0da1732296c4802e0136 | bohaohuang/ersa | nn/nn_utils.py | [
"MIT"
] | Python | read_iou_from_file | <not_specific> | def read_iou_from_file(result_record):
"""
read iou records from a file, ious will be stored based on each file and each filed (city_name)
:param result_record: record read from a result file
:return: tile based iou, field based iou and overall iou
"""
tile_dict = {}
field_list = []
fiel... |
read iou records from a file, ious will be stored based on each file and each filed (city_name)
:param result_record: record read from a result file
:return: tile based iou, field based iou and overall iou
| read iou records from a file, ious will be stored based on each file and each filed (city_name) | [
"read",
"iou",
"records",
"from",
"a",
"file",
"ious",
"will",
"be",
"stored",
"based",
"on",
"each",
"file",
"and",
"each",
"filed",
"(",
"city_name",
")"
] | def read_iou_from_file(result_record):
tile_dict = {}
field_list = []
field_dict = {}
overall = np.zeros(2)
for cnt, line in enumerate(result_record[:-1]):
tile_name = line.split(' ')[0]
a, b = [float(item) for item in line.split('(')[1].strip().strip(')').split(',')]
tile_di... | [
"def",
"read_iou_from_file",
"(",
"result_record",
")",
":",
"tile_dict",
"=",
"{",
"}",
"field_list",
"=",
"[",
"]",
"field_dict",
"=",
"{",
"}",
"overall",
"=",
"np",
".",
"zeros",
"(",
"2",
")",
"for",
"cnt",
",",
"line",
"in",
"enumerate",
"(",
"... | read iou records from a file, ious will be stored based on each file and each filed (city_name) | [
"read",
"iou",
"records",
"from",
"a",
"file",
"ious",
"will",
"be",
"stored",
"based",
"on",
"each",
"file",
"and",
"each",
"filed",
"(",
"city_name",
")"
] | [
"\"\"\"\n read iou records from a file, ious will be stored based on each file and each filed (city_name)\n :param result_record: record read from a result file\n :return: tile based iou, field based iou and overall iou\n \"\"\""
] | [
{
"param": "result_record",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "result_record",
"type": null,
"docstring": "record read from a result file",
"docstring_tokens": [
"record"... |
35673d22447611ef4fab0da1732296c4802e0136 | bohaohuang/ersa | nn/nn_utils.py | [
"MIT"
] | Python | image_summary | <not_specific> | def image_summary(image, truth, prediction, img_mean=np.array((0, 0, 0), dtype=np.float32), label_num=2):
"""
Make a image summary where the format is image|truth|pred
:param image: input rgb image
:param truth: ground truth
:param prediction: network prediction
:param img_mean: image mean, need... |
Make a image summary where the format is image|truth|pred
:param image: input rgb image
:param truth: ground truth
:param prediction: network prediction
:param img_mean: image mean, need to add back here for visualization
:param label_num: #distinct classes in ground truth
:return:
| Make a image summary where the format is image|truth|pred | [
"Make",
"a",
"image",
"summary",
"where",
"the",
"format",
"is",
"image|truth|pred"
] | def image_summary(image, truth, prediction, img_mean=np.array((0, 0, 0), dtype=np.float32), label_num=2):
truth_img = decode_labels(truth, label_num)
prediction = pad_prediction(image, prediction)
pred_labels = get_pred_labels(prediction)
pred_img = decode_labels(pred_labels, label_num)
_, h, w, _ =... | [
"def",
"image_summary",
"(",
"image",
",",
"truth",
",",
"prediction",
",",
"img_mean",
"=",
"np",
".",
"array",
"(",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
",",
"label_num",
"=",
"2",
")",
":",
"truth_im... | Make a image summary where the format is image|truth|pred | [
"Make",
"a",
"image",
"summary",
"where",
"the",
"format",
"is",
"image|truth|pred"
] | [
"\"\"\"\n Make a image summary where the format is image|truth|pred\n :param image: input rgb image\n :param truth: ground truth\n :param prediction: network prediction\n :param img_mean: image mean, need to add back here for visualization\n :param label_num: #distinct classes in ground truth\n ... | [
{
"param": "image",
"type": null
},
{
"param": "truth",
"type": null
},
{
"param": "prediction",
"type": null
},
{
"param": "img_mean",
"type": null
},
{
"param": "label_num",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "image",
"type": null,
"docstring": "input rgb image",
"docstring_tokens": [
"input",
"rgb",
... |
35673d22447611ef4fab0da1732296c4802e0136 | bohaohuang/ersa | nn/nn_utils.py | [
"MIT"
] | Python | tf_warn_level | null | def tf_warn_level(warn_level=3):
"""
Filter out info from tensorflow output
:param warn_level: can be 0 or 1 or 2
:return:
"""
if isinstance(warn_level, int):
os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(warn_level)
else:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = warn_level |
Filter out info from tensorflow output
:param warn_level: can be 0 or 1 or 2
:return:
| Filter out info from tensorflow output | [
"Filter",
"out",
"info",
"from",
"tensorflow",
"output"
] | def tf_warn_level(warn_level=3):
if isinstance(warn_level, int):
os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(warn_level)
else:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = warn_level | [
"def",
"tf_warn_level",
"(",
"warn_level",
"=",
"3",
")",
":",
"if",
"isinstance",
"(",
"warn_level",
",",
"int",
")",
":",
"os",
".",
"environ",
"[",
"'TF_CPP_MIN_LOG_LEVEL'",
"]",
"=",
"str",
"(",
"warn_level",
")",
"else",
":",
"os",
".",
"environ",
... | Filter out info from tensorflow output | [
"Filter",
"out",
"info",
"from",
"tensorflow",
"output"
] | [
"\"\"\"\n Filter out info from tensorflow output\n :param warn_level: can be 0 or 1 or 2\n :return:\n \"\"\""
] | [
{
"param": "warn_level",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "warn_level",
"type": null,
"docstring": "can be 0 or 1 or 2",
"docstring_tokens": [
"can",
"be",
... |
e5478ac26e211a19818f7514d6f604417ef6d3e0 | fx-kirin/kanimysql | kanimysql/core.py | [
"MIT"
] | Python | insert | <not_specific> | def insert(self, value, ignore=False, commit=True):
"""
Insert a dict into db.
:type table: string
:type value: dict
:type ignore: bool
:type commit: bool
:return: int. The row id of the insert.
"""
table = value._table_name
value_q, _args... |
Insert a dict into db.
:type table: string
:type value: dict
:type ignore: bool
:type commit: bool
:return: int. The row id of the insert.
| Insert a dict into db. | [
"Insert",
"a",
"dict",
"into",
"db",
"."
] | def insert(self, value, ignore=False, commit=True):
table = value._table_name
value_q, _args = self._value_parser(value, columnname=False)
_sql = ''.join(['INSERT', ' IGNORE' if ignore else '', ' INTO ', self._backtick(table),
' (', self._backtick_columns(value), ') VALUE... | [
"def",
"insert",
"(",
"self",
",",
"value",
",",
"ignore",
"=",
"False",
",",
"commit",
"=",
"True",
")",
":",
"table",
"=",
"value",
".",
"_table_name",
"value_q",
",",
"_args",
"=",
"self",
".",
"_value_parser",
"(",
"value",
",",
"columnname",
"=",
... | Insert a dict into db. | [
"Insert",
"a",
"dict",
"into",
"db",
"."
] | [
"\"\"\"\n Insert a dict into db.\n :type table: string\n :type value: dict\n :type ignore: bool\n :type commit: bool\n :return: int. The row id of the insert.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "value",
"type": null
},
{
"param": "ignore",
"type": null
},
{
"param": "commit",
"type": null
}
] | {
"returns": [
{
"docstring": "int. The row id of the insert.",
"docstring_tokens": [
"int",
".",
"The",
"row",
"id",
"of",
"the",
"insert",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"ide... |
e5478ac26e211a19818f7514d6f604417ef6d3e0 | fx-kirin/kanimysql | kanimysql/core.py | [
"MIT"
] | Python | insertmany | <not_specific> | def insertmany(self, columns, value, ignore=False, commit=True):
"""
Insert multiple records within one query.
:type columns: list
:type value: list|tuple
:param value: Doesn't support MySQL functions
:param value: Example: [(value1_column1, value1_column2,), ]
:t... |
Insert multiple records within one query.
:type columns: list
:type value: list|tuple
:param value: Doesn't support MySQL functions
:param value: Example: [(value1_column1, value1_column2,), ]
:type ignore: bool
:type commit: bool
:return: int. The row id... | Insert multiple records within one query. | [
"Insert",
"multiple",
"records",
"within",
"one",
"query",
"."
] | def insertmany(self, columns, value, ignore=False, commit=True):
if not isinstance(value, (list, tuple)):
raise TypeError('Input value should be a list or tuple')
if isinstance(value, AttrDict):
table = value._table_name
_sql = ''.join(['INSERT', ' IGNORE' if ignore else ... | [
"def",
"insertmany",
"(",
"self",
",",
"columns",
",",
"value",
",",
"ignore",
"=",
"False",
",",
"commit",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"TypeError",
"(",
"'... | Insert multiple records within one query. | [
"Insert",
"multiple",
"records",
"within",
"one",
"query",
"."
] | [
"\"\"\"\n Insert multiple records within one query.\n :type columns: list\n :type value: list|tuple\n :param value: Doesn't support MySQL functions\n :param value: Example: [(value1_column1, value1_column2,), ]\n :type ignore: bool\n :type commit: bool\n :retu... | [
{
"param": "self",
"type": null
},
{
"param": "columns",
"type": null
},
{
"param": "value",
"type": null
},
{
"param": "ignore",
"type": null
},
{
"param": "commit",
"type": null
}
] | {
"returns": [
{
"docstring": "int. The row id of the LAST insert only.",
"docstring_tokens": [
"int",
".",
"The",
"row",
"id",
"of",
"the",
"LAST",
"insert",
"only",
"."
],
"type": null
}
],
"r... |
9b1c9601f14d74d1d989c3018d9ffedf64de7741 | minesh1291/Keep-It-Up | regression-model-diagnosis/diagnosis.py | [
"MIT"
] | Python | diagnostic_plots | null | def diagnostic_plots(X, y, model_fit=None):
"""
Function to reproduce the 4 base plots of an OLS model in R.
---
Inputs:
X: A numpy array or pandas dataframe of the features to use in building the linear regression model
y: A numpy array or pandas series/dataframe of the target variable of the linear reg... |
Function to reproduce the 4 base plots of an OLS model in R.
---
Inputs:
X: A numpy array or pandas dataframe of the features to use in building the linear regression model
y: A numpy array or pandas series/dataframe of the target variable of the linear regression model
model_fit [optional]: a statsmod... | Function to reproduce the 4 base plots of an OLS model in R.
Inputs.
A numpy array or pandas dataframe of the features to use in building the linear regression model
A numpy array or pandas series/dataframe of the target variable of the linear regression model
model_fit [optional]: a statsmodel.api.OLS model after r... | [
"Function",
"to",
"reproduce",
"the",
"4",
"base",
"plots",
"of",
"an",
"OLS",
"model",
"in",
"R",
".",
"Inputs",
".",
"A",
"numpy",
"array",
"or",
"pandas",
"dataframe",
"of",
"the",
"features",
"to",
"use",
"in",
"building",
"the",
"linear",
"regressio... | def diagnostic_plots(X, y, model_fit=None):
if not model_fit:
model_fit = sm.OLS(y, sm.add_constant(X)).fit()
dataframe = pd.concat([X, y], axis=1)
model_fitted_y = model_fit.fittedvalues
model_residuals = model_fit.resid
model_norm_residuals = model_fit.get_influence().resid_studentized_internal
mode... | [
"def",
"diagnostic_plots",
"(",
"X",
",",
"y",
",",
"model_fit",
"=",
"None",
")",
":",
"if",
"not",
"model_fit",
":",
"model_fit",
"=",
"sm",
".",
"OLS",
"(",
"y",
",",
"sm",
".",
"add_constant",
"(",
"X",
")",
")",
".",
"fit",
"(",
")",
"datafr... | Function to reproduce the 4 base plots of an OLS model in R.
Inputs: | [
"Function",
"to",
"reproduce",
"the",
"4",
"base",
"plots",
"of",
"an",
"OLS",
"model",
"in",
"R",
".",
"Inputs",
":"
] | [
"\"\"\"\n Function to reproduce the 4 base plots of an OLS model in R.\n\n ---\n Inputs:\n\n X: A numpy array or pandas dataframe of the features to use in building the linear regression model\n\n y: A numpy array or pandas series/dataframe of the target variable of the linear regression model\n\n model_fit [... | [
{
"param": "X",
"type": null
},
{
"param": "y",
"type": null
},
{
"param": "model_fit",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "X",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | check_missing | <not_specific> | def check_missing(data,output_path=None):
"""
check the total number & percentage of missing values
per variable of a pandas Dataframe
"""
result = pd.concat([data.isnull().sum(),data.isnull().mean()],axis=1)
result = result.rename(index=str,columns={0:'total missing',1:'proportion'})
i... |
check the total number & percentage of missing values
per variable of a pandas Dataframe
| check the total number & percentage of missing values
per variable of a pandas Dataframe | [
"check",
"the",
"total",
"number",
"&",
"percentage",
"of",
"missing",
"values",
"per",
"variable",
"of",
"a",
"pandas",
"Dataframe"
] | def check_missing(data,output_path=None):
result = pd.concat([data.isnull().sum(),data.isnull().mean()],axis=1)
result = result.rename(index=str,columns={0:'total missing',1:'proportion'})
if output_path is not None:
result.to_csv(output_path+'missing.csv')
print('result saved at', output_pa... | [
"def",
"check_missing",
"(",
"data",
",",
"output_path",
"=",
"None",
")",
":",
"result",
"=",
"pd",
".",
"concat",
"(",
"[",
"data",
".",
"isnull",
"(",
")",
".",
"sum",
"(",
")",
",",
"data",
".",
"isnull",
"(",
")",
".",
"mean",
"(",
")",
"]... | check the total number & percentage of missing values
per variable of a pandas Dataframe | [
"check",
"the",
"total",
"number",
"&",
"percentage",
"of",
"missing",
"values",
"per",
"variable",
"of",
"a",
"pandas",
"Dataframe"
] | [
"\"\"\"\n check the total number & percentage of missing values\n per variable of a pandas Dataframe\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "output_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "output_path",
"type": null,
"docstring": null,
"docstring_tok... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | drop_missing | <not_specific> | def drop_missing(data,axis=0):
"""
Listwise deletion:
excluding all cases (listwise) that have missing values
Parameters
----------
axis: drop cases(0)/columns(1),default 0
Returns
-------
Pandas dataframe with missing cases/columns dropped
"""
data_copy = data.cop... |
Listwise deletion:
excluding all cases (listwise) that have missing values
Parameters
----------
axis: drop cases(0)/columns(1),default 0
Returns
-------
Pandas dataframe with missing cases/columns dropped
| Listwise deletion:
excluding all cases (listwise) that have missing values
Parameters
Returns
Pandas dataframe with missing cases/columns dropped | [
"Listwise",
"deletion",
":",
"excluding",
"all",
"cases",
"(",
"listwise",
")",
"that",
"have",
"missing",
"values",
"Parameters",
"Returns",
"Pandas",
"dataframe",
"with",
"missing",
"cases",
"/",
"columns",
"dropped"
] | def drop_missing(data,axis=0):
data_copy = data.copy(deep=True)
data_copy = data_copy.dropna(axis=axis,inplace=False)
return data_copy | [
"def",
"drop_missing",
"(",
"data",
",",
"axis",
"=",
"0",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"data_copy",
"=",
"data_copy",
".",
"dropna",
"(",
"axis",
"=",
"axis",
",",
"inplace",
"=",
"False",
")",
"r... | Listwise deletion:
excluding all cases (listwise) that have missing values | [
"Listwise",
"deletion",
":",
"excluding",
"all",
"cases",
"(",
"listwise",
")",
"that",
"have",
"missing",
"values"
] | [
"\"\"\"\n Listwise deletion:\n excluding all cases (listwise) that have missing values\n\n Parameters\n ----------\n axis: drop cases(0)/columns(1),default 0\n\n Returns\n -------\n Pandas dataframe with missing cases/columns dropped\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "axis",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "axis",
"type": null,
"docstring": null,
"docstring_tokens": [... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | add_var_denote_NA | <not_specific> | def add_var_denote_NA(data,NA_col=[]):
"""
creating an additional variable indicating whether the data
was missing for that observation (1) or not (0).
"""
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_is_NA'] = np.where... |
creating an additional variable indicating whether the data
was missing for that observation (1) or not (0).
| creating an additional variable indicating whether the data
was missing for that observation (1) or not (0). | [
"creating",
"an",
"additional",
"variable",
"indicating",
"whether",
"the",
"data",
"was",
"missing",
"for",
"that",
"observation",
"(",
"1",
")",
"or",
"not",
"(",
"0",
")",
"."
] | def add_var_denote_NA(data,NA_col=[]):
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_is_NA'] = np.where(data_copy[i].isnull(),1,0)
else:
warn("Column %s has no missing cases" % i)
return data_copy | [
"def",
"add_var_denote_NA",
"(",
"data",
",",
"NA_col",
"=",
"[",
"]",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"for",
"i",
"in",
"NA_col",
":",
"if",
"data_copy",
"[",
"i",
"]",
".",
"isnull",
"(",
")",
"."... | creating an additional variable indicating whether the data
was missing for that observation (1) or not (0). | [
"creating",
"an",
"additional",
"variable",
"indicating",
"whether",
"the",
"data",
"was",
"missing",
"for",
"that",
"observation",
"(",
"1",
")",
"or",
"not",
"(",
"0",
")",
"."
] | [
"\"\"\"\n creating an additional variable indicating whether the data \n was missing for that observation (1) or not (0).\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "NA_col",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "NA_col",
"type": null,
"docstring": null,
"docstring_tokens":... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | impute_NA_with_arbitrary | <not_specific> | def impute_NA_with_arbitrary(data,impute_value,NA_col=[]):
"""
replacing NA with arbitrary values.
"""
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_'+str(impute_value)] = data_copy[i].fillna(impute_value)
else:
... |
replacing NA with arbitrary values.
| replacing NA with arbitrary values. | [
"replacing",
"NA",
"with",
"arbitrary",
"values",
"."
] | def impute_NA_with_arbitrary(data,impute_value,NA_col=[]):
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_'+str(impute_value)] = data_copy[i].fillna(impute_value)
else:
warn("Column %s has no missing cases" % i)
retur... | [
"def",
"impute_NA_with_arbitrary",
"(",
"data",
",",
"impute_value",
",",
"NA_col",
"=",
"[",
"]",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"for",
"i",
"in",
"NA_col",
":",
"if",
"data_copy",
"[",
"i",
"]",
".",... | replacing NA with arbitrary values. | [
"replacing",
"NA",
"with",
"arbitrary",
"values",
"."
] | [
"\"\"\"\n replacing NA with arbitrary values. \n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "impute_value",
"type": null
},
{
"param": "NA_col",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "impute_value",
"type": null,
"docstring": null,
"docstring_to... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | impute_NA_with_avg | <not_specific> | def impute_NA_with_avg(data,strategy='mean',NA_col=[]):
"""
replacing the NA with mean/median/most frequent values of that variable.
Note it should only be performed over training set and then propagated to test set.
"""
data_copy = data.copy(deep=True)
for i in NA_col:
if data_cop... |
replacing the NA with mean/median/most frequent values of that variable.
Note it should only be performed over training set and then propagated to test set.
| replacing the NA with mean/median/most frequent values of that variable.
Note it should only be performed over training set and then propagated to test set. | [
"replacing",
"the",
"NA",
"with",
"mean",
"/",
"median",
"/",
"most",
"frequent",
"values",
"of",
"that",
"variable",
".",
"Note",
"it",
"should",
"only",
"be",
"performed",
"over",
"training",
"set",
"and",
"then",
"propagated",
"to",
"test",
"set",
"."
] | def impute_NA_with_avg(data,strategy='mean',NA_col=[]):
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
if strategy=='mean':
data_copy[i+'_impute_mean'] = data_copy[i].fillna(data[i].mean())
elif strategy=='median':
... | [
"def",
"impute_NA_with_avg",
"(",
"data",
",",
"strategy",
"=",
"'mean'",
",",
"NA_col",
"=",
"[",
"]",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"for",
"i",
"in",
"NA_col",
":",
"if",
"data_copy",
"[",
"i",
"]... | replacing the NA with mean/median/most frequent values of that variable. | [
"replacing",
"the",
"NA",
"with",
"mean",
"/",
"median",
"/",
"most",
"frequent",
"values",
"of",
"that",
"variable",
"."
] | [
"\"\"\"\n replacing the NA with mean/median/most frequent values of that variable. \n Note it should only be performed over training set and then propagated to test set.\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "strategy",
"type": null
},
{
"param": "NA_col",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "strategy",
"type": null,
"docstring": null,
"docstring_tokens... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | impute_NA_with_end_of_distribution | <not_specific> | def impute_NA_with_end_of_distribution(data,NA_col=[]):
"""
replacing the NA by values that are at the far end of the distribution of that variable
calculated by mean + 3*std
"""
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_cop... |
replacing the NA by values that are at the far end of the distribution of that variable
calculated by mean + 3*std
| replacing the NA by values that are at the far end of the distribution of that variable
calculated by mean + 3*std | [
"replacing",
"the",
"NA",
"by",
"values",
"that",
"are",
"at",
"the",
"far",
"end",
"of",
"the",
"distribution",
"of",
"that",
"variable",
"calculated",
"by",
"mean",
"+",
"3",
"*",
"std"
] | def impute_NA_with_end_of_distribution(data,NA_col=[]):
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_impute_end_of_distri'] = data_copy[i].fillna(data[i].mean()+3*data[i].std())
else:
warn("Column %s has no missing" % i... | [
"def",
"impute_NA_with_end_of_distribution",
"(",
"data",
",",
"NA_col",
"=",
"[",
"]",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"for",
"i",
"in",
"NA_col",
":",
"if",
"data_copy",
"[",
"i",
"]",
".",
"isnull",
... | replacing the NA by values that are at the far end of the distribution of that variable
calculated by mean + 3*std | [
"replacing",
"the",
"NA",
"by",
"values",
"that",
"are",
"at",
"the",
"far",
"end",
"of",
"the",
"distribution",
"of",
"that",
"variable",
"calculated",
"by",
"mean",
"+",
"3",
"*",
"std"
] | [
"\"\"\"\n replacing the NA by values that are at the far end of the distribution of that variable\n calculated by mean + 3*std\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "NA_col",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "NA_col",
"type": null,
"docstring": null,
"docstring_tokens":... |
f948de992699b88cd442de420125d67741743aa2 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/missing_data.py | [
"MIT"
] | Python | impute_NA_with_random | <not_specific> | def impute_NA_with_random(data,NA_col=[],random_state=0):
"""
replacing the NA with random sampling from the pool of available observations of the variable
"""
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_random'] = data_c... |
replacing the NA with random sampling from the pool of available observations of the variable
| replacing the NA with random sampling from the pool of available observations of the variable | [
"replacing",
"the",
"NA",
"with",
"random",
"sampling",
"from",
"the",
"pool",
"of",
"available",
"observations",
"of",
"the",
"variable"
] | def impute_NA_with_random(data,NA_col=[],random_state=0):
data_copy = data.copy(deep=True)
for i in NA_col:
if data_copy[i].isnull().sum()>0:
data_copy[i+'_random'] = data_copy[i]
random_sample = data_copy[i].dropna().sample(data_copy[i].isnull().sum(), random_state=random_state)... | [
"def",
"impute_NA_with_random",
"(",
"data",
",",
"NA_col",
"=",
"[",
"]",
",",
"random_state",
"=",
"0",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"for",
"i",
"in",
"NA_col",
":",
"if",
"data_copy",
"[",
"i",
... | replacing the NA with random sampling from the pool of available observations of the variable | [
"replacing",
"the",
"NA",
"with",
"random",
"sampling",
"from",
"the",
"pool",
"of",
"available",
"observations",
"of",
"the",
"variable"
] | [
"\"\"\"\n replacing the NA with random sampling from the pool of available observations of the variable\n \"\"\"",
"# extract the random sample to fill the na"
] | [
{
"param": "data",
"type": null
},
{
"param": "NA_col",
"type": null
},
{
"param": "random_state",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "NA_col",
"type": null,
"docstring": null,
"docstring_tokens":... |
473176d6c31645904af7620da4430ae3d30a304a | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_selection/filter_method.py | [
"MIT"
] | Python | constant_feature_detect | <not_specific> | def constant_feature_detect(data,threshold=0.98):
""" detect features that show the same value for the
majority/all of the observations (constant/quasi-constant features)
Parameters
----------
data : pd.Dataframe
threshold : threshold to identify the variable as constant
Retur... | detect features that show the same value for the
majority/all of the observations (constant/quasi-constant features)
Parameters
----------
data : pd.Dataframe
threshold : threshold to identify the variable as constant
Returns
-------
list of variables names
| detect features that show the same value for the
majority/all of the observations (constant/quasi-constant features)
Parameters
data : pd.Dataframe
threshold : threshold to identify the variable as constant
Returns
list of variables names | [
"detect",
"features",
"that",
"show",
"the",
"same",
"value",
"for",
"the",
"majority",
"/",
"all",
"of",
"the",
"observations",
"(",
"constant",
"/",
"quasi",
"-",
"constant",
"features",
")",
"Parameters",
"data",
":",
"pd",
".",
"Dataframe",
"threshold",
... | def constant_feature_detect(data,threshold=0.98):
data_copy = data.copy(deep=True)
quasi_constant_feature = []
for feature in data_copy.columns:
predominant = (data_copy[feature].value_counts() / np.float(
len(data_copy))).sort_values(ascending=False).values[0]
if predo... | [
"def",
"constant_feature_detect",
"(",
"data",
",",
"threshold",
"=",
"0.98",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"quasi_constant_feature",
"=",
"[",
"]",
"for",
"feature",
"in",
"data_copy",
".",
"columns",
":",... | detect features that show the same value for the
majority/all of the observations (constant/quasi-constant features) | [
"detect",
"features",
"that",
"show",
"the",
"same",
"value",
"for",
"the",
"majority",
"/",
"all",
"of",
"the",
"observations",
"(",
"constant",
"/",
"quasi",
"-",
"constant",
"features",
")"
] | [
"\"\"\" detect features that show the same value for the \n majority/all of the observations (constant/quasi-constant features)\n \n Parameters\n ----------\n data : pd.Dataframe\n threshold : threshold to identify the variable as constant\n \n Returns\n -------\n list of variables... | [
{
"param": "data",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "threshold",
"type": null,
"docstring": null,
"docstring_token... |
473176d6c31645904af7620da4430ae3d30a304a | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_selection/filter_method.py | [
"MIT"
] | Python | corr_feature_detect | <not_specific> | def corr_feature_detect(data,threshold=0.8):
""" detect highly-correlated features of a Dataframe
Parameters
----------
data : pd.Dataframe
threshold : threshold to identify the variable correlated
Returns
-------
pairs of correlated variables
"""
corrmat = data.cor... | detect highly-correlated features of a Dataframe
Parameters
----------
data : pd.Dataframe
threshold : threshold to identify the variable correlated
Returns
-------
pairs of correlated variables
| detect highly-correlated features of a Dataframe
Parameters
data : pd.Dataframe
threshold : threshold to identify the variable correlated
Returns
pairs of correlated variables | [
"detect",
"highly",
"-",
"correlated",
"features",
"of",
"a",
"Dataframe",
"Parameters",
"data",
":",
"pd",
".",
"Dataframe",
"threshold",
":",
"threshold",
"to",
"identify",
"the",
"variable",
"correlated",
"Returns",
"pairs",
"of",
"correlated",
"variables"
] | def corr_feature_detect(data,threshold=0.8):
corrmat = data.corr()
corrmat = corrmat.abs().unstack()
corrmat = corrmat.sort_values(ascending=False)
corrmat = corrmat[corrmat >= threshold]
corrmat = corrmat[corrmat < 1]
corrmat = pd.DataFrame(corrmat).reset_index()
corrmat.columns = ['featu... | [
"def",
"corr_feature_detect",
"(",
"data",
",",
"threshold",
"=",
"0.8",
")",
":",
"corrmat",
"=",
"data",
".",
"corr",
"(",
")",
"corrmat",
"=",
"corrmat",
".",
"abs",
"(",
")",
".",
"unstack",
"(",
")",
"corrmat",
"=",
"corrmat",
".",
"sort_values",
... | detect highly-correlated features of a Dataframe
Parameters | [
"detect",
"highly",
"-",
"correlated",
"features",
"of",
"a",
"Dataframe",
"Parameters"
] | [
"\"\"\" detect highly-correlated features of a Dataframe\n Parameters\n ----------\n data : pd.Dataframe\n threshold : threshold to identify the variable correlated\n \n Returns\n -------\n pairs of correlated variables\n \"\"\"",
"# absolute value of corr coef",
"# remove the dig... | [
{
"param": "data",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "threshold",
"type": null,
"docstring": null,
"docstring_token... |
473176d6c31645904af7620da4430ae3d30a304a | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_selection/filter_method.py | [
"MIT"
] | Python | univariate_roc_auc | <not_specific> | def univariate_roc_auc(X_train,y_train,X_test,y_test,threshold):
"""
First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or ... |
First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)
It selects the highest ranked features
| First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)
It selects the highest ranked features | [
"First",
"it",
"builds",
"one",
"decision",
"tree",
"per",
"feature",
"to",
"predict",
"the",
"target",
"Second",
"it",
"makes",
"predictions",
"using",
"the",
"decision",
"tree",
"and",
"the",
"mentioned",
"feature",
"Third",
"it",
"ranks",
"the",
"features",... | def univariate_roc_auc(X_train,y_train,X_test,y_test,threshold):
roc_values = []
for feature in X_train.columns:
clf = DecisionTreeClassifier()
clf.fit(X_train[feature].to_frame(), y_train)
y_scored = clf.predict_proba(X_test[feature].to_frame())
roc_values.append(roc_auc_score(y... | [
"def",
"univariate_roc_auc",
"(",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test",
",",
"threshold",
")",
":",
"roc_values",
"=",
"[",
"]",
"for",
"feature",
"in",
"X_train",
".",
"columns",
":",
"clf",
"=",
"DecisionTreeClassifier",
"(",
")",
"clf... | First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)
It selects the highest ranked features | [
"First",
"it",
"builds",
"one",
"decision",
"tree",
"per",
"feature",
"to",
"predict",
"the",
"target",
"Second",
"it",
"makes",
"predictions",
"using",
"the",
"decision",
"tree",
"and",
"the",
"mentioned",
"feature",
"Third",
"it",
"ranks",
"the",
"features",... | [
"\"\"\"\n First, it builds one decision tree per feature, to predict the target\n Second, it makes predictions using the decision tree and the mentioned feature\n Third, it ranks the features according to the machine learning metric (roc-auc or mse)\n It selects the highest ranked features\n\n \"\"\"... | [
{
"param": "X_train",
"type": null
},
{
"param": "y_train",
"type": null
},
{
"param": "X_test",
"type": null
},
{
"param": "y_test",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "X_train",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y_train",
"type": null,
"docstring": null,
"docstring_toke... |
473176d6c31645904af7620da4430ae3d30a304a | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_selection/filter_method.py | [
"MIT"
] | Python | univariate_mse | <not_specific> | def univariate_mse(X_train,y_train,X_test,y_test,threshold):
"""
First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)... |
First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)
It selects the highest ranked features
| First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)
It selects the highest ranked features | [
"First",
"it",
"builds",
"one",
"decision",
"tree",
"per",
"feature",
"to",
"predict",
"the",
"target",
"Second",
"it",
"makes",
"predictions",
"using",
"the",
"decision",
"tree",
"and",
"the",
"mentioned",
"feature",
"Third",
"it",
"ranks",
"the",
"features",... | def univariate_mse(X_train,y_train,X_test,y_test,threshold):
mse_values = []
for feature in X_train.columns:
clf = DecisionTreeRegressor()
clf.fit(X_train[feature].to_frame(), y_train)
y_scored = clf.predict(X_test[feature].to_frame())
mse_values.append(mean_squared_error(y_test,... | [
"def",
"univariate_mse",
"(",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test",
",",
"threshold",
")",
":",
"mse_values",
"=",
"[",
"]",
"for",
"feature",
"in",
"X_train",
".",
"columns",
":",
"clf",
"=",
"DecisionTreeRegressor",
"(",
")",
"clf",
... | First, it builds one decision tree per feature, to predict the target
Second, it makes predictions using the decision tree and the mentioned feature
Third, it ranks the features according to the machine learning metric (roc-auc or mse)
It selects the highest ranked features | [
"First",
"it",
"builds",
"one",
"decision",
"tree",
"per",
"feature",
"to",
"predict",
"the",
"target",
"Second",
"it",
"makes",
"predictions",
"using",
"the",
"decision",
"tree",
"and",
"the",
"mentioned",
"feature",
"Third",
"it",
"ranks",
"the",
"features",... | [
"\"\"\"\n First, it builds one decision tree per feature, to predict the target\n Second, it makes predictions using the decision tree and the mentioned feature\n Third, it ranks the features according to the machine learning metric (roc-auc or mse)\n It selects the highest ranked features\n\n \"\"\"... | [
{
"param": "X_train",
"type": null
},
{
"param": "y_train",
"type": null
},
{
"param": "X_test",
"type": null
},
{
"param": "y_test",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "X_train",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y_train",
"type": null,
"docstring": null,
"docstring_toke... |
64b0d533bc15849a82676011690b43d9d75e7095 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/outlier.py | [
"MIT"
] | Python | outlier_detect_arbitrary | <not_specific> | def outlier_detect_arbitrary(data,col,upper_fence,lower_fence):
'''
identify outliers based on arbitrary boundaries passed to the function.
'''
para = (upper_fence, lower_fence)
tmp = pd.concat([data[col]>upper_fence,data[col]<lower_fence],axis=1)
outlier_index = tmp.any(axis=1)
print('Num ... |
identify outliers based on arbitrary boundaries passed to the function.
| identify outliers based on arbitrary boundaries passed to the function. | [
"identify",
"outliers",
"based",
"on",
"arbitrary",
"boundaries",
"passed",
"to",
"the",
"function",
"."
] | def outlier_detect_arbitrary(data,col,upper_fence,lower_fence):
para = (upper_fence, lower_fence)
tmp = pd.concat([data[col]>upper_fence,data[col]<lower_fence],axis=1)
outlier_index = tmp.any(axis=1)
print('Num of outlier detected:',outlier_index.value_counts()[1])
print('Proportion of outlier detec... | [
"def",
"outlier_detect_arbitrary",
"(",
"data",
",",
"col",
",",
"upper_fence",
",",
"lower_fence",
")",
":",
"para",
"=",
"(",
"upper_fence",
",",
"lower_fence",
")",
"tmp",
"=",
"pd",
".",
"concat",
"(",
"[",
"data",
"[",
"col",
"]",
">",
"upper_fence"... | identify outliers based on arbitrary boundaries passed to the function. | [
"identify",
"outliers",
"based",
"on",
"arbitrary",
"boundaries",
"passed",
"to",
"the",
"function",
"."
] | [
"'''\n identify outliers based on arbitrary boundaries passed to the function.\n '''"
] | [
{
"param": "data",
"type": null
},
{
"param": "col",
"type": null
},
{
"param": "upper_fence",
"type": null
},
{
"param": "lower_fence",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "col",
"type": null,
"docstring": null,
"docstring_tokens": []... |
64b0d533bc15849a82676011690b43d9d75e7095 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/outlier.py | [
"MIT"
] | Python | outlier_detect_mean_std | <not_specific> | def outlier_detect_mean_std(data,col,threshold=3):
'''
outlier detection by Mean and Standard Deviation Method.
If a value is a certain number(called threshold) of standard deviations away
from the mean, that data point is identified as an outlier.
Default threshold is 3.
This method can fail... |
outlier detection by Mean and Standard Deviation Method.
If a value is a certain number(called threshold) of standard deviations away
from the mean, that data point is identified as an outlier.
Default threshold is 3.
This method can fail to detect outliers because the outliers increase the stan... | outlier detection by Mean and Standard Deviation Method.
If a value is a certain number(called threshold) of standard deviations away
from the mean, that data point is identified as an outlier.
Default threshold is 3.
This method can fail to detect outliers because the outliers increase the standard deviation.
The mor... | [
"outlier",
"detection",
"by",
"Mean",
"and",
"Standard",
"Deviation",
"Method",
".",
"If",
"a",
"value",
"is",
"a",
"certain",
"number",
"(",
"called",
"threshold",
")",
"of",
"standard",
"deviations",
"away",
"from",
"the",
"mean",
"that",
"data",
"point",
... | def outlier_detect_mean_std(data,col,threshold=3):
Upper_fence = data[col].mean() + threshold * data[col].std()
Lower_fence = data[col].mean() - threshold * data[col].std()
para = (Upper_fence, Lower_fence)
tmp = pd.concat([data[col]>Upper_fence,data[col]<Lower_fence],axis=1)
outlier_index = t... | [
"def",
"outlier_detect_mean_std",
"(",
"data",
",",
"col",
",",
"threshold",
"=",
"3",
")",
":",
"Upper_fence",
"=",
"data",
"[",
"col",
"]",
".",
"mean",
"(",
")",
"+",
"threshold",
"*",
"data",
"[",
"col",
"]",
".",
"std",
"(",
")",
"Lower_fence",
... | outlier detection by Mean and Standard Deviation Method. | [
"outlier",
"detection",
"by",
"Mean",
"and",
"Standard",
"Deviation",
"Method",
"."
] | [
"'''\n outlier detection by Mean and Standard Deviation Method.\n If a value is a certain number(called threshold) of standard deviations away \n from the mean, that data point is identified as an outlier. \n Default threshold is 3.\n\n This method can fail to detect outliers because the outliers inc... | [
{
"param": "data",
"type": null
},
{
"param": "col",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "col",
"type": null,
"docstring": null,
"docstring_tokens": []... |
64b0d533bc15849a82676011690b43d9d75e7095 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/outlier.py | [
"MIT"
] | Python | outlier_detect_MAD | <not_specific> | def outlier_detect_MAD(data,col,threshold=3.5):
"""
outlier detection by Median and Median Absolute Deviation Method (MAD)
The median of the residuals is calculated. Then, the difference is calculated between each historical value and this median.
These differences are expressed as their absolute value... |
outlier detection by Median and Median Absolute Deviation Method (MAD)
The median of the residuals is calculated. Then, the difference is calculated between each historical value and this median.
These differences are expressed as their absolute values, and a new median is calculated and multiplied by
... | outlier detection by Median and Median Absolute Deviation Method (MAD)
The median of the residuals is calculated. Then, the difference is calculated between each historical value and this median.
These differences are expressed as their absolute values, and a new median is calculated and multiplied by
an empirically de... | [
"outlier",
"detection",
"by",
"Median",
"and",
"Median",
"Absolute",
"Deviation",
"Method",
"(",
"MAD",
")",
"The",
"median",
"of",
"the",
"residuals",
"is",
"calculated",
".",
"Then",
"the",
"difference",
"is",
"calculated",
"between",
"each",
"historical",
"... | def outlier_detect_MAD(data,col,threshold=3.5):
median = data[col].median()
median_absolute_deviation = np.median([np.abs(y - median) for y in data[col]])
modified_z_scores = pd.Series([0.6745 * (y - median) / median_absolute_deviation for y in data[col]])
outlier_index = np.abs(modified_z_scores) > thr... | [
"def",
"outlier_detect_MAD",
"(",
"data",
",",
"col",
",",
"threshold",
"=",
"3.5",
")",
":",
"median",
"=",
"data",
"[",
"col",
"]",
".",
"median",
"(",
")",
"median_absolute_deviation",
"=",
"np",
".",
"median",
"(",
"[",
"np",
".",
"abs",
"(",
"y"... | outlier detection by Median and Median Absolute Deviation Method (MAD)
The median of the residuals is calculated. | [
"outlier",
"detection",
"by",
"Median",
"and",
"Median",
"Absolute",
"Deviation",
"Method",
"(",
"MAD",
")",
"The",
"median",
"of",
"the",
"residuals",
"is",
"calculated",
"."
] | [
"\"\"\"\n outlier detection by Median and Median Absolute Deviation Method (MAD)\n The median of the residuals is calculated. Then, the difference is calculated between each historical value and this median. \n These differences are expressed as their absolute values, and a new median is calculated and mul... | [
{
"param": "data",
"type": null
},
{
"param": "col",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "col",
"type": null,
"docstring": null,
"docstring_tokens": []... |
64b0d533bc15849a82676011690b43d9d75e7095 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/outlier.py | [
"MIT"
] | Python | windsorization | <not_specific> | def windsorization(data,col,para,strategy='both'):
"""
top-coding & bottom coding (capping the maximum of a distribution at an arbitrarily set value,vice versa)
"""
data_copy = data.copy(deep=True)
if strategy == 'both':
data_copy.loc[data_copy[col]>para[0],col] = para[0]
data... |
top-coding & bottom coding (capping the maximum of a distribution at an arbitrarily set value,vice versa)
| top-coding & bottom coding (capping the maximum of a distribution at an arbitrarily set value,vice versa) | [
"top",
"-",
"coding",
"&",
"bottom",
"coding",
"(",
"capping",
"the",
"maximum",
"of",
"a",
"distribution",
"at",
"an",
"arbitrarily",
"set",
"value",
"vice",
"versa",
")"
] | def windsorization(data,col,para,strategy='both'):
data_copy = data.copy(deep=True)
if strategy == 'both':
data_copy.loc[data_copy[col]>para[0],col] = para[0]
data_copy.loc[data_copy[col]<para[1],col] = para[1]
elif strategy == 'top':
data_copy.loc[data_copy[col]>para[0],col] = par... | [
"def",
"windsorization",
"(",
"data",
",",
"col",
",",
"para",
",",
"strategy",
"=",
"'both'",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"if",
"strategy",
"==",
"'both'",
":",
"data_copy",
".",
"loc",
"[",
"data_... | top-coding & bottom coding (capping the maximum of a distribution at an arbitrarily set value,vice versa) | [
"top",
"-",
"coding",
"&",
"bottom",
"coding",
"(",
"capping",
"the",
"maximum",
"of",
"a",
"distribution",
"at",
"an",
"arbitrarily",
"set",
"value",
"vice",
"versa",
")"
] | [
"\"\"\"\n top-coding & bottom coding (capping the maximum of a distribution at an arbitrarily set value,vice versa)\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "col",
"type": null
},
{
"param": "para",
"type": null
},
{
"param": "strategy",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "col",
"type": null,
"docstring": null,
"docstring_tokens": []... |
64b0d533bc15849a82676011690b43d9d75e7095 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/outlier.py | [
"MIT"
] | Python | drop_outlier | <not_specific> | def drop_outlier(data,outlier_index):
"""
drop the cases that are outliers
"""
data_copy = data[~outlier_index]
return data_copy |
drop the cases that are outliers
| drop the cases that are outliers | [
"drop",
"the",
"cases",
"that",
"are",
"outliers"
] | def drop_outlier(data,outlier_index):
data_copy = data[~outlier_index]
return data_copy | [
"def",
"drop_outlier",
"(",
"data",
",",
"outlier_index",
")",
":",
"data_copy",
"=",
"data",
"[",
"~",
"outlier_index",
"]",
"return",
"data_copy"
] | drop the cases that are outliers | [
"drop",
"the",
"cases",
"that",
"are",
"outliers"
] | [
"\"\"\"\n drop the cases that are outliers\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "outlier_index",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "outlier_index",
"type": null,
"docstring": null,
"docstring_t... |
64b0d533bc15849a82676011690b43d9d75e7095 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/outlier.py | [
"MIT"
] | Python | impute_outlier_with_avg | <not_specific> | def impute_outlier_with_avg(data,col,outlier_index,strategy='mean'):
"""
impute outlier with mean/median/most frequent values of that variable.
"""
data_copy = data.copy(deep=True)
if strategy=='mean':
data_copy.loc[outlier_index,col] = data_copy[col].mean()
elif strategy=='median':... |
impute outlier with mean/median/most frequent values of that variable.
| impute outlier with mean/median/most frequent values of that variable. | [
"impute",
"outlier",
"with",
"mean",
"/",
"median",
"/",
"most",
"frequent",
"values",
"of",
"that",
"variable",
"."
] | def impute_outlier_with_avg(data,col,outlier_index,strategy='mean'):
data_copy = data.copy(deep=True)
if strategy=='mean':
data_copy.loc[outlier_index,col] = data_copy[col].mean()
elif strategy=='median':
data_copy.loc[outlier_index,col] = data_copy[col].median()
elif strategy=='mode':
... | [
"def",
"impute_outlier_with_avg",
"(",
"data",
",",
"col",
",",
"outlier_index",
",",
"strategy",
"=",
"'mean'",
")",
":",
"data_copy",
"=",
"data",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"if",
"strategy",
"==",
"'mean'",
":",
"data_copy",
".",
"loc... | impute outlier with mean/median/most frequent values of that variable. | [
"impute",
"outlier",
"with",
"mean",
"/",
"median",
"/",
"most",
"frequent",
"values",
"of",
"that",
"variable",
"."
] | [
"\"\"\"\n impute outlier with mean/median/most frequent values of that variable.\n \"\"\""
] | [
{
"param": "data",
"type": null
},
{
"param": "col",
"type": null
},
{
"param": "outlier_index",
"type": null
},
{
"param": "strategy",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "col",
"type": null,
"docstring": null,
"docstring_tokens": []... |
026d92739d1c6f842e82ec2a05fb14e4cd2c8931 | minesh1291/Keep-It-Up | feature-engineering-and-data-transformations/using-toy-exmaples/feature_cleaning/rare_values.py | [
"MIT"
] | Python | grouping | <not_specific> | def grouping(self, X_in, threshold, mapping=None, cols=None):
"""
Grouping the observations that show rare labels into a unique category ('rare')
"""
X = X_in.copy(deep=True)
# if cols is None:
# cols = X.columns.values
if mapping is not None: # transform
... |
Grouping the observations that show rare labels into a unique category ('rare')
| Grouping the observations that show rare labels into a unique category ('rare') | [
"Grouping",
"the",
"observations",
"that",
"show",
"rare",
"labels",
"into",
"a",
"unique",
"category",
"(",
"'",
"rare",
"'",
")"
] | def grouping(self, X_in, threshold, mapping=None, cols=None):
X = X_in.copy(deep=True)
if mapping is not None:
mapping_out = mapping
for i in mapping:
column = i.get('col')
X[column] = X[column].map(i['mapping'])
else:
mappi... | [
"def",
"grouping",
"(",
"self",
",",
"X_in",
",",
"threshold",
",",
"mapping",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"X",
"=",
"X_in",
".",
"copy",
"(",
"deep",
"=",
"True",
")",
"if",
"mapping",
"is",
"not",
"None",
":",
"mapping_out",
... | Grouping the observations that show rare labels into a unique category ('rare') | [
"Grouping",
"the",
"observations",
"that",
"show",
"rare",
"labels",
"into",
"a",
"unique",
"category",
"(",
"'",
"rare",
"'",
")"
] | [
"\"\"\"\n Grouping the observations that show rare labels into a unique category ('rare')\n\n \"\"\"",
"# if cols is None:",
"# cols = X.columns.values",
"# transform",
"# get the column name",
"# try:",
"# X[column] = X[column].astype(in... | [
{
"param": "self",
"type": null
},
{
"param": "X_in",
"type": null
},
{
"param": "threshold",
"type": null
},
{
"param": "mapping",
"type": null
},
{
"param": "cols",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "X_in",
"type": null,
"docstring": null,
"docstring_tokens": [... |
3e3ff4091268ace6503d019f793206caffb592be | owtf/addons | owtf_extensions/wafbypasser/core/helper.py | [
"BSD-3-Clause"
] | Python | load_payload_file | <not_specific> | def load_payload_file(payload_path, valid_size=100000,
exclude_chars=[]):
"""This Function loads a list with payloads"""
payloads = []
try:
with open(os.path.expanduser(payload_path), 'r') as f:
for line in f.readlines():
line = line.strip('\n')
... | This Function loads a list with payloads | This Function loads a list with payloads | [
"This",
"Function",
"loads",
"a",
"list",
"with",
"payloads"
] | def load_payload_file(payload_path, valid_size=100000,
exclude_chars=[]):
payloads = []
try:
with open(os.path.expanduser(payload_path), 'r') as f:
for line in f.readlines():
line = line.strip('\n')
if len(line) > valid_size:
... | [
"def",
"load_payload_file",
"(",
"payload_path",
",",
"valid_size",
"=",
"100000",
",",
"exclude_chars",
"=",
"[",
"]",
")",
":",
"payloads",
"=",
"[",
"]",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"payload_path",
")",
... | This Function loads a list with payloads | [
"This",
"Function",
"loads",
"a",
"list",
"with",
"payloads"
] | [
"\"\"\"This Function loads a list with payloads\"\"\""
] | [
{
"param": "payload_path",
"type": null
},
{
"param": "valid_size",
"type": null
},
{
"param": "exclude_chars",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "payload_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "valid_size",
"type": null,
"docstring": null,
"docstr... |
8ed2e7fe9c87c8174987052a07e6ab5c60093cfe | owtf/addons | owtf_extensions/wafbypasser/core/response_analyzer.py | [
"BSD-3-Clause"
] | Python | format_char | <not_specific> | def format_char(char):
"""Converts a character to printable format"""
if char in string.ascii_letters:
return char
if char in string.digits:
return char
if char in string.punctuation:
return char
if char in string.whitespace:
if char == " ":
return "[SPACE... | Converts a character to printable format | Converts a character to printable format | [
"Converts",
"a",
"character",
"to",
"printable",
"format"
] | def format_char(char):
if char in string.ascii_letters:
return char
if char in string.digits:
return char
if char in string.punctuation:
return char
if char in string.whitespace:
if char == " ":
return "[SPACE]"
if char == "\t":
return "[TA... | [
"def",
"format_char",
"(",
"char",
")",
":",
"if",
"char",
"in",
"string",
".",
"ascii_letters",
":",
"return",
"char",
"if",
"char",
"in",
"string",
".",
"digits",
":",
"return",
"char",
"if",
"char",
"in",
"string",
".",
"punctuation",
":",
"return",
... | Converts a character to printable format | [
"Converts",
"a",
"character",
"to",
"printable",
"format"
] | [
"\"\"\"Converts a character to printable format\"\"\""
] | [
{
"param": "char",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "char",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
66e9462ccb7e45d264b36787dbe5a7c3d80fa329 | owtf/addons | owtf_extensions/wafbypasser/core/http_helper.py | [
"BSD-3-Clause"
] | Python | create_http_request | <not_specific> | def create_http_request(self, method, url, body=None, headers={},
payload=None):
"""This function creates an HTTP request with some additional
initializations"""
request = copy(self.init_request)
request.method = method
request.url = url
requ... | This function creates an HTTP request with some additional
initializations | This function creates an HTTP request with some additional
initializations | [
"This",
"function",
"creates",
"an",
"HTTP",
"request",
"with",
"some",
"additional",
"initializations"
] | def create_http_request(self, method, url, body=None, headers={},
payload=None):
request = copy(self.init_request)
request.method = method
request.url = url
request.headers = headers
if body:
request.body = body
if headers and n... | [
"def",
"create_http_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
",",
"payload",
"=",
"None",
")",
":",
"request",
"=",
"copy",
"(",
"self",
".",
"init_request",
")",
"request",
".",
"meth... | This function creates an HTTP request with some additional
initializations | [
"This",
"function",
"creates",
"an",
"HTTP",
"request",
"with",
"some",
"additional",
"initializations"
] | [
"\"\"\"This function creates an HTTP request with some additional\n initializations\"\"\"",
"#request.headers[\"Content-Length\"] = len(body)"
] | [
{
"param": "self",
"type": null
},
{
"param": "method",
"type": null
},
{
"param": "url",
"type": null
},
{
"param": "body",
"type": null
},
{
"param": "headers",
"type": null
},
{
"param": "payload",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "method",
"type": null,
"docstring": null,
"docstring_tokens":... |
0094eb5c56ec1e10f1080906f2b5dc660ccd3eea | owtf/addons | owtf_extensions/wafbypasser/core/detection.py | [
"BSD-3-Clause"
] | Python | contains | <not_specific> | def contains(response, args):
"""This function detects if the body of an http response contains a
user defined string"""
phrase = args["phrase"]
body = response.body
if body is None:
if not phrase:
detected = True
else:
detected = False
else:
if no... | This function detects if the body of an http response contains a
user defined string | This function detects if the body of an http response contains a
user defined string | [
"This",
"function",
"detects",
"if",
"the",
"body",
"of",
"an",
"http",
"response",
"contains",
"a",
"user",
"defined",
"string"
] | def contains(response, args):
phrase = args["phrase"]
body = response.body
if body is None:
if not phrase:
detected = True
else:
detected = False
else:
if not args["case_sensitive"]:
phrase = phrase.lower()
body = body.lower()
... | [
"def",
"contains",
"(",
"response",
",",
"args",
")",
":",
"phrase",
"=",
"args",
"[",
"\"phrase\"",
"]",
"body",
"=",
"response",
".",
"body",
"if",
"body",
"is",
"None",
":",
"if",
"not",
"phrase",
":",
"detected",
"=",
"True",
"else",
":",
"detect... | This function detects if the body of an http response contains a
user defined string | [
"This",
"function",
"detects",
"if",
"the",
"body",
"of",
"an",
"http",
"response",
"contains",
"a",
"user",
"defined",
"string"
] | [
"\"\"\"This function detects if the body of an http response contains a\n user defined string\"\"\""
] | [
{
"param": "response",
"type": null
},
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "response",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens... |
0094eb5c56ec1e10f1080906f2b5dc660ccd3eea | owtf/addons | owtf_extensions/wafbypasser/core/detection.py | [
"BSD-3-Clause"
] | Python | resp_code_detection | <not_specific> | def resp_code_detection(response, args):
"""This function detects if the response code of an http response is a
a user defined number or range"""
code_range = []
items = []
items = args["response_codes"].split(',')
for item in items:
tokens = item.split('-')
if len(tokens) == 2:
... | This function detects if the response code of an http response is a
a user defined number or range | This function detects if the response code of an http response is a
a user defined number or range | [
"This",
"function",
"detects",
"if",
"the",
"response",
"code",
"of",
"an",
"http",
"response",
"is",
"a",
"a",
"user",
"defined",
"number",
"or",
"range"
] | def resp_code_detection(response, args):
code_range = []
items = []
items = args["response_codes"].split(',')
for item in items:
tokens = item.split('-')
if len(tokens) == 2:
code_range.extend(list(range(int(tokens[0]), int(tokens[1]) + 1)))
else:
code_ran... | [
"def",
"resp_code_detection",
"(",
"response",
",",
"args",
")",
":",
"code_range",
"=",
"[",
"]",
"items",
"=",
"[",
"]",
"items",
"=",
"args",
"[",
"\"response_codes\"",
"]",
".",
"split",
"(",
"','",
")",
"for",
"item",
"in",
"items",
":",
"tokens",... | This function detects if the response code of an http response is a
a user defined number or range | [
"This",
"function",
"detects",
"if",
"the",
"response",
"code",
"of",
"an",
"http",
"response",
"is",
"a",
"a",
"user",
"defined",
"number",
"or",
"range"
] | [
"\"\"\"This function detects if the response code of an http response is a\n a user defined number or range\"\"\""
] | [
{
"param": "response",
"type": null
},
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "response",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens... |
0094eb5c56ec1e10f1080906f2b5dc660ccd3eea | owtf/addons | owtf_extensions/wafbypasser/core/detection.py | [
"BSD-3-Clause"
] | Python | resp_time_detection | <not_specific> | def resp_time_detection(response, args):
"""This function detects if the response of an http response is
timed out or takes more time than the user defined"""
time = float(args["time"])
detected = False
if response.request_time > time or response.code == 599:
detected = True
if args["rev... | This function detects if the response of an http response is
timed out or takes more time than the user defined | This function detects if the response of an http response is
timed out or takes more time than the user defined | [
"This",
"function",
"detects",
"if",
"the",
"response",
"of",
"an",
"http",
"response",
"is",
"timed",
"out",
"or",
"takes",
"more",
"time",
"than",
"the",
"user",
"defined"
] | def resp_time_detection(response, args):
time = float(args["time"])
detected = False
if response.request_time > time or response.code == 599:
detected = True
if args["reverse"]:
return not detected
return detected | [
"def",
"resp_time_detection",
"(",
"response",
",",
"args",
")",
":",
"time",
"=",
"float",
"(",
"args",
"[",
"\"time\"",
"]",
")",
"detected",
"=",
"False",
"if",
"response",
".",
"request_time",
">",
"time",
"or",
"response",
".",
"code",
"==",
"599",
... | This function detects if the response of an http response is
timed out or takes more time than the user defined | [
"This",
"function",
"detects",
"if",
"the",
"response",
"of",
"an",
"http",
"response",
"is",
"timed",
"out",
"or",
"takes",
"more",
"time",
"than",
"the",
"user",
"defined"
] | [
"\"\"\"This function detects if the response of an http response is\n timed out or takes more time than the user defined\"\"\""
] | [
{
"param": "response",
"type": null
},
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "response",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens... |
ff80d7c38ca57b14614c3982c8a23ecdcb8b3510 | hammerd/NLP | 1.3-hmm-tagger-project/helpers.py | [
"MIT"
] | Python | read_tags | <not_specific> | def read_tags(filename):
"""Read a list of word tag classes"""
with open(filename, 'r') as f:
tags = f.read().split("\n")
return frozenset(tags) | Read a list of word tag classes | Read a list of word tag classes | [
"Read",
"a",
"list",
"of",
"word",
"tag",
"classes"
] | def read_tags(filename):
with open(filename, 'r') as f:
tags = f.read().split("\n")
return frozenset(tags) | [
"def",
"read_tags",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"tags",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"return",
"frozenset",
"(",
"tags",
")"
] | Read a list of word tag classes | [
"Read",
"a",
"list",
"of",
"word",
"tag",
"classes"
] | [
"\"\"\"Read a list of word tag classes\"\"\""
] | [
{
"param": "filename",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
ff80d7c38ca57b14614c3982c8a23ecdcb8b3510 | hammerd/NLP | 1.3-hmm-tagger-project/helpers.py | [
"MIT"
] | Python | model2png | <not_specific> | def model2png(model, filename="", overwrite=False, show_ends=False):
"""Convert a Pomegranate model into a PNG image
The conversion pipeline extracts the underlying NetworkX graph object,
converts it to a PyDot graph, then writes the PNG data to a bytes array,
which can be saved as a file to disk or im... | Convert a Pomegranate model into a PNG image
The conversion pipeline extracts the underlying NetworkX graph object,
converts it to a PyDot graph, then writes the PNG data to a bytes array,
which can be saved as a file to disk or imported with matplotlib for display.
Model -> NetworkX.Graph -> PyDo... | Convert a Pomegranate model into a PNG image
The conversion pipeline extracts the underlying NetworkX graph object,
converts it to a PyDot graph, then writes the PNG data to a bytes array,
which can be saved as a file to disk or imported with matplotlib for display.
Parameters
model : Pomegranate.Model
The model ob... | [
"Convert",
"a",
"Pomegranate",
"model",
"into",
"a",
"PNG",
"image",
"The",
"conversion",
"pipeline",
"extracts",
"the",
"underlying",
"NetworkX",
"graph",
"object",
"converts",
"it",
"to",
"a",
"PyDot",
"graph",
"then",
"writes",
"the",
"PNG",
"data",
"to",
... | def model2png(model, filename="", overwrite=False, show_ends=False):
nodes = model.graph.nodes()
if not show_ends:
nodes = [n for n in nodes if n not in (model.start, model.end)]
g = nx.relabel_nodes(model.graph.subgraph(nodes), {n: n.name for n in model.graph.nodes()})
pydot_graph = nx.drawing.... | [
"def",
"model2png",
"(",
"model",
",",
"filename",
"=",
"\"\"",
",",
"overwrite",
"=",
"False",
",",
"show_ends",
"=",
"False",
")",
":",
"nodes",
"=",
"model",
".",
"graph",
".",
"nodes",
"(",
")",
"if",
"not",
"show_ends",
":",
"nodes",
"=",
"[",
... | Convert a Pomegranate model into a PNG image
The conversion pipeline extracts the underlying NetworkX graph object,
converts it to a PyDot graph, then writes the PNG data to a bytes array,
which can be saved as a file to disk or imported with matplotlib for display. | [
"Convert",
"a",
"Pomegranate",
"model",
"into",
"a",
"PNG",
"image",
"The",
"conversion",
"pipeline",
"extracts",
"the",
"underlying",
"NetworkX",
"graph",
"object",
"converts",
"it",
"to",
"a",
"PyDot",
"graph",
"then",
"writes",
"the",
"PNG",
"data",
"to",
... | [
"\"\"\"Convert a Pomegranate model into a PNG image\n\n The conversion pipeline extracts the underlying NetworkX graph object,\n converts it to a PyDot graph, then writes the PNG data to a bytes array,\n which can be saved as a file to disk or imported with matplotlib for display.\n\n Model -> Netwo... | [
{
"param": "model",
"type": null
},
{
"param": "filename",
"type": null
},
{
"param": "overwrite",
"type": null
},
{
"param": "show_ends",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "filename",
"type": null,
"docstring": null,
"docstring_token... |
ff80d7c38ca57b14614c3982c8a23ecdcb8b3510 | hammerd/NLP | 1.3-hmm-tagger-project/helpers.py | [
"MIT"
] | Python | show_model | null | def show_model(model, figsize=(5, 5), **kwargs):
"""Display a Pomegranate model as an image using matplotlib
Parameters
----------
model : Pomegranate.Model
The model object to convert. The model must have an attribute .graph
referencing a NetworkX.Graph instance.
figsize : tuple(i... | Display a Pomegranate model as an image using matplotlib
Parameters
----------
model : Pomegranate.Model
The model object to convert. The model must have an attribute .graph
referencing a NetworkX.Graph instance.
figsize : tuple(int, int) (optional)
A tuple specifying the dimen... | Display a Pomegranate model as an image using matplotlib
Parameters
model : Pomegranate.Model
The model object to convert. The model must have an attribute .graph
referencing a NetworkX.Graph instance.
figsize : tuple(int, int) (optional)
A tuple specifying the dimensions of a matplotlib Figure that will
display the ... | [
"Display",
"a",
"Pomegranate",
"model",
"as",
"an",
"image",
"using",
"matplotlib",
"Parameters",
"model",
":",
"Pomegranate",
".",
"Model",
"The",
"model",
"object",
"to",
"convert",
".",
"The",
"model",
"must",
"have",
"an",
"attribute",
".",
"graph",
"ref... | def show_model(model, figsize=(5, 5), **kwargs):
plt.figure(figsize=figsize)
plt.imshow(model2png(model, **kwargs))
plt.axis('off') | [
"def",
"show_model",
"(",
"model",
",",
"figsize",
"=",
"(",
"5",
",",
"5",
")",
",",
"**",
"kwargs",
")",
":",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"imshow",
"(",
"model2png",
"(",
"model",
",",
"**",
"kwargs",
... | Display a Pomegranate model as an image using matplotlib
Parameters | [
"Display",
"a",
"Pomegranate",
"model",
"as",
"an",
"image",
"using",
"matplotlib",
"Parameters"
] | [
"\"\"\"Display a Pomegranate model as an image using matplotlib\n\n Parameters\n ----------\n model : Pomegranate.Model\n The model object to convert. The model must have an attribute .graph\n referencing a NetworkX.Graph instance.\n\n figsize : tuple(int, int) (optional)\n A tuple ... | [
{
"param": "model",
"type": null
},
{
"param": "figsize",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "figsize",
"type": null,
"docstring": null,
"docstring_tokens... |
e1e43e3fc2fefaef575149971ce352819232021c | hammerd/NLP | 3.1-AIND-VUI-speech-recognition-project/sample_models.py | [
"MIT"
] | Python | rnn_model | <not_specific> | def rnn_model(input_dim, units, activation, output_dim=29):
""" Build a recurrent network for speech
"""
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# Add recurrent layer
simp_rnn = GRU(units, activation=activation,
return_sequences=True, implemen... | Build a recurrent network for speech
| Build a recurrent network for speech | [
"Build",
"a",
"recurrent",
"network",
"for",
"speech"
] | def rnn_model(input_dim, units, activation, output_dim=29):
input_data = Input(name='the_input', shape=(None, input_dim))
simp_rnn = GRU(units, activation=activation,
return_sequences=True, implementation=2, name='rnn')(input_data)
bn_rnn = BatchNormalization()(simp_rnn)
time_dense = TimeDistrib... | [
"def",
"rnn_model",
"(",
"input_dim",
",",
"units",
",",
"activation",
",",
"output_dim",
"=",
"29",
")",
":",
"input_data",
"=",
"Input",
"(",
"name",
"=",
"'the_input'",
",",
"shape",
"=",
"(",
"None",
",",
"input_dim",
")",
")",
"simp_rnn",
"=",
"GR... | Build a recurrent network for speech | [
"Build",
"a",
"recurrent",
"network",
"for",
"speech"
] | [
"\"\"\" Build a recurrent network for speech \n \"\"\"",
"# Main acoustic input",
"# Add recurrent layer",
"# TODO: Add batch normalization ",
"# TODO: Add a TimeDistributed(Dense(output_dim)) layer",
"# Add softmax activation layer",
"# Specify the model"
] | [
{
"param": "input_dim",
"type": null
},
{
"param": "units",
"type": null
},
{
"param": "activation",
"type": null
},
{
"param": "output_dim",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "input_dim",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "units",
"type": null,
"docstring": null,
"docstring_toke... |
e1e43e3fc2fefaef575149971ce352819232021c | hammerd/NLP | 3.1-AIND-VUI-speech-recognition-project/sample_models.py | [
"MIT"
] | Python | deep_rnn_model | <not_specific> | def deep_rnn_model(input_dim, units, recur_layers, output_dim=29):
""" Build a deep recurrent network for speech
"""
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# TODO: Add recurrent layers, each with batch normalization
simp_rnn = GRU(units, activation='... | Build a deep recurrent network for speech
| Build a deep recurrent network for speech | [
"Build",
"a",
"deep",
"recurrent",
"network",
"for",
"speech"
] | def deep_rnn_model(input_dim, units, recur_layers, output_dim=29):
input_data = Input(name='the_input', shape=(None, input_dim))
simp_rnn = GRU(units, activation='relu',
return_sequences=True, implementation=2, name='rnn1')(input_data)
bn_rnn = BatchNormalization(name='bn_simp_rnn1')(simp_rnn)
... | [
"def",
"deep_rnn_model",
"(",
"input_dim",
",",
"units",
",",
"recur_layers",
",",
"output_dim",
"=",
"29",
")",
":",
"input_data",
"=",
"Input",
"(",
"name",
"=",
"'the_input'",
",",
"shape",
"=",
"(",
"None",
",",
"input_dim",
")",
")",
"simp_rnn",
"="... | Build a deep recurrent network for speech | [
"Build",
"a",
"deep",
"recurrent",
"network",
"for",
"speech"
] | [
"\"\"\" Build a deep recurrent network for speech \n \"\"\"",
"# Main acoustic input",
"# TODO: Add recurrent layers, each with batch normalization",
"# TODO: Add a TimeDistributed(Dense(output_dim)) layer",
"# Add softmax activation layer",
"# Specify the model"
] | [
{
"param": "input_dim",
"type": null
},
{
"param": "units",
"type": null
},
{
"param": "recur_layers",
"type": null
},
{
"param": "output_dim",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "input_dim",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "units",
"type": null,
"docstring": null,
"docstring_toke... |
e1e43e3fc2fefaef575149971ce352819232021c | hammerd/NLP | 3.1-AIND-VUI-speech-recognition-project/sample_models.py | [
"MIT"
] | Python | bidirectional_rnn_model | <not_specific> | def bidirectional_rnn_model(input_dim, units, output_dim=29):
""" Build a bidirectional recurrent network for speech
"""
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# TODO: Add bidirectional recurrent layer
bidir_rnn = Bidirectional( GRU(units, return_sequ... | Build a bidirectional recurrent network for speech
| Build a bidirectional recurrent network for speech | [
"Build",
"a",
"bidirectional",
"recurrent",
"network",
"for",
"speech"
] | def bidirectional_rnn_model(input_dim, units, output_dim=29):
input_data = Input(name='the_input', shape=(None, input_dim))
bidir_rnn = Bidirectional( GRU(units, return_sequences=True,merge_mode='concat') )(input_data)
time_dense = TimeDistributed(Dense(output_dim)) (bidir_rnn)
y_pred = Activation('soft... | [
"def",
"bidirectional_rnn_model",
"(",
"input_dim",
",",
"units",
",",
"output_dim",
"=",
"29",
")",
":",
"input_data",
"=",
"Input",
"(",
"name",
"=",
"'the_input'",
",",
"shape",
"=",
"(",
"None",
",",
"input_dim",
")",
")",
"bidir_rnn",
"=",
"Bidirectio... | Build a bidirectional recurrent network for speech | [
"Build",
"a",
"bidirectional",
"recurrent",
"network",
"for",
"speech"
] | [
"\"\"\" Build a bidirectional recurrent network for speech\n \"\"\"",
"# Main acoustic input",
"# TODO: Add bidirectional recurrent layer",
"# TODO: Add a TimeDistributed(Dense(output_dim)) layer",
"# Add softmax activation layer",
"# Specify the model"
] | [
{
"param": "input_dim",
"type": null
},
{
"param": "units",
"type": null
},
{
"param": "output_dim",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "input_dim",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "units",
"type": null,
"docstring": null,
"docstring_toke... |
e1e43e3fc2fefaef575149971ce352819232021c | hammerd/NLP | 3.1-AIND-VUI-speech-recognition-project/sample_models.py | [
"MIT"
] | Python | final_model | <not_specific> | def final_model(input_dim, filters, kernel_size, conv_stride,
conv_border_mode, units, output_dim=29, maxpool_sz=3, recur_layers=1, dropout_cnn=0.3, dropout_rnn=0.3):
""" Build a deep network for speech
"""
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# TO... | Build a deep network for speech
| Build a deep network for speech | [
"Build",
"a",
"deep",
"network",
"for",
"speech"
] | def final_model(input_dim, filters, kernel_size, conv_stride,
conv_border_mode, units, output_dim=29, maxpool_sz=3, recur_layers=1, dropout_cnn=0.3, dropout_rnn=0.3):
input_data = Input(name='the_input', shape=(None, input_dim))
conv_1d = Conv1D(filters, kernel_size,
strides=conv_strid... | [
"def",
"final_model",
"(",
"input_dim",
",",
"filters",
",",
"kernel_size",
",",
"conv_stride",
",",
"conv_border_mode",
",",
"units",
",",
"output_dim",
"=",
"29",
",",
"maxpool_sz",
"=",
"3",
",",
"recur_layers",
"=",
"1",
",",
"dropout_cnn",
"=",
"0.3",
... | Build a deep network for speech | [
"Build",
"a",
"deep",
"network",
"for",
"speech"
] | [
"\"\"\" Build a deep network for speech \n \"\"\"",
"# Main acoustic input",
"# TODO: Specify the layers in your network",
"# Add convolutional layer",
"# Add batch normalization & Dropout",
"# Add max pooling layer",
"# Add bi-directional recurrent layer(s)",
"# TODO: Add a TimeDistributed(Dense(o... | [
{
"param": "input_dim",
"type": null
},
{
"param": "filters",
"type": null
},
{
"param": "kernel_size",
"type": null
},
{
"param": "conv_stride",
"type": null
},
{
"param": "conv_border_mode",
"type": null
},
{
"param": "units",
"type": null
},
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "input_dim",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "filters",
"type": null,
"docstring": null,
"docstring_to... |
88ca753ce5a71fe49bbcd7f9b75cdc76f143d0b6 | khangmach/kolibri | kolibri/core/auth/signals.py | [
"MIT"
] | Python | cascade_delete_membership | null | def cascade_delete_membership(sender, instance=None, *args, **kwargs):
"""
For a given membership instance and the collection associated with it,
we delete all membership objects whose collection is a child of the instance's collection.
"""
Membership.objects.filter(
collection__parent_id=in... |
For a given membership instance and the collection associated with it,
we delete all membership objects whose collection is a child of the instance's collection.
| For a given membership instance and the collection associated with it,
we delete all membership objects whose collection is a child of the instance's collection. | [
"For",
"a",
"given",
"membership",
"instance",
"and",
"the",
"collection",
"associated",
"with",
"it",
"we",
"delete",
"all",
"membership",
"objects",
"whose",
"collection",
"is",
"a",
"child",
"of",
"the",
"instance",
"'",
"s",
"collection",
"."
] | def cascade_delete_membership(sender, instance=None, *args, **kwargs):
Membership.objects.filter(
collection__parent_id=instance.collection_id, user=instance.user
).delete() | [
"def",
"cascade_delete_membership",
"(",
"sender",
",",
"instance",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"Membership",
".",
"objects",
".",
"filter",
"(",
"collection__parent_id",
"=",
"instance",
".",
"collection_id",
",",
"user",
"... | For a given membership instance and the collection associated with it,
we delete all membership objects whose collection is a child of the instance's collection. | [
"For",
"a",
"given",
"membership",
"instance",
"and",
"the",
"collection",
"associated",
"with",
"it",
"we",
"delete",
"all",
"membership",
"objects",
"whose",
"collection",
"is",
"a",
"child",
"of",
"the",
"instance",
"'",
"s",
"collection",
"."
] | [
"\"\"\"\n For a given membership instance and the collection associated with it,\n we delete all membership objects whose collection is a child of the instance's collection.\n \"\"\""
] | [
{
"param": "sender",
"type": null
},
{
"param": "instance",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sender",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "instance",
"type": null,
"docstring": null,
"docstring_toke... |
88ca753ce5a71fe49bbcd7f9b75cdc76f143d0b6 | khangmach/kolibri | kolibri/core/auth/signals.py | [
"MIT"
] | Python | cascade_delete_user | null | def cascade_delete_user(sender, instance=None, *args, **kwargs):
"""
For a given user, we delete all notifications
objects whose user is the instance's user.
"""
LearnerProgressNotification.objects.filter(user_id=instance.id).delete() |
For a given user, we delete all notifications
objects whose user is the instance's user.
| For a given user, we delete all notifications
objects whose user is the instance's user. | [
"For",
"a",
"given",
"user",
"we",
"delete",
"all",
"notifications",
"objects",
"whose",
"user",
"is",
"the",
"instance",
"'",
"s",
"user",
"."
] | def cascade_delete_user(sender, instance=None, *args, **kwargs):
LearnerProgressNotification.objects.filter(user_id=instance.id).delete() | [
"def",
"cascade_delete_user",
"(",
"sender",
",",
"instance",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"LearnerProgressNotification",
".",
"objects",
".",
"filter",
"(",
"user_id",
"=",
"instance",
".",
"id",
")",
".",
"delete",
"(",
... | For a given user, we delete all notifications
objects whose user is the instance's user. | [
"For",
"a",
"given",
"user",
"we",
"delete",
"all",
"notifications",
"objects",
"whose",
"user",
"is",
"the",
"instance",
"'",
"s",
"user",
"."
] | [
"\"\"\"\n For a given user, we delete all notifications\n objects whose user is the instance's user.\n \"\"\""
] | [
{
"param": "sender",
"type": null
},
{
"param": "instance",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "sender",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "instance",
"type": null,
"docstring": null,
"docstring_toke... |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | version_file | <not_specific> | def version_file():
"""
During test runtime, this path may differ because KOLIBRI_HOME is
regenerated
"""
from .conf import KOLIBRI_HOME
return os.path.join(KOLIBRI_HOME, ".data_version") |
During test runtime, this path may differ because KOLIBRI_HOME is
regenerated
| During test runtime, this path may differ because KOLIBRI_HOME is
regenerated | [
"During",
"test",
"runtime",
"this",
"path",
"may",
"differ",
"because",
"KOLIBRI_HOME",
"is",
"regenerated"
] | def version_file():
from .conf import KOLIBRI_HOME
return os.path.join(KOLIBRI_HOME, ".data_version") | [
"def",
"version_file",
"(",
")",
":",
"from",
".",
"conf",
"import",
"KOLIBRI_HOME",
"return",
"os",
".",
"path",
".",
"join",
"(",
"KOLIBRI_HOME",
",",
"\".data_version\"",
")"
] | During test runtime, this path may differ because KOLIBRI_HOME is
regenerated | [
"During",
"test",
"runtime",
"this",
"path",
"may",
"differ",
"because",
"KOLIBRI_HOME",
"is",
"regenerated"
] | [
"\"\"\"\n During test runtime, this path may differ because KOLIBRI_HOME is\n regenerated\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | initialize | null | def initialize(debug=False, skip_update=False):
"""
Currently, always called before running commands. This may change in case
commands that conflict with this behavior show up.
:param: debug: Tells initialization to setup logging etc.
"""
if not os.path.isfile(version_file()):
django.se... |
Currently, always called before running commands. This may change in case
commands that conflict with this behavior show up.
:param: debug: Tells initialization to setup logging etc.
| Currently, always called before running commands. This may change in case
commands that conflict with this behavior show up.
:param: debug: Tells initialization to setup logging etc. | [
"Currently",
"always",
"called",
"before",
"running",
"commands",
".",
"This",
"may",
"change",
"in",
"case",
"commands",
"that",
"conflict",
"with",
"this",
"behavior",
"show",
"up",
".",
":",
"param",
":",
"debug",
":",
"Tells",
"initialization",
"to",
"se... | def initialize(debug=False, skip_update=False):
if not os.path.isfile(version_file()):
django.setup()
setup_logging(debug=debug)
if not skip_update:
_first_run()
else:
from .conf import autoremove_unavailable_plugins, enable_default_plugins
autoremove_unavaila... | [
"def",
"initialize",
"(",
"debug",
"=",
"False",
",",
"skip_update",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"version_file",
"(",
")",
")",
":",
"django",
".",
"setup",
"(",
")",
"setup_logging",
"(",
"debug",
"=",... | Currently, always called before running commands. | [
"Currently",
"always",
"called",
"before",
"running",
"commands",
"."
] | [
"\"\"\"\n Currently, always called before running commands. This may change in case\n commands that conflict with this behavior show up.\n\n :param: debug: Tells initialization to setup logging etc.\n \"\"\"",
"# Do this here so that we can fix any issues with our configuration file before",
"# we a... | [
{
"param": "debug",
"type": null
},
{
"param": "skip_update",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "debug",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "skip_update",
"type": null,
"docstring": null,
"docstring_to... |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | _migrate_databases | null | def _migrate_databases():
"""
Try to migrate all active databases. This should not be called unless Django has
been initialized.
"""
from django.conf import settings
for database in settings.DATABASES:
call_command("migrate", interactive=False, database=database)
# load morango fix... |
Try to migrate all active databases. This should not be called unless Django has
been initialized.
| Try to migrate all active databases. This should not be called unless Django has
been initialized. | [
"Try",
"to",
"migrate",
"all",
"active",
"databases",
".",
"This",
"should",
"not",
"be",
"called",
"unless",
"Django",
"has",
"been",
"initialized",
"."
] | def _migrate_databases():
from django.conf import settings
for database in settings.DATABASES:
call_command("migrate", interactive=False, database=database)
call_command("loaddata", "scopedefinitions") | [
"def",
"_migrate_databases",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"for",
"database",
"in",
"settings",
".",
"DATABASES",
":",
"call_command",
"(",
"\"migrate\"",
",",
"interactive",
"=",
"False",
",",
"database",
"=",
"database",... | Try to migrate all active databases. | [
"Try",
"to",
"migrate",
"all",
"active",
"databases",
"."
] | [
"\"\"\"\n Try to migrate all active databases. This should not be called unless Django has\n been initialized.\n \"\"\"",
"# load morango fixtures needed for certificate related operations"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | update | null | def update():
"""
Called whenever a version change in kolibri is detected
TODO: We should look at version numbers of external plugins, too!
"""
logger.info("Running update routines for new version...")
# Need to do this here, before we run any Django management commands that
# import sett... |
Called whenever a version change in kolibri is detected
TODO: We should look at version numbers of external plugins, too!
| Called whenever a version change in kolibri is detected
TODO: We should look at version numbers of external plugins, too! | [
"Called",
"whenever",
"a",
"version",
"change",
"in",
"kolibri",
"is",
"detected",
"TODO",
":",
"We",
"should",
"look",
"at",
"version",
"numbers",
"of",
"external",
"plugins",
"too!"
] | def update():
logger.info("Running update routines for new version...")
call_command("collectstatic", interactive=False, verbosity=0)
from kolibri.core.settings import SKIP_AUTO_DATABASE_MIGRATION
if not SKIP_AUTO_DATABASE_MIGRATION:
_migrate_databases()
with open(version_file(), "w") as f:
... | [
"def",
"update",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Running update routines for new version...\"",
")",
"call_command",
"(",
"\"collectstatic\"",
",",
"interactive",
"=",
"False",
",",
"verbosity",
"=",
"0",
")",
"from",
"kolibri",
".",
"core",
".",
... | Called whenever a version change in kolibri is detected
TODO: We should look at version numbers of external plugins, too! | [
"Called",
"whenever",
"a",
"version",
"change",
"in",
"kolibri",
"is",
"detected",
"TODO",
":",
"We",
"should",
"look",
"at",
"version",
"numbers",
"of",
"external",
"plugins",
"too!"
] | [
"\"\"\"\n Called whenever a version change in kolibri is detected\n\n TODO: We should look at version numbers of external plugins, too!\n \"\"\"",
"# Need to do this here, before we run any Django management commands that",
"# import settings. Otherwise the updated configuration will not be used",
"#... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | start | null | def start(port=None, daemon=True):
"""
Start the server on given port.
:param: port: Port number (default: 8080)
:param: daemon: Fork to background process (default: True)
"""
run_cherrypy = conf.OPTIONS["Server"]["CHERRYPY_START"]
# In case some tests run start() function only
if not ... |
Start the server on given port.
:param: port: Port number (default: 8080)
:param: daemon: Fork to background process (default: True)
| Start the server on given port. | [
"Start",
"the",
"server",
"on",
"given",
"port",
"."
] | def start(port=None, daemon=True):
run_cherrypy = conf.OPTIONS["Server"]["CHERRYPY_START"]
if not isinstance(port, int):
port = _get_port(port)
if not daemon:
logger.info("Running 'kolibri start' in foreground...")
else:
logger.info("Running 'kolibri start' as daemon (system serv... | [
"def",
"start",
"(",
"port",
"=",
"None",
",",
"daemon",
"=",
"True",
")",
":",
"run_cherrypy",
"=",
"conf",
".",
"OPTIONS",
"[",
"\"Server\"",
"]",
"[",
"\"CHERRYPY_START\"",
"]",
"if",
"not",
"isinstance",
"(",
"port",
",",
"int",
")",
":",
"port",
... | Start the server on given port. | [
"Start",
"the",
"server",
"on",
"given",
"port",
"."
] | [
"\"\"\"\n Start the server on given port.\n\n :param: port: Port number (default: 8080)\n :param: daemon: Fork to background process (default: True)\n \"\"\"",
"# In case some tests run start() function only",
"# Daemonize at this point, no more user output is needed",
"# Truncate the file"
] | [
{
"param": "port",
"type": null
},
{
"param": "daemon",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "port",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "daemon",
"type": null,
"docstring": null,
"docstring_tokens":... |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | stop | null | def stop():
"""
Stops the server unless it isn't running
"""
try:
pid, __, __ = server.get_status()
server.stop(pid=pid)
stopped = True
if conf.OPTIONS["Server"]["CHERRYPY_START"]:
logger.info("Kolibri server has successfully been stopped.")
else:
... |
Stops the server unless it isn't running
| Stops the server unless it isn't running | [
"Stops",
"the",
"server",
"unless",
"it",
"isn",
"'",
"t",
"running"
] | def stop():
try:
pid, __, __ = server.get_status()
server.stop(pid=pid)
stopped = True
if conf.OPTIONS["Server"]["CHERRYPY_START"]:
logger.info("Kolibri server has successfully been stopped.")
else:
logger.info("Kolibri background services have success... | [
"def",
"stop",
"(",
")",
":",
"try",
":",
"pid",
",",
"__",
",",
"__",
"=",
"server",
".",
"get_status",
"(",
")",
"server",
".",
"stop",
"(",
"pid",
"=",
"pid",
")",
"stopped",
"=",
"True",
"if",
"conf",
".",
"OPTIONS",
"[",
"\"Server\"",
"]",
... | Stops the server unless it isn't running | [
"Stops",
"the",
"server",
"unless",
"it",
"isn",
"'",
"t",
"running"
] | [
"\"\"\"\n Stops the server unless it isn't running\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | status | <not_specific> | def status():
"""
Check the server's status. For possible statuses, see the status dictionary
status.codes
Status *always* outputs the current status in the first line of stderr.
The following lines contain optional information such as the addresses where
the server is listening.
TODO: We ... |
Check the server's status. For possible statuses, see the status dictionary
status.codes
Status *always* outputs the current status in the first line of stderr.
The following lines contain optional information such as the addresses where
the server is listening.
TODO: We can't guarantee the a... | Check the server's status. For possible statuses, see the status dictionary
status.codes
Status *always* outputs the current status in the first line of stderr.
The following lines contain optional information such as the addresses where
the server is listening.
We can't guarantee the above behavior because of the dj... | [
"Check",
"the",
"server",
"'",
"s",
"status",
".",
"For",
"possible",
"statuses",
"see",
"the",
"status",
"dictionary",
"status",
".",
"codes",
"Status",
"*",
"always",
"*",
"outputs",
"the",
"current",
"status",
"in",
"the",
"first",
"line",
"of",
"stderr... | def status():
status_code, urls = server.get_urls()
if status_code == server.STATUS_RUNNING:
sys.stderr.write("{msg:s} (0)\n".format(msg=status.codes[0]))
if urls:
sys.stderr.write("Kolibri running on:\n\n")
for addr in urls:
sys.stderr.write("\t{}\n".form... | [
"def",
"status",
"(",
")",
":",
"status_code",
",",
"urls",
"=",
"server",
".",
"get_urls",
"(",
")",
"if",
"status_code",
"==",
"server",
".",
"STATUS_RUNNING",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"{msg:s} (0)\\n\"",
".",
"format",
"(",
"msg... | Check the server's status. | [
"Check",
"the",
"server",
"'",
"s",
"status",
"."
] | [
"\"\"\"\n Check the server's status. For possible statuses, see the status dictionary\n status.codes\n\n Status *always* outputs the current status in the first line of stderr.\n The following lines contain optional information such as the addresses where\n the server is listening.\n\n TODO: We ca... | [] | {
"returns": [
{
"docstring": "status_code, key has description in status.codes",
"docstring_tokens": [
"status_code",
"key",
"has",
"description",
"in",
"status",
".",
"codes"
],
"type": null
}
],
"raises": [],
"par... |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | services | null | def services(daemon=True):
"""
Start the kolibri background services.
:param: daemon: Fork to background process (default: True)
"""
logger.info("Starting Kolibri background services")
# Daemonize at this point, no more user output is needed
if daemon:
kwargs = {}
# Trunc... |
Start the kolibri background services.
:param: daemon: Fork to background process (default: True)
| Start the kolibri background services.
:param: daemon: Fork to background process (default: True) | [
"Start",
"the",
"kolibri",
"background",
"services",
".",
":",
"param",
":",
"daemon",
":",
"Fork",
"to",
"background",
"process",
"(",
"default",
":",
"True",
")"
] | def services(daemon=True):
logger.info("Starting Kolibri background services")
if daemon:
kwargs = {}
if os.path.isfile(server.DAEMON_LOG):
open(server.DAEMON_LOG, "w").truncate()
logger.info("Going to daemon mode, logging to {0}".format(server.DAEMON_LOG))
kwargs["ou... | [
"def",
"services",
"(",
"daemon",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"\"Starting Kolibri background services\"",
")",
"if",
"daemon",
":",
"kwargs",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"server",
".",
"DAEMON_LOG",
... | Start the kolibri background services. | [
"Start",
"the",
"kolibri",
"background",
"services",
"."
] | [
"\"\"\"\n Start the kolibri background services.\n\n :param: daemon: Fork to background process (default: True)\n \"\"\"",
"# Daemonize at this point, no more user output is needed",
"# Truncate the file"
] | [
{
"param": "daemon",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "daemon",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | plugin | null | def plugin(plugin_name, **kwargs):
"""
Receives a plugin identifier and tries to load its main class. Calls class
functions.
"""
from kolibri.utils import conf
if kwargs.get("enable", False):
plugin_classes = get_kolibri_plugin(plugin_name)
for klass in plugin_classes:
... |
Receives a plugin identifier and tries to load its main class. Calls class
functions.
| Receives a plugin identifier and tries to load its main class. Calls class
functions. | [
"Receives",
"a",
"plugin",
"identifier",
"and",
"tries",
"to",
"load",
"its",
"main",
"class",
".",
"Calls",
"class",
"functions",
"."
] | def plugin(plugin_name, **kwargs):
from kolibri.utils import conf
if kwargs.get("enable", False):
plugin_classes = get_kolibri_plugin(plugin_name)
for klass in plugin_classes:
klass.enable()
if kwargs.get("disable", False):
try:
plugin_classes = get_kolibri_pl... | [
"def",
"plugin",
"(",
"plugin_name",
",",
"**",
"kwargs",
")",
":",
"from",
"kolibri",
".",
"utils",
"import",
"conf",
"if",
"kwargs",
".",
"get",
"(",
"\"enable\"",
",",
"False",
")",
":",
"plugin_classes",
"=",
"get_kolibri_plugin",
"(",
"plugin_name",
"... | Receives a plugin identifier and tries to load its main class. | [
"Receives",
"a",
"plugin",
"identifier",
"and",
"tries",
"to",
"load",
"its",
"main",
"class",
"."
] | [
"\"\"\"\n Receives a plugin identifier and tries to load its main class. Calls class\n functions.\n \"\"\""
] | [
{
"param": "plugin_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "plugin_name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | parse_args | <not_specific> | def parse_args(args=None):
"""
Parses arguments by invoking docopt. Arguments for django management
commands are split out before returning.
:returns: (parsed_arguments, raw_django_ars)
"""
if not args:
args = sys.argv[1:]
# Split out the parts of the argument list that we pass on... |
Parses arguments by invoking docopt. Arguments for django management
commands are split out before returning.
:returns: (parsed_arguments, raw_django_ars)
| Parses arguments by invoking docopt. Arguments for django management
commands are split out before returning. | [
"Parses",
"arguments",
"by",
"invoking",
"docopt",
".",
"Arguments",
"for",
"django",
"management",
"commands",
"are",
"split",
"out",
"before",
"returning",
"."
] | def parse_args(args=None):
if not args:
args = sys.argv[1:]
if "--" in args:
pivot = args.index("--")
args, django_args = args[:pivot], args[pivot + 1 :]
elif "manage" in args:
pivot = args.index("manage") + 2
args, django_args = args[:pivot], args[pivot:]
else:
... | [
"def",
"parse_args",
"(",
"args",
"=",
"None",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"if",
"\"--\"",
"in",
"args",
":",
"pivot",
"=",
"args",
".",
"index",
"(",
"\"--\"",
")",
"args",
",",
"dja... | Parses arguments by invoking docopt. | [
"Parses",
"arguments",
"by",
"invoking",
"docopt",
"."
] | [
"\"\"\"\n Parses arguments by invoking docopt. Arguments for django management\n commands are split out before returning.\n\n :returns: (parsed_arguments, raw_django_ars)\n \"\"\"",
"# Split out the parts of the argument list that we pass on to Django",
"# and don't feed to docopt.",
"# At the mom... | [
{
"param": "args",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
08578b15e547f0bd51341bf247da255d353b0970 | khangmach/kolibri | kolibri/utils/cli.py | [
"MIT"
] | Python | main | <not_specific> | def main(args=None): # noqa: max-complexity=13
"""
Kolibri's main function. Parses arguments and calls utility functions.
Utility functions should be callable for unit testing purposes, but remember
to use main() for integration tests in order to test the argument API.
"""
signal.signal(signal... |
Kolibri's main function. Parses arguments and calls utility functions.
Utility functions should be callable for unit testing purposes, but remember
to use main() for integration tests in order to test the argument API.
| Kolibri's main function. Parses arguments and calls utility functions.
Utility functions should be callable for unit testing purposes, but remember
to use main() for integration tests in order to test the argument API. | [
"Kolibri",
"'",
"s",
"main",
"function",
".",
"Parses",
"arguments",
"and",
"calls",
"utility",
"functions",
".",
"Utility",
"functions",
"should",
"be",
"callable",
"for",
"unit",
"testing",
"purposes",
"but",
"remember",
"to",
"use",
"main",
"()",
"for",
"... | def main(args=None):
signal.signal(signal.SIGINT, signal.SIG_DFL)
arguments, django_args = parse_args(args)
debug = arguments["--debug"]
if arguments["start"]:
port = _get_port(arguments["--port"])
if OPTIONS["Server"]["CHERRYPY_START"]:
check_other_kolibri_running(port)
... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_DFL",
")",
"arguments",
",",
"django_args",
"=",
"parse_args",
"(",
"args",
")",
"debug",
"=",
"arguments",
"[",
"\"--deb... | Kolibri's main function. | [
"Kolibri",
"'",
"s",
"main",
"function",
"."
] | [
"# noqa: max-complexity=13",
"\"\"\"\n Kolibri's main function. Parses arguments and calls utility functions.\n Utility functions should be callable for unit testing purposes, but remember\n to use main() for integration tests in order to test the argument API.\n \"\"\"",
"# On Mac, Python crashes w... | [
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2c154c0dda598d5d11fb8c4a327ae216a99594f9 | khangmach/kolibri | build_tools/install_cexts.py | [
"MIT"
] | Python | download_package | <not_specific> | def download_package(
path, platform, version, implementation, abi, name, pk_version, index_url, filename
):
"""
Download the package according to platform, python version, implementation and abi.
"""
if abi == "abi3":
return_code = download_package_abi3(
path,
platfo... |
Download the package according to platform, python version, implementation and abi.
| Download the package according to platform, python version, implementation and abi. | [
"Download",
"the",
"package",
"according",
"to",
"platform",
"python",
"version",
"implementation",
"and",
"abi",
"."
] | def download_package(
path, platform, version, implementation, abi, name, pk_version, index_url, filename
):
if abi == "abi3":
return_code = download_package_abi3(
path,
platform,
version,
implementation,
abi,
name,
pk_v... | [
"def",
"download_package",
"(",
"path",
",",
"platform",
",",
"version",
",",
"implementation",
",",
"abi",
",",
"name",
",",
"pk_version",
",",
"index_url",
",",
"filename",
")",
":",
"if",
"abi",
"==",
"\"abi3\"",
":",
"return_code",
"=",
"download_package... | Download the package according to platform, python version, implementation and abi. | [
"Download",
"the",
"package",
"according",
"to",
"platform",
"python",
"version",
"implementation",
"and",
"abi",
"."
] | [
"\"\"\"\n Download the package according to platform, python version, implementation and abi.\n \"\"\"",
"# When downloaded as a tar.gz, convert to a wheel file first.",
"# This is specifically for pycparser package."
] | [
{
"param": "path",
"type": null
},
{
"param": "platform",
"type": null
},
{
"param": "version",
"type": null
},
{
"param": "implementation",
"type": null
},
{
"param": "abi",
"type": null
},
{
"param": "name",
"type": null
},
{
"param": "pk... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "platform",
"type": null,
"docstring": null,
"docstring_tokens... |
2c154c0dda598d5d11fb8c4a327ae216a99594f9 | khangmach/kolibri | build_tools/install_cexts.py | [
"MIT"
] | Python | download_package_abi3 | <not_specific> | def download_package_abi3(
path, platform, version, implementation, abi, name, pk_version, index_url, filename
):
"""
Download the package when the abi tag is abi3. Install the package to get the dependecies
information from METADATA in dist-info and download all the dependecies.
"""
return_code... |
Download the package when the abi tag is abi3. Install the package to get the dependecies
information from METADATA in dist-info and download all the dependecies.
| Download the package when the abi tag is abi3. Install the package to get the dependecies
information from METADATA in dist-info and download all the dependecies. | [
"Download",
"the",
"package",
"when",
"the",
"abi",
"tag",
"is",
"abi3",
".",
"Install",
"the",
"package",
"to",
"get",
"the",
"dependecies",
"information",
"from",
"METADATA",
"in",
"dist",
"-",
"info",
"and",
"download",
"all",
"the",
"dependecies",
"."
] | def download_package_abi3(
path, platform, version, implementation, abi, name, pk_version, index_url, filename
):
return_code = subprocess.call(
[
"python",
"kolibripip.pex",
"download",
"-q",
"-d",
path,
"--platform",
... | [
"def",
"download_package_abi3",
"(",
"path",
",",
"platform",
",",
"version",
",",
"implementation",
",",
"abi",
",",
"name",
",",
"pk_version",
",",
"index_url",
",",
"filename",
")",
":",
"return_code",
"=",
"subprocess",
".",
"call",
"(",
"[",
"\"python\"... | Download the package when the abi tag is abi3. | [
"Download",
"the",
"package",
"when",
"the",
"abi",
"tag",
"is",
"abi3",
"."
] | [
"\"\"\"\n Download the package when the abi tag is abi3. Install the package to get the dependecies\n information from METADATA in dist-info and download all the dependecies.\n \"\"\"",
"# Open the METADATA file inside dist-info folder to find out dependencies."
] | [
{
"param": "path",
"type": null
},
{
"param": "platform",
"type": null
},
{
"param": "version",
"type": null
},
{
"param": "implementation",
"type": null
},
{
"param": "abi",
"type": null
},
{
"param": "name",
"type": null
},
{
"param": "pk... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "platform",
"type": null,
"docstring": null,
"docstring_tokens... |
2c154c0dda598d5d11fb8c4a327ae216a99594f9 | khangmach/kolibri | build_tools/install_cexts.py | [
"MIT"
] | Python | install_package_by_wheel | null | def install_package_by_wheel(path):
"""
Install the package using the downloaded wheel files.
"""
files = os.listdir(path)
for file in files:
# When the abi tag is abi3, the package has been installed, and a dist-info
# folder has been generated. Skip the installed package and remove... |
Install the package using the downloaded wheel files.
| Install the package using the downloaded wheel files. | [
"Install",
"the",
"package",
"using",
"the",
"downloaded",
"wheel",
"files",
"."
] | def install_package_by_wheel(path):
files = os.listdir(path)
for file in files:
if os.path.isdir(os.path.join(path, file)):
if file.endswith(".dist-info"):
shutil.rmtree(os.path.join(path, file))
continue
if "py2.py3-none-any" in file:
return_c... | [
"def",
"install_package_by_wheel",
"(",
"path",
")",
":",
"files",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"for",
"file",
"in",
"files",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"file",... | Install the package using the downloaded wheel files. | [
"Install",
"the",
"package",
"using",
"the",
"downloaded",
"wheel",
"files",
"."
] | [
"\"\"\"\n Install the package using the downloaded wheel files.\n \"\"\"",
"# When the abi tag is abi3, the package has been installed, and a dist-info",
"# folder has been generated. Skip the installed package and remove the",
"# dist-info folder.",
"# If the file is py2, py3 compatible, install it i... | [
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2c154c0dda598d5d11fb8c4a327ae216a99594f9 | khangmach/kolibri | build_tools/install_cexts.py | [
"MIT"
] | Python | parse_package_page | null | def parse_package_page(files, pk_version, index_url): # noqa C901
"""
Parse the PYPI and Piwheels link for the package and install the desired wheel files.
"""
for file in files.find_all("a"):
# We are not going to install the packages if they are:
# * not a whl file
# * no... |
Parse the PYPI and Piwheels link for the package and install the desired wheel files.
| Parse the PYPI and Piwheels link for the package and install the desired wheel files. | [
"Parse",
"the",
"PYPI",
"and",
"Piwheels",
"link",
"for",
"the",
"package",
"and",
"install",
"the",
"desired",
"wheel",
"files",
"."
] | def parse_package_page(files, pk_version, index_url):
for file in files.find_all("a"):
file_name_chunks = file.string.split("-")
if len(file_name_chunks) == 2:
continue
package_version = file_name_chunks[1]
package_name = file_name_chunks[0]
python_version = fil... | [
"def",
"parse_package_page",
"(",
"files",
",",
"pk_version",
",",
"index_url",
")",
":",
"for",
"file",
"in",
"files",
".",
"find_all",
"(",
"\"a\"",
")",
":",
"file_name_chunks",
"=",
"file",
".",
"string",
".",
"split",
"(",
"\"-\"",
")",
"if",
"len",... | Parse the PYPI and Piwheels link for the package and install the desired wheel files. | [
"Parse",
"the",
"PYPI",
"and",
"Piwheels",
"link",
"for",
"the",
"package",
"and",
"install",
"the",
"desired",
"wheel",
"files",
"."
] | [
"# noqa C901",
"\"\"\"\n Parse the PYPI and Piwheels link for the package and install the desired wheel files.\n \"\"\"",
"# We are not going to install the packages if they are:",
"# * not a whl file",
"# * not the version specified in requirements.txt",
"# * not python versions that kolibri ... | [
{
"param": "files",
"type": null
},
{
"param": "pk_version",
"type": null
},
{
"param": "index_url",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "files",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pk_version",
"type": null,
"docstring": null,
"docstring_tok... |
2c154c0dda598d5d11fb8c4a327ae216a99594f9 | khangmach/kolibri | build_tools/install_cexts.py | [
"MIT"
] | Python | install | null | def install(name, pk_version):
"""
Start installing from the pypi and piwheels pages of the package.
"""
links = [PYPI_DOWNLOAD, PIWHEEL_DOWNLOAD]
for link in links:
r = requests.get(link + name)
if r.status_code == 200:
files = BeautifulSoup(r.content, "html.parser")
... |
Start installing from the pypi and piwheels pages of the package.
| Start installing from the pypi and piwheels pages of the package. | [
"Start",
"installing",
"from",
"the",
"pypi",
"and",
"piwheels",
"pages",
"of",
"the",
"package",
"."
] | def install(name, pk_version):
links = [PYPI_DOWNLOAD, PIWHEEL_DOWNLOAD]
for link in links:
r = requests.get(link + name)
if r.status_code == 200:
files = BeautifulSoup(r.content, "html.parser")
parse_package_page(files, pk_version, link)
else:
sys.exi... | [
"def",
"install",
"(",
"name",
",",
"pk_version",
")",
":",
"links",
"=",
"[",
"PYPI_DOWNLOAD",
",",
"PIWHEEL_DOWNLOAD",
"]",
"for",
"link",
"in",
"links",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"link",
"+",
"name",
")",
"if",
"r",
".",
"status_... | Start installing from the pypi and piwheels pages of the package. | [
"Start",
"installing",
"from",
"the",
"pypi",
"and",
"piwheels",
"pages",
"of",
"the",
"package",
"."
] | [
"\"\"\"\n Start installing from the pypi and piwheels pages of the package.\n \"\"\""
] | [
{
"param": "name",
"type": null
},
{
"param": "pk_version",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pk_version",
"type": null,
"docstring": null,
"docstring_toke... |
2c154c0dda598d5d11fb8c4a327ae216a99594f9 | khangmach/kolibri | build_tools/install_cexts.py | [
"MIT"
] | Python | parse_requirements | null | def parse_requirements(args):
"""
Parse the requirements.txt to get packages' names and versions,
then install them.
"""
with open(args.file) as f:
for line in f:
char_list = line.split("==")
if len(char_list) == 2:
# Install package according to its n... |
Parse the requirements.txt to get packages' names and versions,
then install them.
| Parse the requirements.txt to get packages' names and versions,
then install them. | [
"Parse",
"the",
"requirements",
".",
"txt",
"to",
"get",
"packages",
"'",
"names",
"and",
"versions",
"then",
"install",
"them",
"."
] | def parse_requirements(args):
with open(args.file) as f:
for line in f:
char_list = line.split("==")
if len(char_list) == 2:
install(char_list[0].strip(), char_list[1].strip())
else:
sys.exit(
"\nName format in cext.txt ... | [
"def",
"parse_requirements",
"(",
"args",
")",
":",
"with",
"open",
"(",
"args",
".",
"file",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"char_list",
"=",
"line",
".",
"split",
"(",
"\"==\"",
")",
"if",
"len",
"(",
"char_list",
")",
"==",
... | Parse the requirements.txt to get packages' names and versions,
then install them. | [
"Parse",
"the",
"requirements",
".",
"txt",
"to",
"get",
"packages",
"'",
"names",
"and",
"versions",
"then",
"install",
"them",
"."
] | [
"\"\"\"\n Parse the requirements.txt to get packages' names and versions,\n then install them.\n \"\"\"",
"# Install package according to its name and version"
] | [
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
dad6ec22a0f094b1143050106c21f04539dd72f2 | khangmach/kolibri | kolibri/utils/compat.py | [
"MIT"
] | Python | module_exists | <not_specific> | def module_exists(module_path):
"""
Determines if a module exists without loading it (Python 3)
In Python 2, the module will be loaded
"""
if sys.version_info >= (3, 4):
from importlib.util import find_spec
try:
return find_spec(module_path) is not None
except Im... |
Determines if a module exists without loading it (Python 3)
In Python 2, the module will be loaded
| Determines if a module exists without loading it (Python 3)
In Python 2, the module will be loaded | [
"Determines",
"if",
"a",
"module",
"exists",
"without",
"loading",
"it",
"(",
"Python",
"3",
")",
"In",
"Python",
"2",
"the",
"module",
"will",
"be",
"loaded"
] | def module_exists(module_path):
if sys.version_info >= (3, 4):
from importlib.util import find_spec
try:
return find_spec(module_path) is not None
except ImportError:
return False
elif sys.version_info < (3,):
from imp import find_module
try:
... | [
"def",
"module_exists",
"(",
"module_path",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"4",
")",
":",
"from",
"importlib",
".",
"util",
"import",
"find_spec",
"try",
":",
"return",
"find_spec",
"(",
"module_path",
")",
"is",
"not",
... | Determines if a module exists without loading it (Python 3)
In Python 2, the module will be loaded | [
"Determines",
"if",
"a",
"module",
"exists",
"without",
"loading",
"it",
"(",
"Python",
"3",
")",
"In",
"Python",
"2",
"the",
"module",
"will",
"be",
"loaded"
] | [
"\"\"\"\n Determines if a module exists without loading it (Python 3)\n In Python 2, the module will be loaded\n \"\"\""
] | [
{
"param": "module_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "module_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
dad6ec22a0f094b1143050106c21f04539dd72f2 | khangmach/kolibri | kolibri/utils/compat.py | [
"MIT"
] | Python | parse_version | <not_specific> | def parse_version(v):
"""
In old versions of Python (for instance on Ubuntu 14.04),
pkg_resources.parse_version returns a tuple and not a version object.
"""
parsed = _parse_version(v)
return VersionCompat(parsed) |
In old versions of Python (for instance on Ubuntu 14.04),
pkg_resources.parse_version returns a tuple and not a version object.
| In old versions of Python (for instance on Ubuntu 14.04),
pkg_resources.parse_version returns a tuple and not a version object. | [
"In",
"old",
"versions",
"of",
"Python",
"(",
"for",
"instance",
"on",
"Ubuntu",
"14",
".",
"04",
")",
"pkg_resources",
".",
"parse_version",
"returns",
"a",
"tuple",
"and",
"not",
"a",
"version",
"object",
"."
] | def parse_version(v):
parsed = _parse_version(v)
return VersionCompat(parsed) | [
"def",
"parse_version",
"(",
"v",
")",
":",
"parsed",
"=",
"_parse_version",
"(",
"v",
")",
"return",
"VersionCompat",
"(",
"parsed",
")"
] | In old versions of Python (for instance on Ubuntu 14.04),
pkg_resources.parse_version returns a tuple and not a version object. | [
"In",
"old",
"versions",
"of",
"Python",
"(",
"for",
"instance",
"on",
"Ubuntu",
"14",
".",
"04",
")",
"pkg_resources",
".",
"parse_version",
"returns",
"a",
"tuple",
"and",
"not",
"a",
"version",
"object",
"."
] | [
"\"\"\"\n In old versions of Python (for instance on Ubuntu 14.04),\n pkg_resources.parse_version returns a tuple and not a version object.\n \"\"\""
] | [
{
"param": "v",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "v",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
0310dc56daea19c5cad387b30a4c9fe13d0ef89e | khangmach/kolibri | kolibri/core/logger/migrations/0004_tidy_progress_range.py | [
"MIT"
] | Python | tidy_progress_range | null | def tidy_progress_range(apps, schema_editor):
"""
Tidies progress ranges because a bug had caused them to go out of range
"""
ContentSessionLog = apps.get_model("logger", "ContentSessionLog")
ContentSummaryLog = apps.get_model("logger", "ContentSummaryLog")
# Not knowing how floating points wil... |
Tidies progress ranges because a bug had caused them to go out of range
| Tidies progress ranges because a bug had caused them to go out of range | [
"Tidies",
"progress",
"ranges",
"because",
"a",
"bug",
"had",
"caused",
"them",
"to",
"go",
"out",
"of",
"range"
] | def tidy_progress_range(apps, schema_editor):
ContentSessionLog = apps.get_model("logger", "ContentSessionLog")
ContentSummaryLog = apps.get_model("logger", "ContentSummaryLog")
ContentSessionLog.objects.filter(progress__lt=0).update(progress=0.0)
ContentSummaryLog.objects.filter(progress__lt=0).update(... | [
"def",
"tidy_progress_range",
"(",
"apps",
",",
"schema_editor",
")",
":",
"ContentSessionLog",
"=",
"apps",
".",
"get_model",
"(",
"\"logger\"",
",",
"\"ContentSessionLog\"",
")",
"ContentSummaryLog",
"=",
"apps",
".",
"get_model",
"(",
"\"logger\"",
",",
"\"Cont... | Tidies progress ranges because a bug had caused them to go out of range | [
"Tidies",
"progress",
"ranges",
"because",
"a",
"bug",
"had",
"caused",
"them",
"to",
"go",
"out",
"of",
"range"
] | [
"\"\"\"\n Tidies progress ranges because a bug had caused them to go out of range\n \"\"\"",
"# Not knowing how floating points will behave in the local database,",
"# 1.0 might become bigger than 1.0!!"
] | [
{
"param": "apps",
"type": null
},
{
"param": "schema_editor",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "apps",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "schema_editor",
"type": null,
"docstring": null,
"docstring_t... |
79163a3061bc6da74747984c598a394c3057489a | khangmach/kolibri | kolibri/core/public/api.py | [
"MIT"
] | Python | list | <not_specific> | def list(self, request):
"""Returns metadata information about the device"""
instance_model = InstanceIDModel.get_or_create_current_instance()[0]
info = {
"application": "kolibri",
"kolibri_version": kolibri.__version__,
"instance_id": instance_model.id,
... | Returns metadata information about the device | Returns metadata information about the device | [
"Returns",
"metadata",
"information",
"about",
"the",
"device"
] | def list(self, request):
instance_model = InstanceIDModel.get_or_create_current_instance()[0]
info = {
"application": "kolibri",
"kolibri_version": kolibri.__version__,
"instance_id": instance_model.id,
"device_name": instance_model.hostname,
"... | [
"def",
"list",
"(",
"self",
",",
"request",
")",
":",
"instance_model",
"=",
"InstanceIDModel",
".",
"get_or_create_current_instance",
"(",
")",
"[",
"0",
"]",
"info",
"=",
"{",
"\"application\"",
":",
"\"kolibri\"",
",",
"\"kolibri_version\"",
":",
"kolibri",
... | Returns metadata information about the device | [
"Returns",
"metadata",
"information",
"about",
"the",
"device"
] | [
"\"\"\"Returns metadata information about the device\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "request",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "request",
"type": null,
"docstring": null,
"docstring_tokens"... |
fa1d46c6ba75a2d113f62b445cb5f3a816857314 | khangmach/kolibri | kolibri/utils/env.py | [
"MIT"
] | Python | prepend_cext_path | null | def prepend_cext_path(dist_path):
"""
Calculate the directory of C extensions and add it to sys.path if exists.
"""
python_version = "cp" + str(sys.version_info.major) + str(sys.version_info.minor)
system_name = platform.system()
machine_name = platform.machine()
dirname = os.path.join(dist_... |
Calculate the directory of C extensions and add it to sys.path if exists.
| Calculate the directory of C extensions and add it to sys.path if exists. | [
"Calculate",
"the",
"directory",
"of",
"C",
"extensions",
"and",
"add",
"it",
"to",
"sys",
".",
"path",
"if",
"exists",
"."
] | def prepend_cext_path(dist_path):
python_version = "cp" + str(sys.version_info.major) + str(sys.version_info.minor)
system_name = platform.system()
machine_name = platform.machine()
dirname = os.path.join(dist_path, "cext", python_version, system_name)
if system_name == "Linux" and int(python_versio... | [
"def",
"prepend_cext_path",
"(",
"dist_path",
")",
":",
"python_version",
"=",
"\"cp\"",
"+",
"str",
"(",
"sys",
".",
"version_info",
".",
"major",
")",
"+",
"str",
"(",
"sys",
".",
"version_info",
".",
"minor",
")",
"system_name",
"=",
"platform",
".",
... | Calculate the directory of C extensions and add it to sys.path if exists. | [
"Calculate",
"the",
"directory",
"of",
"C",
"extensions",
"and",
"add",
"it",
"to",
"sys",
".",
"path",
"if",
"exists",
"."
] | [
"\"\"\"\n Calculate the directory of C extensions and add it to sys.path if exists.\n \"\"\"",
"# For Linux system with cpython<3.3, there could be abi tags 'm' and 'mu'",
"# encode with ucs2",
"# encode with ucs4",
"# If the directory of platform-specific cextensions (cryptography) exists,",
"# add... | [
{
"param": "dist_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dist_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
26fecbeb3a29e8a46314c8231f1b61db7f88aeb5 | khangmach/kolibri | kolibri/plugins/base.py | [
"MIT"
] | Python | _module_path | <not_specific> | def _module_path(cls):
"""
Returns the path of the class inheriting this classmethod.
There is no such thing as Class properties, that's why it's implemented
as such.
Used in KolibriPluginBase._installed_apps_add
"""
return ".".join(cls.__module__.split(".")[:-1]... |
Returns the path of the class inheriting this classmethod.
There is no such thing as Class properties, that's why it's implemented
as such.
Used in KolibriPluginBase._installed_apps_add
| Returns the path of the class inheriting this classmethod.
There is no such thing as Class properties, that's why it's implemented
as such.
| [
"Returns",
"the",
"path",
"of",
"the",
"class",
"inheriting",
"this",
"classmethod",
".",
"There",
"is",
"no",
"such",
"thing",
"as",
"Class",
"properties",
"that",
"'",
"s",
"why",
"it",
"'",
"s",
"implemented",
"as",
"such",
"."
] | def _module_path(cls):
return ".".join(cls.__module__.split(".")[:-1]) | [
"def",
"_module_path",
"(",
"cls",
")",
":",
"return",
"\".\"",
".",
"join",
"(",
"cls",
".",
"__module__",
".",
"split",
"(",
"\".\"",
")",
"[",
":",
"-",
"1",
"]",
")"
] | Returns the path of the class inheriting this classmethod. | [
"Returns",
"the",
"path",
"of",
"the",
"class",
"inheriting",
"this",
"classmethod",
"."
] | [
"\"\"\"\n Returns the path of the class inheriting this classmethod.\n There is no such thing as Class properties, that's why it's implemented\n as such.\n\n Used in KolibriPluginBase._installed_apps_add\n \"\"\""
] | [
{
"param": "cls",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
26fecbeb3a29e8a46314c8231f1b61db7f88aeb5 | khangmach/kolibri | kolibri/plugins/base.py | [
"MIT"
] | Python | _installed_apps_add | null | def _installed_apps_add(cls):
"""Call this from your enable() method to have the plugin automatically
added to Kolibri configuration"""
module_path = cls._module_path()
if module_path not in config["INSTALLED_APPS"]:
config["INSTALLED_APPS"].append(module_path)
else:
... | Call this from your enable() method to have the plugin automatically
added to Kolibri configuration | Call this from your enable() method to have the plugin automatically
added to Kolibri configuration | [
"Call",
"this",
"from",
"your",
"enable",
"()",
"method",
"to",
"have",
"the",
"plugin",
"automatically",
"added",
"to",
"Kolibri",
"configuration"
] | def _installed_apps_add(cls):
module_path = cls._module_path()
if module_path not in config["INSTALLED_APPS"]:
config["INSTALLED_APPS"].append(module_path)
else:
logger.warning("{} already enabled".format(module_path)) | [
"def",
"_installed_apps_add",
"(",
"cls",
")",
":",
"module_path",
"=",
"cls",
".",
"_module_path",
"(",
")",
"if",
"module_path",
"not",
"in",
"config",
"[",
"\"INSTALLED_APPS\"",
"]",
":",
"config",
"[",
"\"INSTALLED_APPS\"",
"]",
".",
"append",
"(",
"modu... | Call this from your enable() method to have the plugin automatically
added to Kolibri configuration | [
"Call",
"this",
"from",
"your",
"enable",
"()",
"method",
"to",
"have",
"the",
"plugin",
"automatically",
"added",
"to",
"Kolibri",
"configuration"
] | [
"\"\"\"Call this from your enable() method to have the plugin automatically\n added to Kolibri configuration\"\"\""
] | [
{
"param": "cls",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
26fecbeb3a29e8a46314c8231f1b61db7f88aeb5 | khangmach/kolibri | kolibri/plugins/base.py | [
"MIT"
] | Python | _installed_apps_remove | null | def _installed_apps_remove(cls):
"""Call this from your enable() method to have the plugin automatically
added to Kolibri configuration"""
module_path = cls._module_path()
if module_path in config["INSTALLED_APPS"]:
config["INSTALLED_APPS"].remove(module_path)
else:
... | Call this from your enable() method to have the plugin automatically
added to Kolibri configuration | Call this from your enable() method to have the plugin automatically
added to Kolibri configuration | [
"Call",
"this",
"from",
"your",
"enable",
"()",
"method",
"to",
"have",
"the",
"plugin",
"automatically",
"added",
"to",
"Kolibri",
"configuration"
] | def _installed_apps_remove(cls):
module_path = cls._module_path()
if module_path in config["INSTALLED_APPS"]:
config["INSTALLED_APPS"].remove(module_path)
else:
logger.warning("{} already disabled".format(module_path)) | [
"def",
"_installed_apps_remove",
"(",
"cls",
")",
":",
"module_path",
"=",
"cls",
".",
"_module_path",
"(",
")",
"if",
"module_path",
"in",
"config",
"[",
"\"INSTALLED_APPS\"",
"]",
":",
"config",
"[",
"\"INSTALLED_APPS\"",
"]",
".",
"remove",
"(",
"module_pat... | Call this from your enable() method to have the plugin automatically
added to Kolibri configuration | [
"Call",
"this",
"from",
"your",
"enable",
"()",
"method",
"to",
"have",
"the",
"plugin",
"automatically",
"added",
"to",
"Kolibri",
"configuration"
] | [
"\"\"\"Call this from your enable() method to have the plugin automatically\n added to Kolibri configuration\"\"\""
] | [
{
"param": "cls",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
26fecbeb3a29e8a46314c8231f1b61db7f88aeb5 | khangmach/kolibri | kolibri/plugins/base.py | [
"MIT"
] | Python | url_namespace | <not_specific> | def url_namespace(self):
"""
Used for the ``namespace`` argument when including the plugin's
urlpatterns. By default, returns a lowercase of the class name.
"""
return self.__class__.__name__.lower() |
Used for the ``namespace`` argument when including the plugin's
urlpatterns. By default, returns a lowercase of the class name.
| Used for the ``namespace`` argument when including the plugin's
urlpatterns. By default, returns a lowercase of the class name. | [
"Used",
"for",
"the",
"`",
"`",
"namespace",
"`",
"`",
"argument",
"when",
"including",
"the",
"plugin",
"'",
"s",
"urlpatterns",
".",
"By",
"default",
"returns",
"a",
"lowercase",
"of",
"the",
"class",
"name",
"."
] | def url_namespace(self):
return self.__class__.__name__.lower() | [
"def",
"url_namespace",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")"
] | Used for the ``namespace`` argument when including the plugin's
urlpatterns. | [
"Used",
"for",
"the",
"`",
"`",
"namespace",
"`",
"`",
"argument",
"when",
"including",
"the",
"plugin",
"'",
"s",
"urlpatterns",
"."
] | [
"\"\"\"\n Used for the ``namespace`` argument when including the plugin's\n urlpatterns. By default, returns a lowercase of the class name.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
6d137040c0c7dc9486e3fed7a16416eb64054e14 | khangmach/kolibri | kolibri/core/discovery/utils/filesystem/__init__.py | [
"MIT"
] | Python | enumerate_mounted_disk_partitions | <not_specific> | def enumerate_mounted_disk_partitions():
"""
Searches the local device for attached partitions/drives, and computes metadata about each one.
Returns a dict that maps drive IDs to DriveData objects containing metadata about each drive.
Note that drives for which the current user does not have read permis... |
Searches the local device for attached partitions/drives, and computes metadata about each one.
Returns a dict that maps drive IDs to DriveData objects containing metadata about each drive.
Note that drives for which the current user does not have read permissions are not included.
| Searches the local device for attached partitions/drives, and computes metadata about each one.
Returns a dict that maps drive IDs to DriveData objects containing metadata about each drive.
Note that drives for which the current user does not have read permissions are not included. | [
"Searches",
"the",
"local",
"device",
"for",
"attached",
"partitions",
"/",
"drives",
"and",
"computes",
"metadata",
"about",
"each",
"one",
".",
"Returns",
"a",
"dict",
"that",
"maps",
"drive",
"IDs",
"to",
"DriveData",
"objects",
"containing",
"metadata",
"a... | def enumerate_mounted_disk_partitions():
if sys.platform == "win32":
drive_list = get_drive_list_windows()
else:
drive_list = get_drive_list_posix()
drives = {}
for drive in drive_list:
path = drive["path"]
drive_id = hashlib.sha1((drive["guid"] or path).encode("utf-8")).... | [
"def",
"enumerate_mounted_disk_partitions",
"(",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"drive_list",
"=",
"get_drive_list_windows",
"(",
")",
"else",
":",
"drive_list",
"=",
"get_drive_list_posix",
"(",
")",
"drives",
"=",
"{",
"}",
"... | Searches the local device for attached partitions/drives, and computes metadata about each one. | [
"Searches",
"the",
"local",
"device",
"for",
"attached",
"partitions",
"/",
"drives",
"and",
"computes",
"metadata",
"about",
"each",
"one",
"."
] | [
"\"\"\"\n Searches the local device for attached partitions/drives, and computes metadata about each one.\n Returns a dict that maps drive IDs to DriveData objects containing metadata about each drive.\n Note that drives for which the current user does not have read permissions are not included.\n \"\"\... | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
0e328942d96fef56ebc317029aebe6196f2226da | khangmach/kolibri | kolibri/utils/pskolibri/_pslinux.py | [
"MIT"
] | Python | cpu_count_logical | <not_specific> | def cpu_count_logical():
"""Return the number of logical CPUs in the system."""
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
# as a second fallback we try to parse /proc/cpuinfo
num = 0
with open_binary("%s/cpuinfo" % get_procfs_path()) as f:
f... | Return the number of logical CPUs in the system. | Return the number of logical CPUs in the system. | [
"Return",
"the",
"number",
"of",
"logical",
"CPUs",
"in",
"the",
"system",
"."
] | def cpu_count_logical():
try:
return os.sysconf("SC_NPROCESSORS_ONLN")
except ValueError:
num = 0
with open_binary("%s/cpuinfo" % get_procfs_path()) as f:
for line in f:
if line.lower().startswith(b"processor"):
num += 1
if num == 0... | [
"def",
"cpu_count_logical",
"(",
")",
":",
"try",
":",
"return",
"os",
".",
"sysconf",
"(",
"\"SC_NPROCESSORS_ONLN\"",
")",
"except",
"ValueError",
":",
"num",
"=",
"0",
"with",
"open_binary",
"(",
"\"%s/cpuinfo\"",
"%",
"get_procfs_path",
"(",
")",
")",
"as... | Return the number of logical CPUs in the system. | [
"Return",
"the",
"number",
"of",
"logical",
"CPUs",
"in",
"the",
"system",
"."
] | [
"\"\"\"Return the number of logical CPUs in the system.\"\"\"",
"# as a second fallback we try to parse /proc/cpuinfo",
"# unknown format (e.g. amrel/sparc architectures), see:",
"# https://github.com/giampaolo/psutil/issues/200",
"# try to parse /proc/stat as a last resort",
"# mimic os.cpu_count()"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
0e328942d96fef56ebc317029aebe6196f2226da | khangmach/kolibri | kolibri/utils/pskolibri/_pslinux.py | [
"MIT"
] | Python | boot_time | <not_specific> | def boot_time():
"""Return the system boot time expressed in seconds since the epoch."""
global BOOT_TIME
path = "%s/stat" % get_procfs_path()
with open_binary(path) as f:
for line in f:
if line.startswith(b"btime"):
ret = float(line.strip().split()[1])
... | Return the system boot time expressed in seconds since the epoch. | Return the system boot time expressed in seconds since the epoch. | [
"Return",
"the",
"system",
"boot",
"time",
"expressed",
"in",
"seconds",
"since",
"the",
"epoch",
"."
] | def boot_time():
global BOOT_TIME
path = "%s/stat" % get_procfs_path()
with open_binary(path) as f:
for line in f:
if line.startswith(b"btime"):
ret = float(line.strip().split()[1])
BOOT_TIME = ret
return ret
raise RuntimeError("lin... | [
"def",
"boot_time",
"(",
")",
":",
"global",
"BOOT_TIME",
"path",
"=",
"\"%s/stat\"",
"%",
"get_procfs_path",
"(",
")",
"with",
"open_binary",
"(",
"path",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
".",
"startswith",
"(",
"b\"bt... | Return the system boot time expressed in seconds since the epoch. | [
"Return",
"the",
"system",
"boot",
"time",
"expressed",
"in",
"seconds",
"since",
"the",
"epoch",
"."
] | [
"\"\"\"Return the system boot time expressed in seconds since the epoch.\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
107525ec2a112ce3bc83d20f5ffc3c14b7b5bbfd | khangmach/kolibri | kolibri/plugins/coach/test/helpers.py | [
"MIT"
] | Python | create_learner | <not_specific> | def create_learner(username, password, facility, classroom=None, learner_group=None):
"""
Create a facility learner.
Assign them a classroom if specified.
Assign them a learner group if specified.
"""
learner = FacilityUser.objects.create(username=username, facility=facility)
learner.set_pa... |
Create a facility learner.
Assign them a classroom if specified.
Assign them a learner group if specified.
| Create a facility learner.
Assign them a classroom if specified.
Assign them a learner group if specified. | [
"Create",
"a",
"facility",
"learner",
".",
"Assign",
"them",
"a",
"classroom",
"if",
"specified",
".",
"Assign",
"them",
"a",
"learner",
"group",
"if",
"specified",
"."
] | def create_learner(username, password, facility, classroom=None, learner_group=None):
learner = FacilityUser.objects.create(username=username, facility=facility)
learner.set_password(password)
learner.save()
if classroom is not None:
classroom.add_member(learner)
if learner_group is not None... | [
"def",
"create_learner",
"(",
"username",
",",
"password",
",",
"facility",
",",
"classroom",
"=",
"None",
",",
"learner_group",
"=",
"None",
")",
":",
"learner",
"=",
"FacilityUser",
".",
"objects",
".",
"create",
"(",
"username",
"=",
"username",
",",
"f... | Create a facility learner. | [
"Create",
"a",
"facility",
"learner",
"."
] | [
"\"\"\"\n Create a facility learner.\n Assign them a classroom if specified.\n Assign them a learner group if specified.\n \"\"\""
] | [
{
"param": "username",
"type": null
},
{
"param": "password",
"type": null
},
{
"param": "facility",
"type": null
},
{
"param": "classroom",
"type": null
},
{
"param": "learner_group",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "username",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "password",
"type": null,
"docstring": null,
"docstring_to... |
107525ec2a112ce3bc83d20f5ffc3c14b7b5bbfd | khangmach/kolibri | kolibri/plugins/coach/test/helpers.py | [
"MIT"
] | Python | create_coach | <not_specific> | def create_coach(username, password, facility, classroom=None, is_facility_coach=False):
"""
Create a coach.
Assign them a classroom if specified.
Grant facility permissions if is_facility_coach is True.
"""
coach = FacilityUser.objects.create(username=username, facility=facility)
coach.set... |
Create a coach.
Assign them a classroom if specified.
Grant facility permissions if is_facility_coach is True.
| Create a coach.
Assign them a classroom if specified.
Grant facility permissions if is_facility_coach is True. | [
"Create",
"a",
"coach",
".",
"Assign",
"them",
"a",
"classroom",
"if",
"specified",
".",
"Grant",
"facility",
"permissions",
"if",
"is_facility_coach",
"is",
"True",
"."
] | def create_coach(username, password, facility, classroom=None, is_facility_coach=False):
coach = FacilityUser.objects.create(username=username, facility=facility)
coach.set_password(password)
coach.save()
if classroom is not None:
classroom.add_coach(coach)
if is_facility_coach:
faci... | [
"def",
"create_coach",
"(",
"username",
",",
"password",
",",
"facility",
",",
"classroom",
"=",
"None",
",",
"is_facility_coach",
"=",
"False",
")",
":",
"coach",
"=",
"FacilityUser",
".",
"objects",
".",
"create",
"(",
"username",
"=",
"username",
",",
"... | Create a coach. | [
"Create",
"a",
"coach",
"."
] | [
"\"\"\"\n Create a coach.\n Assign them a classroom if specified.\n Grant facility permissions if is_facility_coach is True.\n \"\"\""
] | [
{
"param": "username",
"type": null
},
{
"param": "password",
"type": null
},
{
"param": "facility",
"type": null
},
{
"param": "classroom",
"type": null
},
{
"param": "is_facility_coach",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "username",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "password",
"type": null,
"docstring": null,
"docstring_to... |
740c4b49731161c2a5c6a2e6b3f4f3a64127d03e | khangmach/kolibri | kolibri/utils/pskolibri/_pswindows.py | [
"MIT"
] | Python | cpu_times | <not_specific> | def cpu_times():
"""Return system CPU times as a named tuple."""
idle_time, kernel_time, user_time = FILETIME(), FILETIME(), FILETIME()
kernel32.GetSystemTimes(
ctypes.byref(idle_time), ctypes.byref(kernel_time), ctypes.byref(user_time)
)
idle = HI_T * idle_time.dwHighDateTime + LO_T * idle... | Return system CPU times as a named tuple. | Return system CPU times as a named tuple. | [
"Return",
"system",
"CPU",
"times",
"as",
"a",
"named",
"tuple",
"."
] | def cpu_times():
idle_time, kernel_time, user_time = FILETIME(), FILETIME(), FILETIME()
kernel32.GetSystemTimes(
ctypes.byref(idle_time), ctypes.byref(kernel_time), ctypes.byref(user_time)
)
idle = HI_T * idle_time.dwHighDateTime + LO_T * idle_time.dwLowDateTime
user = HI_T * user_time.dwHig... | [
"def",
"cpu_times",
"(",
")",
":",
"idle_time",
",",
"kernel_time",
",",
"user_time",
"=",
"FILETIME",
"(",
")",
",",
"FILETIME",
"(",
")",
",",
"FILETIME",
"(",
")",
"kernel32",
".",
"GetSystemTimes",
"(",
"ctypes",
".",
"byref",
"(",
"idle_time",
")",
... | Return system CPU times as a named tuple. | [
"Return",
"system",
"CPU",
"times",
"as",
"a",
"named",
"tuple",
"."
] | [
"\"\"\"Return system CPU times as a named tuple.\"\"\"",
"# Kernel time includes idle time.",
"# We return only busy kernel time subtracting idle time from",
"# kernel time."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
740c4b49731161c2a5c6a2e6b3f4f3a64127d03e | khangmach/kolibri | kolibri/utils/pskolibri/_pswindows.py | [
"MIT"
] | Python | virtual_memory | <not_specific> | def virtual_memory():
"""System virtual memory as a namedtuple."""
meminfo = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(meminfo))
total = meminfo.ullTotalPhys
avail = meminfo.ullAvailPhys
used = total - avail
return svmem(total, used) | System virtual memory as a namedtuple. | System virtual memory as a namedtuple. | [
"System",
"virtual",
"memory",
"as",
"a",
"namedtuple",
"."
] | def virtual_memory():
meminfo = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(meminfo))
total = meminfo.ullTotalPhys
avail = meminfo.ullAvailPhys
used = total - avail
return svmem(total, used) | [
"def",
"virtual_memory",
"(",
")",
":",
"meminfo",
"=",
"MEMORYSTATUSEX",
"(",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GlobalMemoryStatusEx",
"(",
"ctypes",
".",
"byref",
"(",
"meminfo",
")",
")",
"total",
"=",
"meminfo",
".",
"ullTotalPhys",
... | System virtual memory as a namedtuple. | [
"System",
"virtual",
"memory",
"as",
"a",
"namedtuple",
"."
] | [
"\"\"\"System virtual memory as a namedtuple.\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
740c4b49731161c2a5c6a2e6b3f4f3a64127d03e | khangmach/kolibri | kolibri/utils/pskolibri/_pswindows.py | [
"MIT"
] | Python | pids | <not_specific> | def pids():
"""Returns a list of PIDs currently running on the system."""
length = 4096
PID_SIZE = ctypes.sizeof(wintypes.DWORD)
while True:
pids = (wintypes.DWORD * length)()
cb = ctypes.sizeof(pids)
cbret = wintypes.DWORD()
psapi.EnumProcesses(pids, cb, ctypes.byref(cbr... | Returns a list of PIDs currently running on the system. | Returns a list of PIDs currently running on the system. | [
"Returns",
"a",
"list",
"of",
"PIDs",
"currently",
"running",
"on",
"the",
"system",
"."
] | def pids():
length = 4096
PID_SIZE = ctypes.sizeof(wintypes.DWORD)
while True:
pids = (wintypes.DWORD * length)()
cb = ctypes.sizeof(pids)
cbret = wintypes.DWORD()
psapi.EnumProcesses(pids, cb, ctypes.byref(cbret))
if cbret.value < cb:
length = cbret.value... | [
"def",
"pids",
"(",
")",
":",
"length",
"=",
"4096",
"PID_SIZE",
"=",
"ctypes",
".",
"sizeof",
"(",
"wintypes",
".",
"DWORD",
")",
"while",
"True",
":",
"pids",
"=",
"(",
"wintypes",
".",
"DWORD",
"*",
"length",
")",
"(",
")",
"cb",
"=",
"ctypes",
... | Returns a list of PIDs currently running on the system. | [
"Returns",
"a",
"list",
"of",
"PIDs",
"currently",
"running",
"on",
"the",
"system",
"."
] | [
"\"\"\"Returns a list of PIDs currently running on the system.\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
9f4a867e0c1ca1c61aea43fc8c70629f8cbbebfc | khangmach/kolibri | kolibri/core/content/management/commands/content.py | [
"MIT"
] | Python | migrate | null | def migrate(self, src, dst):
"""
Migrate the content from current content directory to the destination.
"""
logger.info("Current content directory is {}".format(src))
logger.info("Migrating the content into {}".format(dst))
databases_src = os.path.join(src, "databases")
... |
Migrate the content from current content directory to the destination.
| Migrate the content from current content directory to the destination. | [
"Migrate",
"the",
"content",
"from",
"current",
"content",
"directory",
"to",
"the",
"destination",
"."
] | def migrate(self, src, dst):
logger.info("Current content directory is {}".format(src))
logger.info("Migrating the content into {}".format(dst))
databases_src = os.path.join(src, "databases")
databases_dst = os.path.join(dst, "databases")
storage_src = os.path.join(src, "storage"... | [
"def",
"migrate",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"logger",
".",
"info",
"(",
"\"Current content directory is {}\"",
".",
"format",
"(",
"src",
")",
")",
"logger",
".",
"info",
"(",
"\"Migrating the content into {}\"",
".",
"format",
"(",
"dst... | Migrate the content from current content directory to the destination. | [
"Migrate",
"the",
"content",
"from",
"current",
"content",
"directory",
"to",
"the",
"destination",
"."
] | [
"\"\"\"\n Migrate the content from current content directory to the destination.\n \"\"\"",
"# Check if destination has content by checking if databases folder is not empty",
"# If destination has content inside, ask users if they want to overwrite content",
"# copy the databases folder",
"# c... | [
{
"param": "self",
"type": null
},
{
"param": "src",
"type": null
},
{
"param": "dst",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "src",
"type": null,
"docstring": null,
"docstring_tokens": []... |
9f4a867e0c1ca1c61aea43fc8c70629f8cbbebfc | khangmach/kolibri | kolibri/core/content/management/commands/content.py | [
"MIT"
] | Python | ask_user_overwrite_or_keep_content | null | def ask_user_overwrite_or_keep_content(self, src, dst):
"""
If destination has content inside, ask users if they want to overwrite
content in the destination. We will copy the content to destination
depending on the user response.
"""
user_answer = input(
self... |
If destination has content inside, ask users if they want to overwrite
content in the destination. We will copy the content to destination
depending on the user response.
| If destination has content inside, ask users if they want to overwrite
content in the destination. We will copy the content to destination
depending on the user response. | [
"If",
"destination",
"has",
"content",
"inside",
"ask",
"users",
"if",
"they",
"want",
"to",
"overwrite",
"content",
"in",
"the",
"destination",
".",
"We",
"will",
"copy",
"the",
"content",
"to",
"destination",
"depending",
"on",
"the",
"user",
"response",
"... | def ask_user_overwrite_or_keep_content(self, src, dst):
user_answer = input(
self.style.WARNING(
"The destination has content inside: {}\n"
"Do you want to overwrite it completely? (y/N)".format(dst)
)
)
if user_answer.strip().lower() in ["... | [
"def",
"ask_user_overwrite_or_keep_content",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"user_answer",
"=",
"input",
"(",
"self",
".",
"style",
".",
"WARNING",
"(",
"\"The destination has content inside: {}\\n\"",
"\"Do you want to overwrite it completely? (y/N)\"",
"... | If destination has content inside, ask users if they want to overwrite
content in the destination. | [
"If",
"destination",
"has",
"content",
"inside",
"ask",
"users",
"if",
"they",
"want",
"to",
"overwrite",
"content",
"in",
"the",
"destination",
"."
] | [
"\"\"\"\n If destination has content inside, ask users if they want to overwrite\n content in the destination. We will copy the content to destination\n depending on the user response.\n \"\"\"",
"# If the user does not want to keep the content in the destination,",
"# remove the dat... | [
{
"param": "self",
"type": null
},
{
"param": "src",
"type": null
},
{
"param": "dst",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "src",
"type": null,
"docstring": null,
"docstring_tokens": []... |
9f4a867e0c1ca1c61aea43fc8c70629f8cbbebfc | khangmach/kolibri | kolibri/core/content/management/commands/content.py | [
"MIT"
] | Python | update_config_content_directory | null | def update_config_content_directory(self, dst):
"""
Update kolibri_settings.json in KOLIBRI_HOME so that the variable
CONTENT_DIRECTORY points to the destination content directory.
"""
update_options_file("Paths", "CONTENT_DIR", dst, KOLIBRI_HOME)
self.stdout.write(
... |
Update kolibri_settings.json in KOLIBRI_HOME so that the variable
CONTENT_DIRECTORY points to the destination content directory.
| Update kolibri_settings.json in KOLIBRI_HOME so that the variable
CONTENT_DIRECTORY points to the destination content directory. | [
"Update",
"kolibri_settings",
".",
"json",
"in",
"KOLIBRI_HOME",
"so",
"that",
"the",
"variable",
"CONTENT_DIRECTORY",
"points",
"to",
"the",
"destination",
"content",
"directory",
"."
] | def update_config_content_directory(self, dst):
update_options_file("Paths", "CONTENT_DIR", dst, KOLIBRI_HOME)
self.stdout.write(
self.style.SUCCESS("\nCurrent content directory is {}".format(dst))
) | [
"def",
"update_config_content_directory",
"(",
"self",
",",
"dst",
")",
":",
"update_options_file",
"(",
"\"Paths\"",
",",
"\"CONTENT_DIR\"",
",",
"dst",
",",
"KOLIBRI_HOME",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"style",
".",
"SUCCESS",
... | Update kolibri_settings.json in KOLIBRI_HOME so that the variable
CONTENT_DIRECTORY points to the destination content directory. | [
"Update",
"kolibri_settings",
".",
"json",
"in",
"KOLIBRI_HOME",
"so",
"that",
"the",
"variable",
"CONTENT_DIRECTORY",
"points",
"to",
"the",
"destination",
"content",
"directory",
"."
] | [
"\"\"\"\n Update kolibri_settings.json in KOLIBRI_HOME so that the variable\n CONTENT_DIRECTORY points to the destination content directory.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "dst",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dst",
"type": null,
"docstring": null,
"docstring_tokens": []... |
9f4a867e0c1ca1c61aea43fc8c70629f8cbbebfc | khangmach/kolibri | kolibri/core/content/management/commands/content.py | [
"MIT"
] | Python | copy_content | null | def copy_content(self, src, dst):
"""
Copy the content from current directory to destination directory.
"""
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
files = os.listdir(src)
for file in files:
src_name = os.... |
Copy the content from current directory to destination directory.
| Copy the content from current directory to destination directory. | [
"Copy",
"the",
"content",
"from",
"current",
"directory",
"to",
"destination",
"directory",
"."
] | def copy_content(self, src, dst):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
files = os.listdir(src)
for file in files:
src_name = os.path.join(src, file)
dst_name = os.path.join(dst, file)
if os.path.isdir(s... | [
"def",
"copy_content",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst",
")",
":",
"os",
".",
"makedirs",
"(",
"dst",
")",
"shutil",
".",
"copystat",
"(",
"src",
",",
"dst",
")",
"files",
... | Copy the content from current directory to destination directory. | [
"Copy",
"the",
"content",
"from",
"current",
"directory",
"to",
"destination",
"directory",
"."
] | [
"\"\"\"\n Copy the content from current directory to destination directory.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "src",
"type": null
},
{
"param": "dst",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "src",
"type": null,
"docstring": null,
"docstring_tokens": []... |
ec034f8e42311e7c9bd94e32fe9d551dfd6a1942 | khangmach/kolibri | build_tools/i18n/crowdin.py | [
"MIT"
] | Python | _format_json_files | null | def _format_json_files():
"""
re-print all json files to ensure consistent diffs with ordered keys
"""
locale_paths = []
for lang_object in utils.supported_languages(include_in_context=True):
locale_paths.append(utils.local_locale_path(lang_object))
locale_paths.append(utils.local_pe... |
re-print all json files to ensure consistent diffs with ordered keys
| re-print all json files to ensure consistent diffs with ordered keys | [
"re",
"-",
"print",
"all",
"json",
"files",
"to",
"ensure",
"consistent",
"diffs",
"with",
"ordered",
"keys"
] | def _format_json_files():
locale_paths = []
for lang_object in utils.supported_languages(include_in_context=True):
locale_paths.append(utils.local_locale_path(lang_object))
locale_paths.append(utils.local_perseus_locale_path(lang_object))
for locale_path in locale_paths:
for file_nam... | [
"def",
"_format_json_files",
"(",
")",
":",
"locale_paths",
"=",
"[",
"]",
"for",
"lang_object",
"in",
"utils",
".",
"supported_languages",
"(",
"include_in_context",
"=",
"True",
")",
":",
"locale_paths",
".",
"append",
"(",
"utils",
".",
"local_locale_path",
... | re-print all json files to ensure consistent diffs with ordered keys | [
"re",
"-",
"print",
"all",
"json",
"files",
"to",
"ensure",
"consistent",
"diffs",
"with",
"ordered",
"keys"
] | [
"\"\"\"\n re-print all json files to ensure consistent diffs with ordered keys\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
ec034f8e42311e7c9bd94e32fe9d551dfd6a1942 | khangmach/kolibri | build_tools/i18n/crowdin.py | [
"MIT"
] | Python | command_download | null | def command_download(branch):
"""
Downloads and updates the local translation files from the given branch on Crowdin
"""
logging.info("Crowdin: downloading '{}'...".format(branch))
# delete previous files
_wipe_translations(utils.LOCALE_PATH)
_wipe_translations(utils.PERSEUS_LOCALE_PATH)
... |
Downloads and updates the local translation files from the given branch on Crowdin
| Downloads and updates the local translation files from the given branch on Crowdin | [
"Downloads",
"and",
"updates",
"the",
"local",
"translation",
"files",
"from",
"the",
"given",
"branch",
"on",
"Crowdin"
] | def command_download(branch):
logging.info("Crowdin: downloading '{}'...".format(branch))
_wipe_translations(utils.LOCALE_PATH)
_wipe_translations(utils.PERSEUS_LOCALE_PATH)
for lang_object in utils.supported_languages(include_in_context=True):
code = lang_object[utils.KEY_CROWDIN_CODE]
... | [
"def",
"command_download",
"(",
"branch",
")",
":",
"logging",
".",
"info",
"(",
"\"Crowdin: downloading '{}'...\"",
".",
"format",
"(",
"branch",
")",
")",
"_wipe_translations",
"(",
"utils",
".",
"LOCALE_PATH",
")",
"_wipe_translations",
"(",
"utils",
".",
"PE... | Downloads and updates the local translation files from the given branch on Crowdin | [
"Downloads",
"and",
"updates",
"the",
"local",
"translation",
"files",
"from",
"the",
"given",
"branch",
"on",
"Crowdin"
] | [
"\"\"\"\n Downloads and updates the local translation files from the given branch on Crowdin\n \"\"\"",
"# delete previous files",
"# hack for perseus",
"# clean them up to make git diffs more meaningful"
] | [
{
"param": "branch",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "branch",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f9f3346c50249e31f07b2dc98287e680fca8c8a1 | khangmach/kolibri | kolibri/core/content/decorators.py | [
"MIT"
] | Python | add_security_headers | <not_specific> | def add_security_headers(some_func):
"""
Decorator for adding security headers to zipcontent endpoints
"""
def wrapper_func(request, *args, **kwargs):
response = some_func(request, *args, **kwargs)
try:
request = args[0]
request = kwargs.get("request", request)... |
Decorator for adding security headers to zipcontent endpoints
| Decorator for adding security headers to zipcontent endpoints | [
"Decorator",
"for",
"adding",
"security",
"headers",
"to",
"zipcontent",
"endpoints"
] | def add_security_headers(some_func):
def wrapper_func(request, *args, **kwargs):
response = some_func(request, *args, **kwargs)
try:
request = args[0]
request = kwargs.get("request", request)
except IndexError:
request = kwargs.get("request", None)
... | [
"def",
"add_security_headers",
"(",
"some_func",
")",
":",
"def",
"wrapper_func",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"response",
"=",
"some_func",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"try",
":",
"re... | Decorator for adding security headers to zipcontent endpoints | [
"Decorator",
"for",
"adding",
"security",
"headers",
"to",
"zipcontent",
"endpoints"
] | [
"\"\"\"\n Decorator for adding security headers to zipcontent endpoints\n \"\"\""
] | [
{
"param": "some_func",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "some_func",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | user_can_create_object | null | def user_can_create_object(self, user, obj):
"""Returns True if this permission class grants <user> permission to create the provided <obj>.
Note that the object may not yet have been saved to the database (as this may be a pre-save check)."""
raise NotImplementedError(
"Override `us... | Returns True if this permission class grants <user> permission to create the provided <obj>.
Note that the object may not yet have been saved to the database (as this may be a pre-save check). | Returns True if this permission class grants permission to create the provided .
Note that the object may not yet have been saved to the database (as this may be a pre-save check). | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"permission",
"to",
"create",
"the",
"provided",
".",
"Note",
"that",
"the",
"object",
"may",
"not",
"yet",
"have",
"been",
"saved",
"to",
"the",
"database",
"(",
"as",
"this",
"may",
"be",
... | def user_can_create_object(self, user, obj):
raise NotImplementedError(
"Override `user_can_create_object` in your permission class before you use it."
) | [
"def",
"user_can_create_object",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Override `user_can_create_object` in your permission class before you use it.\"",
")"
] | Returns True if this permission class grants <user> permission to create the provided <obj>. | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"<user",
">",
"permission",
"to",
"create",
"the",
"provided",
"<obj",
">",
"."
] | [
"\"\"\"Returns True if this permission class grants <user> permission to create the provided <obj>.\n Note that the object may not yet have been saved to the database (as this may be a pre-save check).\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | user_can_read_object | null | def user_can_read_object(self, user, obj):
"""Returns True if this permission class grants <user> permission to read the provided <obj>."""
raise NotImplementedError(
"Override `user_can_read_object` in your permission class before you use it."
) | Returns True if this permission class grants <user> permission to read the provided <obj>. | Returns True if this permission class grants permission to read the provided . | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"permission",
"to",
"read",
"the",
"provided",
"."
] | def user_can_read_object(self, user, obj):
raise NotImplementedError(
"Override `user_can_read_object` in your permission class before you use it."
) | [
"def",
"user_can_read_object",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Override `user_can_read_object` in your permission class before you use it.\"",
")"
] | Returns True if this permission class grants <user> permission to read the provided <obj>. | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"<user",
">",
"permission",
"to",
"read",
"the",
"provided",
"<obj",
">",
"."
] | [
"\"\"\"Returns True if this permission class grants <user> permission to read the provided <obj>.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | user_can_update_object | null | def user_can_update_object(self, user, obj):
"""Returns True if this permission class grants <user> permission to update the provided <obj>."""
raise NotImplementedError(
"Override `user_can_update_object` in your permission class before you use it."
) | Returns True if this permission class grants <user> permission to update the provided <obj>. | Returns True if this permission class grants permission to update the provided . | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"permission",
"to",
"update",
"the",
"provided",
"."
] | def user_can_update_object(self, user, obj):
raise NotImplementedError(
"Override `user_can_update_object` in your permission class before you use it."
) | [
"def",
"user_can_update_object",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Override `user_can_update_object` in your permission class before you use it.\"",
")"
] | Returns True if this permission class grants <user> permission to update the provided <obj>. | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"<user",
">",
"permission",
"to",
"update",
"the",
"provided",
"<obj",
">",
"."
] | [
"\"\"\"Returns True if this permission class grants <user> permission to update the provided <obj>.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | user_can_delete_object | null | def user_can_delete_object(self, user, obj):
"""Returns True if this permission class grants <user> permission to delete the provided <obj>."""
raise NotImplementedError(
"Override `user_can_delete_object` in your permission class before you use it."
) | Returns True if this permission class grants <user> permission to delete the provided <obj>. | Returns True if this permission class grants permission to delete the provided . | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"permission",
"to",
"delete",
"the",
"provided",
"."
] | def user_can_delete_object(self, user, obj):
raise NotImplementedError(
"Override `user_can_delete_object` in your permission class before you use it."
) | [
"def",
"user_can_delete_object",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Override `user_can_delete_object` in your permission class before you use it.\"",
")"
] | Returns True if this permission class grants <user> permission to delete the provided <obj>. | [
"Returns",
"True",
"if",
"this",
"permission",
"class",
"grants",
"<user",
">",
"permission",
"to",
"delete",
"the",
"provided",
"<obj",
">",
"."
] | [
"\"\"\"Returns True if this permission class grants <user> permission to delete the provided <obj>.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | readable_by_user_filter | null | def readable_by_user_filter(self, user, queryset):
"""Applies a filter to the provided queryset, only returning items for which the user has read permission."""
raise NotImplementedError(
"Override `readable_by_user_filter` in your permission class before you use it."
) | Applies a filter to the provided queryset, only returning items for which the user has read permission. | Applies a filter to the provided queryset, only returning items for which the user has read permission. | [
"Applies",
"a",
"filter",
"to",
"the",
"provided",
"queryset",
"only",
"returning",
"items",
"for",
"which",
"the",
"user",
"has",
"read",
"permission",
"."
] | def readable_by_user_filter(self, user, queryset):
raise NotImplementedError(
"Override `readable_by_user_filter` in your permission class before you use it."
) | [
"def",
"readable_by_user_filter",
"(",
"self",
",",
"user",
",",
"queryset",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Override `readable_by_user_filter` in your permission class before you use it.\"",
")"
] | Applies a filter to the provided queryset, only returning items for which the user has read permission. | [
"Applies",
"a",
"filter",
"to",
"the",
"provided",
"queryset",
"only",
"returning",
"items",
"for",
"which",
"the",
"user",
"has",
"read",
"permission",
"."
] | [
"\"\"\"Applies a filter to the provided queryset, only returning items for which the user has read permission.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "queryset",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | _permissions_from_any | <not_specific> | def _permissions_from_any(self, user, obj, method_name):
"""
Private helper method to do the corresponding method calls on children permissions instances,
and succeed as soon as one of them succeeds, or fail if none of them do.
"""
for perm in self.perms:
if getattr(p... |
Private helper method to do the corresponding method calls on children permissions instances,
and succeed as soon as one of them succeeds, or fail if none of them do.
| Private helper method to do the corresponding method calls on children permissions instances,
and succeed as soon as one of them succeeds, or fail if none of them do. | [
"Private",
"helper",
"method",
"to",
"do",
"the",
"corresponding",
"method",
"calls",
"on",
"children",
"permissions",
"instances",
"and",
"succeed",
"as",
"soon",
"as",
"one",
"of",
"them",
"succeeds",
"or",
"fail",
"if",
"none",
"of",
"them",
"do",
"."
] | def _permissions_from_any(self, user, obj, method_name):
for perm in self.perms:
if getattr(perm, method_name)(user, obj):
return True
return False | [
"def",
"_permissions_from_any",
"(",
"self",
",",
"user",
",",
"obj",
",",
"method_name",
")",
":",
"for",
"perm",
"in",
"self",
".",
"perms",
":",
"if",
"getattr",
"(",
"perm",
",",
"method_name",
")",
"(",
"user",
",",
"obj",
")",
":",
"return",
"T... | Private helper method to do the corresponding method calls on children permissions instances,
and succeed as soon as one of them succeeds, or fail if none of them do. | [
"Private",
"helper",
"method",
"to",
"do",
"the",
"corresponding",
"method",
"calls",
"on",
"children",
"permissions",
"instances",
"and",
"succeed",
"as",
"soon",
"as",
"one",
"of",
"them",
"succeeds",
"or",
"fail",
"if",
"none",
"of",
"them",
"do",
"."
] | [
"\"\"\"\n Private helper method to do the corresponding method calls on children permissions instances,\n and succeed as soon as one of them succeeds, or fail if none of them do.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "obj",
"type": null
},
{
"param": "method_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
37fb7235b573db121babf52bc344ad8f6523cd32 | khangmach/kolibri | kolibri/core/auth/permissions/base.py | [
"MIT"
] | Python | _permissions_from_all | <not_specific> | def _permissions_from_all(self, user, obj, method_name):
"""
Private helper method to do the corresponding method calls on children permissions instances,
and fail as soon as one of them fails, or succeed if all of them succeed.
"""
for perm in self.perms:
if not geta... |
Private helper method to do the corresponding method calls on children permissions instances,
and fail as soon as one of them fails, or succeed if all of them succeed.
| Private helper method to do the corresponding method calls on children permissions instances,
and fail as soon as one of them fails, or succeed if all of them succeed. | [
"Private",
"helper",
"method",
"to",
"do",
"the",
"corresponding",
"method",
"calls",
"on",
"children",
"permissions",
"instances",
"and",
"fail",
"as",
"soon",
"as",
"one",
"of",
"them",
"fails",
"or",
"succeed",
"if",
"all",
"of",
"them",
"succeed",
"."
] | def _permissions_from_all(self, user, obj, method_name):
for perm in self.perms:
if not getattr(perm, method_name)(user, obj):
return False
return True | [
"def",
"_permissions_from_all",
"(",
"self",
",",
"user",
",",
"obj",
",",
"method_name",
")",
":",
"for",
"perm",
"in",
"self",
".",
"perms",
":",
"if",
"not",
"getattr",
"(",
"perm",
",",
"method_name",
")",
"(",
"user",
",",
"obj",
")",
":",
"retu... | Private helper method to do the corresponding method calls on children permissions instances,
and fail as soon as one of them fails, or succeed if all of them succeed. | [
"Private",
"helper",
"method",
"to",
"do",
"the",
"corresponding",
"method",
"calls",
"on",
"children",
"permissions",
"instances",
"and",
"fail",
"as",
"soon",
"as",
"one",
"of",
"them",
"fails",
"or",
"succeed",
"if",
"all",
"of",
"them",
"succeed",
"."
] | [
"\"\"\"\n Private helper method to do the corresponding method calls on children permissions instances,\n and fail as soon as one of them fails, or succeed if all of them succeed.\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "user",
"type": null
},
{
"param": "obj",
"type": null
},
{
"param": "method_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "user",
"type": null,
"docstring": null,
"docstring_tokens": [... |
9ce81b4b1bf8a98736bdd47cd6d2fb66575456cd | khangmach/kolibri | kolibri/core/serializers.py | [
"MIT"
] | Python | run_validation | <not_specific> | def run_validation(self, data=empty):
"""
We override the default `run_validation`, because the validation
performed by validators and the `.validate()` method should
be coerced into an error dictionary with a 'non_fields_error' key.
"""
(is_empty_value, data) = self.val... |
We override the default `run_validation`, because the validation
performed by validators and the `.validate()` method should
be coerced into an error dictionary with a 'non_fields_error' key.
| We override the default `run_validation`, because the validation
performed by validators and the `.validate()` method should
be coerced into an error dictionary with a 'non_fields_error' key. | [
"We",
"override",
"the",
"default",
"`",
"run_validation",
"`",
"because",
"the",
"validation",
"performed",
"by",
"validators",
"and",
"the",
"`",
".",
"validate",
"()",
"`",
"method",
"should",
"be",
"coerced",
"into",
"an",
"error",
"dictionary",
"with",
... | def run_validation(self, data=empty):
(is_empty_value, data) = self.validate_empty_values(data)
if is_empty_value:
return data
try:
if self.partial:
value = self.update_to_internal_value(data)
else:
value = self.to_internal_valu... | [
"def",
"run_validation",
"(",
"self",
",",
"data",
"=",
"empty",
")",
":",
"(",
"is_empty_value",
",",
"data",
")",
"=",
"self",
".",
"validate_empty_values",
"(",
"data",
")",
"if",
"is_empty_value",
":",
"return",
"data",
"try",
":",
"if",
"self",
".",... | We override the default `run_validation`, because the validation
performed by validators and the `.validate()` method should
be coerced into an error dictionary with a 'non_fields_error' key. | [
"We",
"override",
"the",
"default",
"`",
"run_validation",
"`",
"because",
"the",
"validation",
"performed",
"by",
"validators",
"and",
"the",
"`",
".",
"validate",
"()",
"`",
"method",
"should",
"be",
"coerced",
"into",
"an",
"error",
"dictionary",
"with",
... | [
"\"\"\"\n We override the default `run_validation`, because the validation\n performed by validators and the `.validate()` method should\n be coerced into an error dictionary with a 'non_fields_error' key.\n \"\"\"",
"# If we are creating the object (POST) we run the ModelSerializer va... | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [... |
9ce81b4b1bf8a98736bdd47cd6d2fb66575456cd | khangmach/kolibri | kolibri/core/serializers.py | [
"MIT"
] | Python | update_to_internal_value | <not_specific> | def update_to_internal_value(self, data):
"""
Dict of native values <- Dict of primitive datatypes.
"""
if not isinstance(data, Mapping):
message = self.error_messages["invalid"].format(
datatype=type(data).__name__
)
raise ValidationE... |
Dict of native values <- Dict of primitive datatypes.
| Dict of native values <- Dict of primitive datatypes. | [
"Dict",
"of",
"native",
"values",
"<",
"-",
"Dict",
"of",
"primitive",
"datatypes",
"."
] | def update_to_internal_value(self, data):
if not isinstance(data, Mapping):
message = self.error_messages["invalid"].format(
datatype=type(data).__name__
)
raise ValidationError(
{api_settings.NON_FIELD_ERRORS_KEY: [message]}, code="invalid"
... | [
"def",
"update_to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Mapping",
")",
":",
"message",
"=",
"self",
".",
"error_messages",
"[",
"\"invalid\"",
"]",
".",
"format",
"(",
"datatype",
"=",
"type",
... | Dict of native values <- Dict of primitive datatypes. | [
"Dict",
"of",
"native",
"values",
"<",
"-",
"Dict",
"of",
"primitive",
"datatypes",
"."
] | [
"\"\"\"\n Dict of native values <- Dict of primitive datatypes.\n \"\"\"",
"# fields that are computed methods don't need validation:"
] | [
{
"param": "self",
"type": null
},
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [... |
0addee446275810beb1b59397e24b9fdf9ed0b51 | lyubadimitrova/dfoseq2seq | scripts/helpers.py | [
"MIT"
] | Python | serialize | null | def serialize(x, path):
"""
Pickles a given object to a file.
:param x: an object, could be anything
:param path: a filename string
"""
with open(path, 'wb') as f:
pickle.dump(x, f) |
Pickles a given object to a file.
:param x: an object, could be anything
:param path: a filename string
| Pickles a given object to a file. | [
"Pickles",
"a",
"given",
"object",
"to",
"a",
"file",
"."
] | def serialize(x, path):
with open(path, 'wb') as f:
pickle.dump(x, f) | [
"def",
"serialize",
"(",
"x",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"x",
",",
"f",
")"
] | Pickles a given object to a file. | [
"Pickles",
"a",
"given",
"object",
"to",
"a",
"file",
"."
] | [
"\"\"\"\n Pickles a given object to a file.\n\n :param x: an object, could be anything\n :param path: a filename string\n \"\"\""
] | [
{
"param": "x",
"type": null
},
{
"param": "path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": "an object, could be anything",
"docstring_tokens": [
"an",
"object",
"could",
"be",
"anything"
],
"default": null,
"is_optional": null
... |
0addee446275810beb1b59397e24b9fdf9ed0b51 | lyubadimitrova/dfoseq2seq | scripts/helpers.py | [
"MIT"
] | Python | subarray_generator | null | def subarray_generator(arr, subarray_size):
"""
Yields blocks of size subarray_size from a given array. The blocks are split off from
the first dimension of the array, e.g. array 100 x 20, subarray_size 10 -> block size: 10 x 20
"""
i = 0
while i < len(arr):
yield arr[i : i + subarray_s... |
Yields blocks of size subarray_size from a given array. The blocks are split off from
the first dimension of the array, e.g. array 100 x 20, subarray_size 10 -> block size: 10 x 20
| Yields blocks of size subarray_size from a given array. The blocks are split off from
the first dimension of the array, e.g. | [
"Yields",
"blocks",
"of",
"size",
"subarray_size",
"from",
"a",
"given",
"array",
".",
"The",
"blocks",
"are",
"split",
"off",
"from",
"the",
"first",
"dimension",
"of",
"the",
"array",
"e",
".",
"g",
"."
] | def subarray_generator(arr, subarray_size):
i = 0
while i < len(arr):
yield arr[i : i + subarray_size], i
i += subarray_size | [
"def",
"subarray_generator",
"(",
"arr",
",",
"subarray_size",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"arr",
")",
":",
"yield",
"arr",
"[",
"i",
":",
"i",
"+",
"subarray_size",
"]",
",",
"i",
"i",
"+=",
"subarray_size"
] | Yields blocks of size subarray_size from a given array. | [
"Yields",
"blocks",
"of",
"size",
"subarray_size",
"from",
"a",
"given",
"array",
"."
] | [
"\"\"\"\n Yields blocks of size subarray_size from a given array. The blocks are split off from \n the first dimension of the array, e.g. array 100 x 20, subarray_size 10 -> block size: 10 x 20\n \"\"\""
] | [
{
"param": "arr",
"type": null
},
{
"param": "subarray_size",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "arr",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "subarray_size",
"type": null,
"docstring": null,
"docstring_to... |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | update | <not_specific> | def update(self, theta, grad):
"""
Updates theta with a step computed with a given gradient.
:param theta: the parameters to update
:param grad: the gradient that should be used for the update
"""
self.t += 1
step = self._compute_step(grad)
theta.add_(ste... |
Updates theta with a step computed with a given gradient.
:param theta: the parameters to update
:param grad: the gradient that should be used for the update
| Updates theta with a step computed with a given gradient. | [
"Updates",
"theta",
"with",
"a",
"step",
"computed",
"with",
"a",
"given",
"gradient",
"."
] | def update(self, theta, grad):
self.t += 1
step = self._compute_step(grad)
theta.add_(step)
return step | [
"def",
"update",
"(",
"self",
",",
"theta",
",",
"grad",
")",
":",
"self",
".",
"t",
"+=",
"1",
"step",
"=",
"self",
".",
"_compute_step",
"(",
"grad",
")",
"theta",
".",
"add_",
"(",
"step",
")",
"return",
"step"
] | Updates theta with a step computed with a given gradient. | [
"Updates",
"theta",
"with",
"a",
"step",
"computed",
"with",
"a",
"given",
"gradient",
"."
] | [
"\"\"\"\n Updates theta with a step computed with a given gradient.\n\n :param theta: the parameters to update\n :param grad: the gradient that should be used for the update\n \"\"\"",
"# in-place adding, no need to return theta"
] | [
{
"param": "self",
"type": null
},
{
"param": "theta",
"type": null
},
{
"param": "grad",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "theta",
"type": null,
"docstring": "the parameters to update",
... |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | _compute_step | null | def _compute_step(self, grad):
"""
Implemented in the child classes.
"""
raise NotImplementedError |
Implemented in the child classes.
| Implemented in the child classes. | [
"Implemented",
"in",
"the",
"child",
"classes",
"."
] | def _compute_step(self, grad):
raise NotImplementedError | [
"def",
"_compute_step",
"(",
"self",
",",
"grad",
")",
":",
"raise",
"NotImplementedError"
] | Implemented in the child classes. | [
"Implemented",
"in",
"the",
"child",
"classes",
"."
] | [
"\"\"\"\n Implemented in the child classes.\n\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "grad",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "grad",
"type": null,
"docstring": null,
"docstring_tokens": [... |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | load_state | null | def load_state(self, state_dict):
"""
Loads optimizer attributes, for example from a DFO checkpoint.
:param state_dict: a dict like self.get_state() returns
"""
[setattr(self, attr, value) for attr, value in state_dict.items()] |
Loads optimizer attributes, for example from a DFO checkpoint.
:param state_dict: a dict like self.get_state() returns
| Loads optimizer attributes, for example from a DFO checkpoint. | [
"Loads",
"optimizer",
"attributes",
"for",
"example",
"from",
"a",
"DFO",
"checkpoint",
"."
] | def load_state(self, state_dict):
[setattr(self, attr, value) for attr, value in state_dict.items()] | [
"def",
"load_state",
"(",
"self",
",",
"state_dict",
")",
":",
"[",
"setattr",
"(",
"self",
",",
"attr",
",",
"value",
")",
"for",
"attr",
",",
"value",
"in",
"state_dict",
".",
"items",
"(",
")",
"]"
] | Loads optimizer attributes, for example from a DFO checkpoint. | [
"Loads",
"optimizer",
"attributes",
"for",
"example",
"from",
"a",
"DFO",
"checkpoint",
"."
] | [
"\"\"\"\n Loads optimizer attributes, for example from a DFO checkpoint.\n\n :param state_dict: a dict like self.get_state() returns\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "state_dict",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "state_dict",
"type": null,
"docstring": "a dict like self.get_state... |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | cudafy | null | def cudafy(self):
"""
Moves all attributes represented by torch tensors to CUDA.
"""
for attr, value in self.get_state().items():
try:
setattr(self, attr, value.cuda())
except AttributeError:
pass |
Moves all attributes represented by torch tensors to CUDA.
| Moves all attributes represented by torch tensors to CUDA. | [
"Moves",
"all",
"attributes",
"represented",
"by",
"torch",
"tensors",
"to",
"CUDA",
"."
] | def cudafy(self):
for attr, value in self.get_state().items():
try:
setattr(self, attr, value.cuda())
except AttributeError:
pass | [
"def",
"cudafy",
"(",
"self",
")",
":",
"for",
"attr",
",",
"value",
"in",
"self",
".",
"get_state",
"(",
")",
".",
"items",
"(",
")",
":",
"try",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"value",
".",
"cuda",
"(",
")",
")",
"except",
"At... | Moves all attributes represented by torch tensors to CUDA. | [
"Moves",
"all",
"attributes",
"represented",
"by",
"torch",
"tensors",
"to",
"CUDA",
"."
] | [
"\"\"\"\n Moves all attributes represented by torch tensors to CUDA.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | _compute_step | <not_specific> | def _compute_step(self, grad):
"""
Computes one SGD step based on the given gradient.
:param grad: the gradient to optimize with
:return: the step, size [dim]
"""
step = -self.stepsize * grad
if self.stepsize > self.min_stepsize:
self.stepsize *= self... |
Computes one SGD step based on the given gradient.
:param grad: the gradient to optimize with
:return: the step, size [dim]
| Computes one SGD step based on the given gradient. | [
"Computes",
"one",
"SGD",
"step",
"based",
"on",
"the",
"given",
"gradient",
"."
] | def _compute_step(self, grad):
step = -self.stepsize * grad
if self.stepsize > self.min_stepsize:
self.stepsize *= self.decay
return step | [
"def",
"_compute_step",
"(",
"self",
",",
"grad",
")",
":",
"step",
"=",
"-",
"self",
".",
"stepsize",
"*",
"grad",
"if",
"self",
".",
"stepsize",
">",
"self",
".",
"min_stepsize",
":",
"self",
".",
"stepsize",
"*=",
"self",
".",
"decay",
"return",
"... | Computes one SGD step based on the given gradient. | [
"Computes",
"one",
"SGD",
"step",
"based",
"on",
"the",
"given",
"gradient",
"."
] | [
"\"\"\"\n Computes one SGD step based on the given gradient.\n\n :param grad: the gradient to optimize with\n :return: the step, size [dim]\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "grad",
"type": null
}
] | {
"returns": [
{
"docstring": "the step, size [dim]",
"docstring_tokens": [
"the",
"step",
"size",
"[",
"dim",
"]"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring... |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | _compute_step | <not_specific> | def _compute_step(self, grad):
"""
Computes one Momentum-SGD step based on the given gradient.
:param grad: the gradient to optimize with
:return: the step, size [dim]
"""
self.v = self.momentum * self.v + (1. - self.momentum) * grad
step = -self.stepsize... |
Computes one Momentum-SGD step based on the given gradient.
:param grad: the gradient to optimize with
:return: the step, size [dim]
| Computes one Momentum-SGD step based on the given gradient. | [
"Computes",
"one",
"Momentum",
"-",
"SGD",
"step",
"based",
"on",
"the",
"given",
"gradient",
"."
] | def _compute_step(self, grad):
self.v = self.momentum * self.v + (1. - self.momentum) * grad
step = -self.stepsize * self.v
return step | [
"def",
"_compute_step",
"(",
"self",
",",
"grad",
")",
":",
"self",
".",
"v",
"=",
"self",
".",
"momentum",
"*",
"self",
".",
"v",
"+",
"(",
"1.",
"-",
"self",
".",
"momentum",
")",
"*",
"grad",
"step",
"=",
"-",
"self",
".",
"stepsize",
"*",
"... | Computes one Momentum-SGD step based on the given gradient. | [
"Computes",
"one",
"Momentum",
"-",
"SGD",
"step",
"based",
"on",
"the",
"given",
"gradient",
"."
] | [
"\"\"\"\n Computes one Momentum-SGD step based on the given gradient.\n \n :param grad: the gradient to optimize with\n :return: the step, size [dim]\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "grad",
"type": null
}
] | {
"returns": [
{
"docstring": "the step, size [dim]",
"docstring_tokens": [
"the",
"step",
"size",
"[",
"dim",
"]"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring... |
b29a5eea25555dbea6a587b770d2b24631f09985 | lyubadimitrova/dfoseq2seq | scripts/optimizers.py | [
"MIT"
] | Python | _compute_step | <not_specific> | def _compute_step(self, grad):
"""
Computes one Adam step based on the given gradient.
:param grad: the gradient to optimize with
:return: the step, size [dim]
"""
a = self.stepsize * np.sqrt(1 - self.beta2 ** self.t) / (1 - self.beta1 ** self.t)
self.m =... |
Computes one Adam step based on the given gradient.
:param grad: the gradient to optimize with
:return: the step, size [dim]
| Computes one Adam step based on the given gradient. | [
"Computes",
"one",
"Adam",
"step",
"based",
"on",
"the",
"given",
"gradient",
"."
] | def _compute_step(self, grad):
a = self.stepsize * np.sqrt(1 - self.beta2 ** self.t) / (1 - self.beta1 ** self.t)
self.m = self.beta1 * self.m + (1 - self.beta1) * grad
self.v = self.beta2 * self.v + (1 - self.beta2) * (grad * grad)
step = -a * self.m / (torch.sqrt(self.v) + self.epsilon... | [
"def",
"_compute_step",
"(",
"self",
",",
"grad",
")",
":",
"a",
"=",
"self",
".",
"stepsize",
"*",
"np",
".",
"sqrt",
"(",
"1",
"-",
"self",
".",
"beta2",
"**",
"self",
".",
"t",
")",
"/",
"(",
"1",
"-",
"self",
".",
"beta1",
"**",
"self",
"... | Computes one Adam step based on the given gradient. | [
"Computes",
"one",
"Adam",
"step",
"based",
"on",
"the",
"given",
"gradient",
"."
] | [
"\"\"\"\n Computes one Adam step based on the given gradient.\n \n :param grad: the gradient to optimize with\n :return: the step, size [dim]\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "grad",
"type": null
}
] | {
"returns": [
{
"docstring": "the step, size [dim]",
"docstring_tokens": [
"the",
"step",
"size",
"[",
"dim",
"]"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring... |
0a93eb976541bd99ece7ba2367c75e4b61dc579e | lyubadimitrova/dfoseq2seq | scripts/reward_function.py | [
"MIT"
] | Python | my_reward | <not_specific> | def my_reward(tm, candidate_theta):
"""
Computes the reward of a single candidate-theta.
:param candidate_theta: the candidate model parameters
:return reward: a scalar representing the reward of candidate_theta on the current data
"""
# set the evaluation/reward metric
eval_metric = t... |
Computes the reward of a single candidate-theta.
:param candidate_theta: the candidate model parameters
:return reward: a scalar representing the reward of candidate_theta on the current data
| Computes the reward of a single candidate-theta. | [
"Computes",
"the",
"reward",
"of",
"a",
"single",
"candidate",
"-",
"theta",
"."
] | def my_reward(tm, candidate_theta):
eval_metric = tm.train_cfg.get("eval_metric", "bleu")
dummy_model = copy.deepcopy(tm.model)
torch.nn.utils.vector_to_parameters(candidate_theta, dummy_model.parameters())
if isinstance(tm.current_data, Dataset):
return validate_on_data(dummy_model, tm.cur... | [
"def",
"my_reward",
"(",
"tm",
",",
"candidate_theta",
")",
":",
"eval_metric",
"=",
"tm",
".",
"train_cfg",
".",
"get",
"(",
"\"eval_metric\"",
",",
"\"bleu\"",
")",
"dummy_model",
"=",
"copy",
".",
"deepcopy",
"(",
"tm",
".",
"model",
")",
"torch",
"."... | Computes the reward of a single candidate-theta. | [
"Computes",
"the",
"reward",
"of",
"a",
"single",
"candidate",
"-",
"theta",
"."
] | [
"\"\"\"\n Computes the reward of a single candidate-theta.\n\n :param candidate_theta: the candidate model parameters\n :return reward: a scalar representing the reward of candidate_theta on the current data\n \"\"\"",
"# set the evaluation/reward metric",
"# make a copy of the model, mostly for par... | [
{
"param": "tm",
"type": null
},
{
"param": "candidate_theta",
"type": null
}
] | {
"returns": [
{
"docstring": "a scalar representing the reward of candidate_theta on the current data",
"docstring_tokens": [
"a",
"scalar",
"representing",
"the",
"reward",
"of",
"candidate_theta",
"on",
"the",
"current"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.