Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
deRuiter_radius | (src1, src2) | Calculates the De Ruiter radius for two sources | Calculates the De Ruiter radius for two sources | def deRuiter_radius(src1, src2):
"""Calculates the De Ruiter radius for two sources"""
# The errors are the square root of the quadratic sum of
# the systematic and fitted errors.
src1_ew_uncertainty = math.sqrt(src1.ew_sys_err**2 + src1.error_radius**2) / 3600.
src1_ns_uncertainty = math.sqrt(src1... | [
"def",
"deRuiter_radius",
"(",
"src1",
",",
"src2",
")",
":",
"# The errors are the square root of the quadratic sum of",
"# the systematic and fitted errors.",
"src1_ew_uncertainty",
"=",
"math",
".",
"sqrt",
"(",
"src1",
".",
"ew_sys_err",
"**",
"2",
"+",
"src1",
".",... | [
165,
0
] | [
184,
13
] | python | en | ['en', 'en', 'en'] | True |
lightcurve_metrics | (src_list) |
Calculates various metrics for a lightcurve made up of source extractions
These are normally calculated internally in the database - this function
serves as a sanity check, and is used for unit-testing purposes.
Returns a list of dictionaries, the nth dict representing the value
of the metrics af... |
Calculates various metrics for a lightcurve made up of source extractions | def lightcurve_metrics(src_list):
"""
Calculates various metrics for a lightcurve made up of source extractions
These are normally calculated internally in the database - this function
serves as a sanity check, and is used for unit-testing purposes.
Returns a list of dictionaries, the nth dict rep... | [
"def",
"lightcurve_metrics",
"(",
"src_list",
")",
":",
"metrics",
"=",
"[",
"]",
"for",
"i",
",",
"src",
"in",
"enumerate",
"(",
"src_list",
")",
":",
"N",
"=",
"i",
"+",
"1",
"avg_int_flux",
"=",
"sum",
"(",
"src",
".",
"flux",
"for",
"src",
"in"... | [
187,
0
] | [
231,
18
] | python | en | ['en', 'error', 'th'] | False |
insert_image_and_simulated_sources | (dataset, image_params, mock_sources,
new_source_sigma_margin,
deruiter_radius=3.7) |
Simulates the standard database image-and-source insertion logic using mock
sources.
Args:
dataset: The dataset object
image_params (dict): Contains the image properties.
mock_sources (list of MockSource): The mock sources to simulate.
new_source_sigma_margin (float): Param... |
Simulates the standard database image-and-source insertion logic using mock
sources. | def insert_image_and_simulated_sources(dataset, image_params, mock_sources,
new_source_sigma_margin,
deruiter_radius=3.7):
"""
Simulates the standard database image-and-source insertion logic using mock
sources.
Args:
... | [
"def",
"insert_image_and_simulated_sources",
"(",
"dataset",
",",
"image_params",
",",
"mock_sources",
",",
"new_source_sigma_margin",
",",
"deruiter_radius",
"=",
"3.7",
")",
":",
"image",
"=",
"tkp",
".",
"db",
".",
"Image",
"(",
"data",
"=",
"image_params",
"... | [
323,
0
] | [
371,
48
] | python | en | ['en', 'error', 'th'] | False |
get_newsources_for_dataset | (dsid) |
Returns dicts representing all newsources for this dataset.
Args:
dsid: Dataset id
Returns:
tuple: (list of dicts) Each dict represents one newsource.
The dict keys are all the columns in the newsources table, plus
the 'taustart_ts' from the image table, which repr... |
Returns dicts representing all newsources for this dataset. | def get_newsources_for_dataset(dsid):
"""
Returns dicts representing all newsources for this dataset.
Args:
dsid: Dataset id
Returns:
tuple: (list of dicts) Each dict represents one newsource.
The dict keys are all the columns in the newsources table, plus
the '... | [
"def",
"get_newsources_for_dataset",
"(",
"dsid",
")",
":",
"qry",
"=",
"\"\"\"\\\n SELECT tr.id\n ,tr.previous_limits_image\n ,rc.id as runcat_id\n ,img.taustart_ts\n ,img.band\n ,ax.v_int\n ,ax.eta_int\n , ((ex.f_peak - limits_image... | [
374,
0
] | [
416,
37
] | python | en | ['en', 'error', 'th'] | False |
get_sources_filtered_by_final_variability | (dataset_id,
eta_min,
v_min,
# minpoints
) |
Search the database to find high-variability lightcurves.
Uses the variability associated with the last datapoint in a lightcurve
as the key criteria.
Args:
dataset_id (int): Dataset to search
eta_min (float): Minimum value of eta-index to return.
v_min (float): Minimum value ... |
Search the database to find high-variability lightcurves. | def get_sources_filtered_by_final_variability(dataset_id,
eta_min,
v_min,
# minpoints
):
"""
Search the database to find high-variability lightcurves.
Uses the variability associated with the last datapoint in a lightcurve
as the key cr... | [
"def",
"get_sources_filtered_by_final_variability",
"(",
"dataset_id",
",",
"eta_min",
",",
"v_min",
",",
"# minpoints",
")",
":",
"query",
"=",
"\"\"\"\\\nSELECT rc.id as runcat_id\n ,image.band\n ,ax.v_int\n ,ax.eta_int\nFROM runningcatalog as rc\n JOIN assocxtrsource... | [
418,
0
] | [
477,
21
] | python | en | ['en', 'error', 'th'] | False |
MockSource.__init__ | (self,
template_extractedsource,
lightcurve,
) |
Defines a MockSource for generating mock source lists.
(These can be used to test the database routines.)
The lightcurve-dict entries define the times of non-zero
flux (we do not support time-ranges here, discretely defined datapoints are
sufficiently complex for the current ... | def __init__(self,
template_extractedsource,
lightcurve,
):
"""
Defines a MockSource for generating mock source lists.
(These can be used to test the database routines.)
The lightcurve-dict entries define the times of non-zero
... | [
"def",
"__init__",
"(",
"self",
",",
"template_extractedsource",
",",
"lightcurve",
",",
")",
":",
"self",
".",
"base_source",
"=",
"template_extractedsource",
"self",
".",
"lightcurve",
"=",
"lightcurve"
] | [
237,
4
] | [
266,
36
] | python | en | ['en', 'error', 'th'] | False | |
MockSource.value_at_dtime | (self, dtime, image_rms) | Returns an `extractedsource` for a given datetime.
If lightcurve is defined but does not contain the requested datetime,
then peak, flux, sigma are all set to zero.
| Returns an `extractedsource` for a given datetime. | def value_at_dtime(self, dtime, image_rms):
"""Returns an `extractedsource` for a given datetime.
If lightcurve is defined but does not contain the requested datetime,
then peak, flux, sigma are all set to zero.
"""
try:
fluxval = self.lightcurve[dtime]
excep... | [
"def",
"value_at_dtime",
"(",
"self",
",",
"dtime",
",",
"image_rms",
")",
":",
"try",
":",
"fluxval",
"=",
"self",
".",
"lightcurve",
"[",
"dtime",
"]",
"except",
"KeyError",
":",
"fluxval",
"=",
"0",
"return",
"self",
".",
"base_source",
".",
"_replace... | [
268,
4
] | [
279,
66
] | python | en | ['en', 'en', 'en'] | True |
MockSource.simulate_extraction | (self, db_image, extraction_type,
rms_attribute='rms_min') |
Simulate extraction process, returns extracted source or none.
Uses the database image properties (extraction region, rms values)
to determine if this source would be extracted in the given image,
and return an extraction or None accordingly.
Args:
db_image (int): ... |
Simulate extraction process, returns extracted source or none. | def simulate_extraction(self, db_image, extraction_type,
rms_attribute='rms_min'):
"""
Simulate extraction process, returns extracted source or none.
Uses the database image properties (extraction region, rms values)
to determine if this source would be extra... | [
"def",
"simulate_extraction",
"(",
"self",
",",
"db_image",
",",
"extraction_type",
",",
"rms_attribute",
"=",
"'rms_min'",
")",
":",
"rms",
"=",
"getattr",
"(",
"db_image",
",",
"rms_attribute",
")",
"ex",
"=",
"self",
".",
"value_at_dtime",
"(",
"db_image",
... | [
281,
4
] | [
321,
77
] | python | en | ['en', 'error', 'th'] | False |
execute | (query, parameters={}, commit=False) |
A generic wrapper for doing any query to the database
:param query: the query string
:param parameters: The query parameters. These will be converted and escaped.
:param commit: should a commit be performed afterwards, boolean
:returns: a database cursor object
|
A generic wrapper for doing any query to the database | def execute(query, parameters={}, commit=False):
"""
A generic wrapper for doing any query to the database
:param query: the query string
:param parameters: The query parameters. These will be converted and escaped.
:param commit: should a commit be performed afterwards, boolean
:returns: a da... | [
"def",
"execute",
"(",
"query",
",",
"parameters",
"=",
"{",
"}",
",",
"commit",
"=",
"False",
")",
":",
"database",
"=",
"Database",
"(",
")",
"return",
"database",
".",
"execute",
"(",
"query",
",",
"parameters",
"=",
"parameters",
",",
"commit",
"="... | [
7,
0
] | [
18,
72
] | python | en | ['en', 'error', 'th'] | False |
serve | (app, global_conf, **local_conf) | \
A Paste Deployment server runner.
Example configuration:
[server:main]
use = egg:gunicorn#main
host = 127.0.0.1
port = 5000
| \
A Paste Deployment server runner. | def serve(app, global_conf, **local_conf):
"""\
A Paste Deployment server runner.
Example configuration:
[server:main]
use = egg:gunicorn#main
host = 127.0.0.1
port = 5000
"""
config_file = global_conf['__file__']
gunicorn_config_file = local_conf.pop('config', ... | [
"def",
"serve",
"(",
"app",
",",
"global_conf",
",",
"*",
"*",
"local_conf",
")",
":",
"config_file",
"=",
"global_conf",
"[",
"'__file__'",
"]",
"gunicorn_config_file",
"=",
"local_conf",
".",
"pop",
"(",
"'config'",
",",
"None",
")",
"host",
"=",
"local_... | [
32,
0
] | [
74,
35
] | python | en | ['en', 'ja', 'hi'] | False |
_normalize_mode | (im, initial_call=False) |
Takes an image (or frame), returns an image in a mode that is appropriate
for saving in a Gif.
It may return the original image, or it may return an image converted to
palette or 'L' mode.
UNDONE: What is the point of mucking with the initial call palette, for
an image that shouldn't have a p... |
Takes an image (or frame), returns an image in a mode that is appropriate
for saving in a Gif. | def _normalize_mode(im, initial_call=False):
"""
Takes an image (or frame), returns an image in a mode that is appropriate
for saving in a Gif.
It may return the original image, or it may return an image converted to
palette or 'L' mode.
UNDONE: What is the point of mucking with the initial ca... | [
"def",
"_normalize_mode",
"(",
"im",
",",
"initial_call",
"=",
"False",
")",
":",
"if",
"im",
".",
"mode",
"in",
"RAWMODE",
":",
"im",
".",
"load",
"(",
")",
"return",
"im",
"if",
"Image",
".",
"getmodebase",
"(",
"im",
".",
"mode",
")",
"==",
"\"R... | [
328,
0
] | [
355,
26
] | python | en | ['en', 'error', 'th'] | False |
_normalize_palette | (im, palette, info) |
Normalizes the palette for image.
- Sets the palette to the incoming palette, if provided.
- Ensures that there's a palette for L mode images
- Optimizes the palette if necessary/desired.
:param im: Image object
:param palette: bytes object containing the source palette, or ....
:par... |
Normalizes the palette for image.
- Sets the palette to the incoming palette, if provided.
- Ensures that there's a palette for L mode images
- Optimizes the palette if necessary/desired. | def _normalize_palette(im, palette, info):
"""
Normalizes the palette for image.
- Sets the palette to the incoming palette, if provided.
- Ensures that there's a palette for L mode images
- Optimizes the palette if necessary/desired.
:param im: Image object
:param palette: bytes obje... | [
"def",
"_normalize_palette",
"(",
"im",
",",
"palette",
",",
"info",
")",
":",
"source_palette",
"=",
"None",
"if",
"palette",
":",
"# a bytes palette",
"if",
"isinstance",
"(",
"palette",
",",
"(",
"bytes",
",",
"bytearray",
",",
"list",
")",
")",
":",
... | [
358,
0
] | [
399,
13
] | python | en | ['en', 'error', 'th'] | False |
_get_optimize | (im, info) |
Palette optimization is a potentially expensive operation.
This function determines if the palette should be optimized using
some heuristics, then returns the list of palette entries in use.
:param im: Image object
:param info: encoderinfo
:returns: list of indexes of palette entries in use, ... |
Palette optimization is a potentially expensive operation. | def _get_optimize(im, info):
"""
Palette optimization is a potentially expensive operation.
This function determines if the palette should be optimized using
some heuristics, then returns the list of palette entries in use.
:param im: Image object
:param info: encoderinfo
:returns: list of... | [
"def",
"_get_optimize",
"(",
"im",
",",
"info",
")",
":",
"if",
"im",
".",
"mode",
"in",
"(",
"\"P\"",
",",
"\"L\"",
")",
"and",
"info",
"and",
"info",
".",
"get",
"(",
"\"optimize\"",
",",
"0",
")",
":",
"# Potentially expensive operation.",
"# The pale... | [
668,
0
] | [
702,
42
] | python | en | ['en', 'error', 'th'] | False |
_get_header_palette | (palette_bytes) |
Returns the palette, null padded to the next power of 2 (*3) bytes
suitable for direct inclusion in the GIF header
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
:returns: Null padded palette
|
Returns the palette, null padded to the next power of 2 (*3) bytes
suitable for direct inclusion in the GIF header | def _get_header_palette(palette_bytes):
"""
Returns the palette, null padded to the next power of 2 (*3) bytes
suitable for direct inclusion in the GIF header
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
:returns: Null padded palette
"""
color_table_size = _get_color_table_s... | [
"def",
"_get_header_palette",
"(",
"palette_bytes",
")",
":",
"color_table_size",
"=",
"_get_color_table_size",
"(",
"palette_bytes",
")",
"# add the missing amount of bytes",
"# the palette has to be 2<<n in size",
"actual_target_size_diff",
"=",
"(",
"2",
"<<",
"color_table_s... | [
715,
0
] | [
730,
24
] | python | en | ['en', 'error', 'th'] | False |
_get_palette_bytes | (im) |
Gets the palette for inclusion in the gif header
:param im: Image object
:returns: Bytes, len<=768 suitable for inclusion in gif header
|
Gets the palette for inclusion in the gif header | def _get_palette_bytes(im):
"""
Gets the palette for inclusion in the gif header
:param im: Image object
:returns: Bytes, len<=768 suitable for inclusion in gif header
"""
return im.palette.palette | [
"def",
"_get_palette_bytes",
"(",
"im",
")",
":",
"return",
"im",
".",
"palette",
".",
"palette"
] | [
733,
0
] | [
740,
29
] | python | en | ['en', 'error', 'th'] | False |
_get_global_header | (im, info) | Return a list of strings representing a GIF header | Return a list of strings representing a GIF header | def _get_global_header(im, info):
"""Return a list of strings representing a GIF header"""
# Header Block
# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
version = b"87a"
for extensionKey in ["transparency", "duration", "loop", "comment"]:
if info and extensionKey in ... | [
"def",
"_get_global_header",
"(",
"im",
",",
"info",
")",
":",
"# Header Block",
"# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp",
"version",
"=",
"b\"87a\"",
"for",
"extensionKey",
"in",
"[",
"\"transparency\"",
",",
"\"duration\"",
",",
"\"loop\"",
... | [
755,
0
] | [
791,
5
] | python | en | ['en', 'en', 'en'] | True |
getheader | (im, palette=None, info=None) |
Legacy Method to get Gif data from image.
Warning:: May modify image data.
:param im: Image object
:param palette: bytes object containing the source palette, or ....
:param info: encoderinfo
:returns: tuple of(list of header items, optimized palette)
|
Legacy Method to get Gif data from image. | def getheader(im, palette=None, info=None):
"""
Legacy Method to get Gif data from image.
Warning:: May modify image data.
:param im: Image object
:param palette: bytes object containing the source palette, or ....
:param info: encoderinfo
:returns: tuple of(list of header items, optimized... | [
"def",
"getheader",
"(",
"im",
",",
"palette",
"=",
"None",
",",
"info",
"=",
"None",
")",
":",
"used_palette_colors",
"=",
"_get_optimize",
"(",
"im",
",",
"info",
")",
"if",
"info",
"is",
"None",
":",
"info",
"=",
"{",
"}",
"if",
"\"background\"",
... | [
814,
0
] | [
839,
38
] | python | en | ['en', 'error', 'th'] | False |
getdata | (im, offset=(0, 0), **params) |
Legacy Method
Return a list of strings representing this image.
The first string is a local image header, the rest contains
encoded image data.
:param im: Image object
:param offset: Tuple of (x, y) pixels. Defaults to (0,0)
:param \\**params: E.g. duration or other encoder info parameter... |
Legacy Method | def getdata(im, offset=(0, 0), **params):
"""
Legacy Method
Return a list of strings representing this image.
The first string is a local image header, the rest contains
encoded image data.
:param im: Image object
:param offset: Tuple of (x, y) pixels. Defaults to (0,0)
:param \\**para... | [
"def",
"getdata",
"(",
"im",
",",
"offset",
"=",
"(",
"0",
",",
"0",
")",
",",
"*",
"*",
"params",
")",
":",
"class",
"Collector",
":",
"data",
"=",
"[",
"]",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"data",
".",
"appe... | [
844,
0
] | [
871,
18
] | python | en | ['en', 'error', 'th'] | False |
BaselineRemoval.poly | (self,input_array_for_poly,degree_for_poly) | qr factorization of a matrix. q` is orthonormal and `r` is upper-triangular.
- QR decomposition is equivalent to Gram Schmidt orthogonalization, which builds a sequence of orthogonal polynomials that approximate your function with minimal least-squares error
- in the next step, discard the first column ... | qr factorization of a matrix. q` is orthonormal and `r` is upper-triangular.
- QR decomposition is equivalent to Gram Schmidt orthogonalization, which builds a sequence of orthogonal polynomials that approximate your function with minimal least-squares error
- in the next step, discard the first column ... | def poly(self,input_array_for_poly,degree_for_poly):
'''qr factorization of a matrix. q` is orthonormal and `r` is upper-triangular.
- QR decomposition is equivalent to Gram Schmidt orthogonalization, which builds a sequence of orthogonal polynomials that approximate your function with minimal least-squ... | [
"def",
"poly",
"(",
"self",
",",
"input_array_for_poly",
",",
"degree_for_poly",
")",
":",
"input_array_for_poly",
"=",
"np",
".",
"array",
"(",
"input_array_for_poly",
")",
"X",
"=",
"np",
".",
"transpose",
"(",
"np",
".",
"vstack",
"(",
"(",
"input_array_f... | [
15,
4
] | [
26,
39
] | python | en | ['en', 'en', 'en'] | True |
BaselineRemoval.ModPoly | (self,degree=2,repitition=100,gradient=0.001) | Implementation of Modified polyfit method from paper: Automated Method for Subtraction of Fluorescence from Biological Raman Spectra, by Lieber & Mahadevan-Jansen (2003)
degree: Polynomial degree, default is 2
repitition: How many iterations to run. Default is 100
gradient: Gradient for... | Implementation of Modified polyfit method from paper: Automated Method for Subtraction of Fluorescence from Biological Raman Spectra, by Lieber & Mahadevan-Jansen (2003)
degree: Polynomial degree, default is 2
repitition: How many iterations to run. Default is 100
gradient: Gradient for... | def ModPoly(self,degree=2,repitition=100,gradient=0.001):
'''Implementation of Modified polyfit method from paper: Automated Method for Subtraction of Fluorescence from Biological Raman Spectra, by Lieber & Mahadevan-Jansen (2003)
degree: Polynomial degree, default is 2
repitition: How ... | [
"def",
"ModPoly",
"(",
"self",
",",
"degree",
"=",
"2",
",",
"repitition",
"=",
"100",
",",
"gradient",
"=",
"0.001",
")",
":",
"#initial improvement criteria is set as positive infinity, to be replaced later on with actual value",
"criteria",
"=",
"np",
".",
"inf",
"... | [
27,
4
] | [
56,
24
] | python | en | ['en', 'en', 'en'] | True |
BaselineRemoval.IModPoly | (self,degree=2,repitition=100,gradient=0.001) | IModPoly from paper: Automated Autofluorescence Background Subtraction Algorithm for Biomedical Raman Spectroscopy, by Zhao, Jianhua, Lui, Harvey, McLean, David I., Zeng, Haishan (2007)
degree: Polynomial degree, default is 2
repitition: How many iterations to run. Default is 100
gradie... | IModPoly from paper: Automated Autofluorescence Background Subtraction Algorithm for Biomedical Raman Spectroscopy, by Zhao, Jianhua, Lui, Harvey, McLean, David I., Zeng, Haishan (2007) | def IModPoly(self,degree=2,repitition=100,gradient=0.001):
'''IModPoly from paper: Automated Autofluorescence Background Subtraction Algorithm for Biomedical Raman Spectroscopy, by Zhao, Jianhua, Lui, Harvey, McLean, David I., Zeng, Haishan (2007)
degree: Polynomial degree, default is 2
... | [
"def",
"IModPoly",
"(",
"self",
",",
"degree",
"=",
"2",
",",
"repitition",
"=",
"100",
",",
"gradient",
"=",
"0.001",
")",
":",
"yold",
"=",
"np",
".",
"array",
"(",
"self",
".",
"input_array",
")",
"yorig",
"=",
"np",
".",
"array",
"(",
"self",
... | [
58,
4
] | [
96,
24
] | python | en | ['en', 'en', 'en'] | True |
BaselineRemoval._WhittakerSmooth | (self,x,w,lambda_,differences=1) |
Penalized least squares algorithm for background fitting
input
x: input data (i.e. chromatogram of spectrum)
w: binary masks (value of the mask is zero if a point belongs to peaks and one otherwise)
lambda_: parameter that can be adjusted by user. The larger lambda ... |
Penalized least squares algorithm for background fitting | def _WhittakerSmooth(self,x,w,lambda_,differences=1):
'''
Penalized least squares algorithm for background fitting
input
x: input data (i.e. chromatogram of spectrum)
w: binary masks (value of the mask is zero if a point belongs to peaks and one otherwise)
la... | [
"def",
"_WhittakerSmooth",
"(",
"self",
",",
"x",
",",
"w",
",",
"lambda_",
",",
"differences",
"=",
"1",
")",
":",
"X",
"=",
"np",
".",
"matrix",
"(",
"x",
")",
"m",
"=",
"X",
".",
"size",
"i",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"m",
... | [
98,
4
] | [
120,
35
] | python | en | ['en', 'error', 'th'] | False |
BaselineRemoval.ZhangFit | (self,lambda_=100, porder=1, itermax=15) |
Implementation of Zhang fit for Adaptive iteratively reweighted penalized least squares for baseline fitting. Modified from Original implementation by Professor Zhimin Zhang at https://github.com/zmzhang/airPLS/
lambda_: parameter that can be adjusted by user. The larger lambda is, the smooth... |
Implementation of Zhang fit for Adaptive iteratively reweighted penalized least squares for baseline fitting. Modified from Original implementation by Professor Zhimin Zhang at https://github.com/zmzhang/airPLS/
lambda_: parameter that can be adjusted by user. The larger lambda is, the smooth... | def ZhangFit(self,lambda_=100, porder=1, itermax=15):
'''
Implementation of Zhang fit for Adaptive iteratively reweighted penalized least squares for baseline fitting. Modified from Original implementation by Professor Zhimin Zhang at https://github.com/zmzhang/airPLS/
lambda_: paramete... | [
"def",
"ZhangFit",
"(",
"self",
",",
"lambda_",
"=",
"100",
",",
"porder",
"=",
"1",
",",
"itermax",
"=",
"15",
")",
":",
"yorig",
"=",
"np",
".",
"array",
"(",
"self",
".",
"input_array",
")",
"corrected",
"=",
"[",
"]",
"m",
"=",
"yorig",
".",
... | [
122,
4
] | [
146,
30
] | python | en | ['en', 'error', 'th'] | False |
daemon_launch_lock_path | (root_path: Path) |
A path to a file that is lock when a daemon is launching but not yet started.
This prevents multiple instances from launching.
|
A path to a file that is lock when a daemon is launching but not yet started.
This prevents multiple instances from launching.
| def daemon_launch_lock_path(root_path: Path) -> Path:
"""
A path to a file that is lock when a daemon is launching but not yet started.
This prevents multiple instances from launching.
"""
return root_path / "run" / "start-daemon.launching" | [
"def",
"daemon_launch_lock_path",
"(",
"root_path",
":",
"Path",
")",
"->",
"Path",
":",
"return",
"root_path",
"/",
"\"run\"",
"/",
"\"start-daemon.launching\""
] | [
702,
0
] | [
707,
55
] | python | en | ['en', 'error', 'th'] | False |
service_launch_lock_path | (root_path: Path, service: str) |
A path to a file that is lock when a service is running.
|
A path to a file that is lock when a service is running.
| def service_launch_lock_path(root_path: Path, service: str) -> Path:
"""
A path to a file that is lock when a service is running.
"""
service_name = service.replace(" ", "-").replace("/", "-")
return root_path / "run" / f"{service_name}.lock" | [
"def",
"service_launch_lock_path",
"(",
"root_path",
":",
"Path",
",",
"service",
":",
"str",
")",
"->",
"Path",
":",
"service_name",
"=",
"service",
".",
"replace",
"(",
"\" \"",
",",
"\"-\"",
")",
".",
"replace",
"(",
"\"/\"",
",",
"\"-\"",
")",
"retur... | [
710,
0
] | [
715,
53
] | python | en | ['en', 'error', 'th'] | False |
pid_path_for_service | (root_path: Path, service: str, id: str = "") |
Generate a path for a PID file for the given service name.
|
Generate a path for a PID file for the given service name.
| def pid_path_for_service(root_path: Path, service: str, id: str = "") -> Path:
"""
Generate a path for a PID file for the given service name.
"""
pid_name = service.replace(" ", "-").replace("/", "-")
return root_path / "run" / f"{pid_name}{id}.pid" | [
"def",
"pid_path_for_service",
"(",
"root_path",
":",
"Path",
",",
"service",
":",
"str",
",",
"id",
":",
"str",
"=",
"\"\"",
")",
"->",
"Path",
":",
"pid_name",
"=",
"service",
".",
"replace",
"(",
"\" \"",
",",
"\"-\"",
")",
".",
"replace",
"(",
"\... | [
718,
0
] | [
723,
52
] | python | en | ['en', 'error', 'th'] | False |
launch_service | (root_path: Path, service_command) |
Launch a child process.
|
Launch a child process.
| def launch_service(root_path: Path, service_command) -> Tuple[subprocess.Popen, Path]:
"""
Launch a child process.
"""
# set up KALE_ROOT
# invoke correct script
# save away PID
# we need to pass on the possibly altered KALE_ROOT
os.environ["KALE_ROOT"] = str(root_path)
log.debug(f... | [
"def",
"launch_service",
"(",
"root_path",
":",
"Path",
",",
"service_command",
")",
"->",
"Tuple",
"[",
"subprocess",
".",
"Popen",
",",
"Path",
"]",
":",
"# set up KALE_ROOT",
"# invoke correct script",
"# save away PID",
"# we need to pass on the possibly altered KALE_... | [
763,
0
] | [
806,
28
] | python | en | ['en', 'error', 'th'] | False |
singleton | (lockfile: Path, text: str = "semaphore") |
Open a lockfile exclusively.
|
Open a lockfile exclusively.
| def singleton(lockfile: Path, text: str = "semaphore") -> Optional[TextIO]:
"""
Open a lockfile exclusively.
"""
if not lockfile.parent.exists():
mkdir(lockfile.parent)
try:
if has_fcntl:
f = open(lockfile, "w")
fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
... | [
"def",
"singleton",
"(",
"lockfile",
":",
"Path",
",",
"text",
":",
"str",
"=",
"\"semaphore\"",
")",
"->",
"Optional",
"[",
"TextIO",
"]",
":",
"if",
"not",
"lockfile",
".",
"parent",
".",
"exists",
"(",
")",
":",
"mkdir",
"(",
"lockfile",
".",
"par... | [
924,
0
] | [
944,
12
] | python | en | ['en', 'error', 'th'] | False |
WebSocketServer.handle_message | (
self, websocket: WebSocketServerProtocol, message: WsRpcMessage
) |
This function gets called when new message is received via websocket.
|
This function gets called when new message is received via websocket.
| async def handle_message(
self, websocket: WebSocketServerProtocol, message: WsRpcMessage
) -> Tuple[Optional[str], List[Any]]:
"""
This function gets called when new message is received via websocket.
"""
command = message["command"]
destination = message["destinati... | [
"async",
"def",
"handle_message",
"(",
"self",
",",
"websocket",
":",
"WebSocketServerProtocol",
",",
"message",
":",
"WsRpcMessage",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"List",
"[",
"Any",
"]",
"]",
":",
"command",
"=",
"message",
... | [
244,
4
] | [
295,
41
] | python | en | ['en', 'error', 'th'] | False |
WebSocketServer._state_changed | (self, service: str, message: Dict[str, Any]) | If id is None, send the whole state queue | If id is None, send the whole state queue | async def _state_changed(self, service: str, message: Dict[str, Any]):
"""If id is None, send the whole state queue"""
if service not in self.connections:
return None
websockets = self.connections[service]
if message is None:
return None
response = crea... | [
"async",
"def",
"_state_changed",
"(",
"self",
",",
"service",
":",
"str",
",",
"message",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"if",
"service",
"not",
"in",
"self",
".",
"connections",
":",
"return",
"None",
"websockets",
"=",
"self",
... | [
336,
4
] | [
355,
39
] | python | en | ['en', 'en', 'en'] | True |
MessageMiddleware.process_response | (self, request, response) |
Updates the storage backend (i.e., saves the messages).
If not all messages could not be stored and ``DEBUG`` is ``True``, a
``ValueError`` is raised.
|
Updates the storage backend (i.e., saves the messages). | def process_response(self, request, response):
"""
Updates the storage backend (i.e., saves the messages).
If not all messages could not be stored and ``DEBUG`` is ``True``, a
``ValueError`` is raised.
"""
# A higher middleware layer may return a request which does not c... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"# A higher middleware layer may return a request which does not contain",
"# messages storage, so make no assumption that it will be there.",
"if",
"hasattr",
"(",
"request",
",",
"'_messages'",
"... | [
13,
4
] | [
26,
23
] | python | en | ['en', 'error', 'th'] | False |
BaseMemcachedCache._cache | (self) |
Implements transparent thread-safe access to a memcached client.
|
Implements transparent thread-safe access to a memcached client.
| def _cache(self):
"""
Implements transparent thread-safe access to a memcached client.
"""
if getattr(self, '_client', None) is None:
self._client = self._lib.Client(self._servers, **self._options)
return self._client | [
"def",
"_cache",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_client'",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"_client",
"=",
"self",
".",
"_lib",
".",
"Client",
"(",
"self",
".",
"_servers",
",",
"*",
"*",
"self",
"."... | [
32,
4
] | [
39,
27
] | python | en | ['en', 'error', 'th'] | False |
BaseMemcachedCache.get_backend_timeout | (self, timeout=DEFAULT_TIMEOUT) |
Memcached deals with long (> 30 days) timeouts in a special
way. Call this function to obtain a safe value for your timeout.
|
Memcached deals with long (> 30 days) timeouts in a special
way. Call this function to obtain a safe value for your timeout.
| def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):
"""
Memcached deals with long (> 30 days) timeouts in a special
way. Call this function to obtain a safe value for your timeout.
"""
if timeout == DEFAULT_TIMEOUT:
timeout = self.default_timeout
if timeo... | [
"def",
"get_backend_timeout",
"(",
"self",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"if",
"timeout",
"==",
"DEFAULT_TIMEOUT",
":",
"timeout",
"=",
"self",
".",
"default_timeout",
"if",
"timeout",
"is",
"None",
":",
"# Using 0 in memcache sets a non-expiring... | [
41,
4
] | [
66,
27
] | python | en | ['en', 'error', 'th'] | False |
SourceMap._index_for | (self, minified_src: str) | Return the source map index for minified_src, loading it if not
already loaded. | Return the source map index for minified_src, loading it if not
already loaded. | def _index_for(self, minified_src: str) -> Optional[sourcemap.SourceMapDecoder]:
"""Return the source map index for minified_src, loading it if not
already loaded."""
# Prevent path traversal
assert ".." not in minified_src and "/" not in minified_src
if minified_src not in sel... | [
"def",
"_index_for",
"(",
"self",
",",
"minified_src",
":",
"str",
")",
"->",
"Optional",
"[",
"sourcemap",
".",
"SourceMapDecoder",
"]",
":",
"# Prevent path traversal",
"assert",
"\"..\"",
"not",
"in",
"minified_src",
"and",
"\"/\"",
"not",
"in",
"minified_src... | [
16,
4
] | [
41,
46
] | python | en | ['en', 'en', 'en'] | True |
Wheel.__init__ | (self, filename) |
:raises InvalidWheelFilename: when the filename is invalid for a wheel
|
:raises InvalidWheelFilename: when the filename is invalid for a wheel
| def __init__(self, filename):
# type: (str) -> None
"""
:raises InvalidWheelFilename: when the filename is invalid for a wheel
"""
wheel_info = self.wheel_file_re.match(filename)
if not wheel_info:
raise InvalidWheelFilename(
"{} is not a valid... | [
"def",
"__init__",
"(",
"self",
",",
"filename",
")",
":",
"# type: (str) -> None",
"wheel_info",
"=",
"self",
".",
"wheel_file_re",
".",
"match",
"(",
"filename",
")",
"if",
"not",
"wheel_info",
":",
"raise",
"InvalidWheelFilename",
"(",
"\"{} is not a valid whee... | [
24,
4
] | [
48,
9
] | python | en | ['en', 'error', 'th'] | False |
Wheel.get_formatted_file_tags | (self) | Return the wheel's tags as a sorted list of strings. | Return the wheel's tags as a sorted list of strings. | def get_formatted_file_tags(self):
# type: () -> List[str]
"""Return the wheel's tags as a sorted list of strings."""
return sorted(str(tag) for tag in self.file_tags) | [
"def",
"get_formatted_file_tags",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"return",
"sorted",
"(",
"str",
"(",
"tag",
")",
"for",
"tag",
"in",
"self",
".",
"file_tags",
")"
] | [
50,
4
] | [
53,
57
] | python | en | ['en', 'en', 'en'] | True |
Wheel.support_index_min | (self, tags) | Return the lowest index that one of the wheel's file_tag combinations
achieves in the given list of supported tags.
For example, if there are 8 supported tags and one of the file tags
is first in the list, then return 0.
:param tags: the PEP 425 tags to check the wheel against, in orde... | Return the lowest index that one of the wheel's file_tag combinations
achieves in the given list of supported tags. | def support_index_min(self, tags):
# type: (List[Tag]) -> int
"""Return the lowest index that one of the wheel's file_tag combinations
achieves in the given list of supported tags.
For example, if there are 8 supported tags and one of the file tags
is first in the list, then ret... | [
"def",
"support_index_min",
"(",
"self",
",",
"tags",
")",
":",
"# type: (List[Tag]) -> int",
"return",
"min",
"(",
"tags",
".",
"index",
"(",
"tag",
")",
"for",
"tag",
"in",
"self",
".",
"file_tags",
"if",
"tag",
"in",
"tags",
")"
] | [
55,
4
] | [
69,
76
] | python | en | ['en', 'en', 'en'] | True |
Wheel.supported | (self, tags) | Return whether the wheel is compatible with one of the given tags.
:param tags: the PEP 425 tags to check the wheel against.
| Return whether the wheel is compatible with one of the given tags. | def supported(self, tags):
# type: (List[Tag]) -> bool
"""Return whether the wheel is compatible with one of the given tags.
:param tags: the PEP 425 tags to check the wheel against.
"""
return not self.file_tags.isdisjoint(tags) | [
"def",
"supported",
"(",
"self",
",",
"tags",
")",
":",
"# type: (List[Tag]) -> bool",
"return",
"not",
"self",
".",
"file_tags",
".",
"isdisjoint",
"(",
"tags",
")"
] | [
71,
4
] | [
77,
50
] | python | en | ['en', 'en', 'en'] | True |
Hashes.__init__ | (self, hashes=None) |
:param hashes: A dict of algorithm names pointing to lists of allowed
hex digests
|
:param hashes: A dict of algorithm names pointing to lists of allowed
hex digests
| def __init__(self, hashes=None):
# type: (Dict[str, List[str]]) -> None
"""
:param hashes: A dict of algorithm names pointing to lists of allowed
hex digests
"""
allowed = {}
if hashes is not None:
for alg, keys in hashes.items():
#... | [
"def",
"__init__",
"(",
"self",
",",
"hashes",
"=",
"None",
")",
":",
"# type: (Dict[str, List[str]]) -> None",
"allowed",
"=",
"{",
"}",
"if",
"hashes",
"is",
"not",
"None",
":",
"for",
"alg",
",",
"keys",
"in",
"hashes",
".",
"items",
"(",
")",
":",
... | [
35,
4
] | [
46,
31
] | python | en | ['en', 'error', 'th'] | False |
Hashes.is_hash_allowed | (
self,
hash_name, # type: str
hex_digest, # type: str
) | Return whether the given hex digest is allowed. | Return whether the given hex digest is allowed. | def is_hash_allowed(
self,
hash_name, # type: str
hex_digest, # type: str
):
# type: (...) -> bool
"""Return whether the given hex digest is allowed."""
return hex_digest in self._allowed.get(hash_name, []) | [
"def",
"is_hash_allowed",
"(",
"self",
",",
"hash_name",
",",
"# type: str",
"hex_digest",
",",
"# type: str",
")",
":",
"# type: (...) -> bool",
"return",
"hex_digest",
"in",
"self",
".",
"_allowed",
".",
"get",
"(",
"hash_name",
",",
"[",
"]",
")"
] | [
73,
4
] | [
80,
61
] | python | en | ['en', 'en', 'en'] | True |
Hashes.check_against_chunks | (self, chunks) | Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
| Check good hashes against ones built from iterable of chunks of
data. | def check_against_chunks(self, chunks):
# type: (Iterator[bytes]) -> None
"""Check good hashes against ones built from iterable of chunks of
data.
Raise HashMismatch if none match.
"""
gots = {}
for hash_name in iterkeys(self._allowed):
try:
... | [
"def",
"check_against_chunks",
"(",
"self",
",",
"chunks",
")",
":",
"# type: (Iterator[bytes]) -> None",
"gots",
"=",
"{",
"}",
"for",
"hash_name",
"in",
"iterkeys",
"(",
"self",
".",
"_allowed",
")",
":",
"try",
":",
"gots",
"[",
"hash_name",
"]",
"=",
"... | [
82,
4
] | [
106,
25
] | python | en | ['en', 'en', 'en'] | True |
Hashes.check_against_file | (self, file) | Check good hashes against a file-like object
Raise HashMismatch if none match.
| Check good hashes against a file-like object | def check_against_file(self, file):
# type: (BinaryIO) -> None
"""Check good hashes against a file-like object
Raise HashMismatch if none match.
"""
return self.check_against_chunks(read_chunks(file)) | [
"def",
"check_against_file",
"(",
"self",
",",
"file",
")",
":",
"# type: (BinaryIO) -> None",
"return",
"self",
".",
"check_against_chunks",
"(",
"read_chunks",
"(",
"file",
")",
")"
] | [
112,
4
] | [
119,
59
] | python | en | ['en', 'en', 'en'] | True |
Hashes.__nonzero__ | (self) | Return whether I know any known-good hashes. | Return whether I know any known-good hashes. | def __nonzero__(self):
# type: () -> bool
"""Return whether I know any known-good hashes."""
return bool(self._allowed) | [
"def",
"__nonzero__",
"(",
"self",
")",
":",
"# type: () -> bool",
"return",
"bool",
"(",
"self",
".",
"_allowed",
")"
] | [
126,
4
] | [
129,
34
] | python | en | ['en', 'en', 'en'] | True |
MissingHashes.__init__ | (self) | Don't offer the ``hashes`` kwarg. | Don't offer the ``hashes`` kwarg. | def __init__(self):
# type: () -> None
"""Don't offer the ``hashes`` kwarg."""
# Pass our favorite hash in to generate a "gotten hash". With the
# empty list, it will never match, so an error will always raise.
super(MissingHashes, self).__init__(hashes={FAVORITE_HASH: []}) | [
"def",
"__init__",
"(",
"self",
")",
":",
"# type: () -> None",
"# Pass our favorite hash in to generate a \"gotten hash\". With the",
"# empty list, it will never match, so an error will always raise.",
"super",
"(",
"MissingHashes",
",",
"self",
")",
".",
"__init__",
"(",
"hash... | [
159,
4
] | [
164,
71
] | python | en | ['en', 'en', 'sw'] | True |
_find_all_simple | (path) |
Find all files under 'path'
|
Find all files under 'path'
| def _find_all_simple(path):
"""
Find all files under 'path'
"""
results = (
os.path.join(base, file)
for base, dirs, files in os.walk(path, followlinks=True)
for file in files
)
return filter(os.path.isfile, results) | [
"def",
"_find_all_simple",
"(",
"path",
")",
":",
"results",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"file",
")",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"followlinks",
"=",
"True",
... | [
211,
0
] | [
220,
42
] | python | en | ['en', 'error', 'th'] | False |
findall | (dir=os.curdir) |
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
|
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
| def findall(dir=os.curdir):
"""
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
"""
files = _find_all_simple(dir)
if dir == os.curdir:
make_rel = functools.partial(os.path.relpath, start=dir)
files = m... | [
"def",
"findall",
"(",
"dir",
"=",
"os",
".",
"curdir",
")",
":",
"files",
"=",
"_find_all_simple",
"(",
"dir",
")",
"if",
"dir",
"==",
"os",
".",
"curdir",
":",
"make_rel",
"=",
"functools",
".",
"partial",
"(",
"os",
".",
"path",
".",
"relpath",
... | [
223,
0
] | [
232,
22
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.find | (cls, where='.', exclude=(), include=('*',)) | Return a list all Python packages found within directory 'where'
'where' is the root directory which will be searched for packages. It
should be supplied as a "cross-platform" (i.e. URL-style) path; it will
be converted to the appropriate local path syntax.
'exclude' is a sequence of ... | Return a list all Python packages found within directory 'where' | def find(cls, where='.', exclude=(), include=('*',)):
"""Return a list all Python packages found within directory 'where'
'where' is the root directory which will be searched for packages. It
should be supplied as a "cross-platform" (i.e. URL-style) path; it will
be converted to the ap... | [
"def",
"find",
"(",
"cls",
",",
"where",
"=",
"'.'",
",",
"exclude",
"=",
"(",
")",
",",
"include",
"=",
"(",
"'*'",
",",
")",
")",
":",
"return",
"list",
"(",
"cls",
".",
"_find_packages_iter",
"(",
"convert_path",
"(",
"where",
")",
",",
"cls",
... | [
45,
4
] | [
65,
41
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder._find_packages_iter | (cls, where, exclude, include) |
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
|
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
| def _find_packages_iter(cls, where, exclude, include):
"""
All the packages found in 'where' that pass the 'include' filter, but
not the 'exclude' filter.
"""
for root, dirs, files in os.walk(where, followlinks=True):
# Copy dirs to iterate over it, then empty dirs.
... | [
"def",
"_find_packages_iter",
"(",
"cls",
",",
"where",
",",
"exclude",
",",
"include",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"where",
",",
"followlinks",
"=",
"True",
")",
":",
"# Copy dirs to iterate over it, t... | [
68,
4
] | [
93,
32
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder._looks_like_package | (path) | Does a directory look like a package? | Does a directory look like a package? | def _looks_like_package(path):
"""Does a directory look like a package?"""
return os.path.isfile(os.path.join(path, '__init__.py')) | [
"def",
"_looks_like_package",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'__init__.py'",
")",
")"
] | [
96,
4
] | [
98,
64
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder._build_filter | (*patterns) |
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
|
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
| def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns) | [
"def",
"_build_filter",
"(",
"*",
"patterns",
")",
":",
"return",
"lambda",
"name",
":",
"any",
"(",
"fnmatchcase",
"(",
"name",
",",
"pat",
"=",
"pat",
")",
"for",
"pat",
"in",
"patterns",
")"
] | [
101,
4
] | [
106,
79
] | python | en | ['en', 'error', 'th'] | False |
Command.__init__ | (self, dist, **kw) |
Construct the command for dist, updating
vars(self) with any keyword parameters.
|
Construct the command for dist, updating
vars(self) with any keyword parameters.
| def __init__(self, dist, **kw):
"""
Construct the command for dist, updating
vars(self) with any keyword parameters.
"""
_Command.__init__(self, dist)
vars(self).update(kw) | [
"def",
"__init__",
"(",
"self",
",",
"dist",
",",
"*",
"*",
"kw",
")",
":",
"_Command",
".",
"__init__",
"(",
"self",
",",
"dist",
")",
"vars",
"(",
"self",
")",
".",
"update",
"(",
"kw",
")"
] | [
166,
4
] | [
172,
29
] | python | en | ['en', 'error', 'th'] | False |
Command.ensure_string_list | (self, option) | r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
| r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
| def ensure_string_list(self, option):
r"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
"""
val = getattr(self, ... | [
"def",
"ensure_string_list",
"(",
"self",
",",
"option",
")",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"option",
")",
"if",
"val",
"is",
"None",
":",
"return",
"elif",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"setattr",
"(",
"self",
",",
... | [
184,
4
] | [
203,
36
] | python | en | ['en', 'en', 'en'] | True |
VendorImporter.search_path | (self) |
Search first the vendor package then as a natural package.
|
Search first the vendor package then as a natural package.
| def search_path(self):
"""
Search first the vendor package then as a natural package.
"""
yield self.vendor_pkg + '.'
yield '' | [
"def",
"search_path",
"(",
"self",
")",
":",
"yield",
"self",
".",
"vendor_pkg",
"+",
"'.'",
"yield",
"''"
] | [
15,
4
] | [
20,
16
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.find_module | (self, fullname, path=None) |
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
|
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
| def find_module(self, fullname, path=None):
"""
Return self when fullname starts with root_name and the
target module is one vendored through this importer.
"""
root, base, target = fullname.partition(self.root_name + '.')
if root:
return
if not any(ma... | [
"def",
"find_module",
"(",
"self",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"if",
"root",
":",
"return",
"if",
"not",
... | [
22,
4
] | [
32,
19
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.load_module | (self, fullname) |
Iterate over the search path to locate and load fullname.
|
Iterate over the search path to locate and load fullname.
| def load_module(self, fullname):
"""
Iterate over the search path to locate and load fullname.
"""
root, base, target = fullname.partition(self.root_name + '.')
for prefix in self.search_path:
try:
extant = prefix + target
__import__(ex... | [
"def",
"load_module",
"(",
"self",
",",
"fullname",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"for",
"prefix",
"in",
"self",
".",
"search_path",
":",
"try",
":",
"... | [
34,
4
] | [
54,
13
] | python | en | ['en', 'error', 'th'] | False |
VendorImporter.install | (self) |
Install this importer into sys.meta_path if not already present.
|
Install this importer into sys.meta_path if not already present.
| def install(self):
"""
Install this importer into sys.meta_path if not already present.
"""
if self not in sys.meta_path:
sys.meta_path.append(self) | [
"def",
"install",
"(",
"self",
")",
":",
"if",
"self",
"not",
"in",
"sys",
".",
"meta_path",
":",
"sys",
".",
"meta_path",
".",
"append",
"(",
"self",
")"
] | [
56,
4
] | [
61,
38
] | python | en | ['en', 'error', 'th'] | False |
default_test_processes | () |
Default number of test processes when using the --parallel option.
|
Default number of test processes when using the --parallel option.
| def default_test_processes():
"""
Default number of test processes when using the --parallel option.
"""
# The current implementation of the parallel test runner requires
# multiprocessing to start subprocesses with fork().
# On Python 3.4+: if multiprocessing.get_start_method() != 'fork':
i... | [
"def",
"default_test_processes",
"(",
")",
":",
"# The current implementation of the parallel test runner requires",
"# multiprocessing to start subprocesses with fork().",
"# On Python 3.4+: if multiprocessing.get_start_method() != 'fork':",
"if",
"not",
"hasattr",
"(",
"os",
",",
"'for... | [
254,
0
] | [
266,
42
] | python | en | ['en', 'error', 'th'] | False |
_init_worker | (counter) |
Switch to databases dedicated to this worker.
This helper lives at module-level because of the multiprocessing module's
requirements.
|
Switch to databases dedicated to this worker. | def _init_worker(counter):
"""
Switch to databases dedicated to this worker.
This helper lives at module-level because of the multiprocessing module's
requirements.
"""
global _worker_id
with counter.get_lock():
counter.value += 1
_worker_id = counter.value
for alias ... | [
"def",
"_init_worker",
"(",
"counter",
")",
":",
"global",
"_worker_id",
"with",
"counter",
".",
"get_lock",
"(",
")",
":",
"counter",
".",
"value",
"+=",
"1",
"_worker_id",
"=",
"counter",
".",
"value",
"for",
"alias",
"in",
"connections",
":",
"connectio... | [
272,
0
] | [
294,
26
] | python | en | ['en', 'error', 'th'] | False |
_run_subsuite | (args) |
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
This helper lives at module-level and its arguments are wrapped in a tuple
because of the multiprocessing module's requirements.
|
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. | def _run_subsuite(args):
"""
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
This helper lives at module-level and its arguments are wrapped in a tuple
because of the multiprocessing module's requirements.
"""
runner_class, subsuite_index, subsuite, failfast = args
... | [
"def",
"_run_subsuite",
"(",
"args",
")",
":",
"runner_class",
",",
"subsuite_index",
",",
"subsuite",
",",
"failfast",
"=",
"args",
"runner",
"=",
"runner_class",
"(",
"failfast",
"=",
"failfast",
")",
"result",
"=",
"runner",
".",
"run",
"(",
"subsuite",
... | [
297,
0
] | [
307,
40
] | python | en | ['en', 'error', 'th'] | False |
is_discoverable | (label) |
Check if a test label points to a python package or file directory.
Relative labels like "." and ".." are seen as directories.
|
Check if a test label points to a python package or file directory. | def is_discoverable(label):
"""
Check if a test label points to a python package or file directory.
Relative labels like "." and ".." are seen as directories.
"""
try:
mod = import_module(label)
except (ImportError, TypeError):
pass
else:
return hasattr(mod, '__path_... | [
"def",
"is_discoverable",
"(",
"label",
")",
":",
"try",
":",
"mod",
"=",
"import_module",
"(",
"label",
")",
"except",
"(",
"ImportError",
",",
"TypeError",
")",
":",
"pass",
"else",
":",
"return",
"hasattr",
"(",
"mod",
",",
"'__path__'",
")",
"return"... | [
608,
0
] | [
621,
48
] | python | en | ['en', 'error', 'th'] | False |
reorder_suite | (suite, classes, reverse=False) |
Reorders a test suite by test type.
`classes` is a sequence of types
All tests of type classes[0] are placed first, then tests of type
classes[1], etc. Tests with no match in classes are placed last.
If `reverse` is True, tests within classes are sorted in opposite order,
but test classes ar... |
Reorders a test suite by test type. | def reorder_suite(suite, classes, reverse=False):
"""
Reorders a test suite by test type.
`classes` is a sequence of types
All tests of type classes[0] are placed first, then tests of type
classes[1], etc. Tests with no match in classes are placed last.
If `reverse` is True, tests within clas... | [
"def",
"reorder_suite",
"(",
"suite",
",",
"classes",
",",
"reverse",
"=",
"False",
")",
":",
"class_count",
"=",
"len",
"(",
"classes",
")",
"suite_class",
"=",
"type",
"(",
"suite",
")",
"bins",
"=",
"[",
"OrderedSet",
"(",
")",
"for",
"i",
"in",
"... | [
624,
0
] | [
643,
26
] | python | en | ['en', 'error', 'th'] | False |
partition_suite_by_type | (suite, classes, bins, reverse=False) |
Partitions a test suite by test type. Also prevents duplicated tests.
classes is a sequence of types
bins is a sequence of TestSuites, one more than classes
reverse changes the ordering of tests within bins
Tests of type classes[i] are added to bins[i],
tests with no match found in classes ar... |
Partitions a test suite by test type. Also prevents duplicated tests. | def partition_suite_by_type(suite, classes, bins, reverse=False):
"""
Partitions a test suite by test type. Also prevents duplicated tests.
classes is a sequence of types
bins is a sequence of TestSuites, one more than classes
reverse changes the ordering of tests within bins
Tests of type cla... | [
"def",
"partition_suite_by_type",
"(",
"suite",
",",
"classes",
",",
"bins",
",",
"reverse",
"=",
"False",
")",
":",
"suite_class",
"=",
"type",
"(",
"suite",
")",
"if",
"reverse",
":",
"suite",
"=",
"reversed",
"(",
"tuple",
"(",
"suite",
")",
")",
"f... | [
646,
0
] | [
669,
34
] | python | en | ['en', 'error', 'th'] | False |
partition_suite_by_case | (suite) |
Partitions a test suite by test case, preserving the order of tests.
|
Partitions a test suite by test case, preserving the order of tests.
| def partition_suite_by_case(suite):
"""
Partitions a test suite by test case, preserving the order of tests.
"""
groups = []
suite_class = type(suite)
for test_type, test_group in itertools.groupby(suite, type):
if issubclass(test_type, unittest.TestCase):
groups.append(suite... | [
"def",
"partition_suite_by_case",
"(",
"suite",
")",
":",
"groups",
"=",
"[",
"]",
"suite_class",
"=",
"type",
"(",
"suite",
")",
"for",
"test_type",
",",
"test_group",
"in",
"itertools",
".",
"groupby",
"(",
"suite",
",",
"type",
")",
":",
"if",
"issubc... | [
672,
0
] | [
684,
17
] | python | en | ['en', 'error', 'th'] | False |
RemoteTestResult._confirm_picklable | (self, obj) |
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
|
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
| def _confirm_picklable(self, obj):
"""
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
"""
pickle.loads(pickle.dumps(obj)) | [
"def",
"_confirm_picklable",
"(",
"self",
",",
"obj",
")",
":",
"pickle",
".",
"loads",
"(",
"pickle",
".",
"dumps",
"(",
"obj",
")",
")"
] | [
92,
4
] | [
98,
39
] | python | en | ['en', 'error', 'th'] | False |
ParallelTestSuite.run | (self, result) |
Distribute test cases across workers.
Return an identifier of each test case with its result in order to use
imap_unordered to show results as soon as they're available.
To minimize pickling errors when getting results from workers:
- pass back numeric indexes in self.subsuit... |
Distribute test cases across workers. | def run(self, result):
"""
Distribute test cases across workers.
Return an identifier of each test case with its result in order to use
imap_unordered to show results as soon as they're available.
To minimize pickling errors when getting results from workers:
- pass ba... | [
"def",
"run",
"(",
"self",
",",
"result",
")",
":",
"counter",
"=",
"multiprocessing",
".",
"Value",
"(",
"ctypes",
".",
"c_int",
",",
"0",
")",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"processes",
"=",
"self",
".",
"processes",
",",
"initial... | [
337,
4
] | [
388,
21
] | python | en | ['en', 'error', 'th'] | False |
DiscoverRunner.teardown_databases | (self, old_config, **kwargs) |
Destroys all the non-mirror databases.
|
Destroys all the non-mirror databases.
| def teardown_databases(self, old_config, **kwargs):
"""
Destroys all the non-mirror databases.
"""
_teardown_databases(
old_config,
verbosity=self.verbosity,
parallel=self.parallel,
keepdb=self.keepdb,
) | [
"def",
"teardown_databases",
"(",
"self",
",",
"old_config",
",",
"*",
"*",
"kwargs",
")",
":",
"_teardown_databases",
"(",
"old_config",
",",
"verbosity",
"=",
"self",
".",
"verbosity",
",",
"parallel",
"=",
"self",
".",
"parallel",
",",
"keepdb",
"=",
"s... | [
568,
4
] | [
577,
9
] | python | en | ['en', 'error', 'th'] | False |
DiscoverRunner.run_tests | (self, test_labels, extra_tests=None, **kwargs) |
Run the unit tests for all the test labels in the provided list.
Test labels should be dotted Python paths to test modules, test
classes, or test methods.
A list of 'extra' tests may also be provided; these tests
will be added to the test suite.
Returns the number of ... |
Run the unit tests for all the test labels in the provided list. | def run_tests(self, test_labels, extra_tests=None, **kwargs):
"""
Run the unit tests for all the test labels in the provided list.
Test labels should be dotted Python paths to test modules, test
classes, or test methods.
A list of 'extra' tests may also be provided; these tests... | [
"def",
"run_tests",
"(",
"self",
",",
"test_labels",
",",
"extra_tests",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"setup_test_environment",
"(",
")",
"suite",
"=",
"self",
".",
"build_suite",
"(",
"test_labels",
",",
"extra_tests",
")",... | [
586,
4
] | [
605,
47
] | python | en | ['en', 'error', 'th'] | False |
database_disabled | () | Return ``True`` if the database is disabled for test purposes. | Return ``True`` if the database is disabled for test purposes. | def database_disabled():
"""Return ``True`` if the database is disabled for test purposes."""
return os.environ.get("TKP_DISABLEDB", False) | [
"def",
"database_disabled",
"(",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"\"TKP_DISABLEDB\"",
",",
"False",
")"
] | [
4,
0
] | [
6,
49
] | python | en | ['en', 'en', 'en'] | True |
requires_test_db_managed | () |
This decorator is used to disable tests that do potentially low level
database management operations like destroy and create. You can enable
these tests by setting the TKP_TESTDBMANAGEMENT environment variable.
|
This decorator is used to disable tests that do potentially low level
database management operations like destroy and create. You can enable
these tests by setting the TKP_TESTDBMANAGEMENT environment variable.
| def requires_test_db_managed():
"""
This decorator is used to disable tests that do potentially low level
database management operations like destroy and create. You can enable
these tests by setting the TKP_TESTDBMANAGEMENT environment variable.
"""
if os.environ.get("TKP_TESTDBMANAGEMENT", Fa... | [
"def",
"requires_test_db_managed",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"TKP_TESTDBMANAGEMENT\"",
",",
"False",
")",
":",
"return",
"lambda",
"func",
":",
"func",
"return",
"unittest",
".",
"skip",
"(",
"\"DB management tests disabled, T... | [
40,
0
] | [
50,
36
] | python | en | ['en', 'error', 'th'] | False |
high_ram_requirements | () |
Used to disable tests that break Travis due to out-of-memory issues.
|
Used to disable tests that break Travis due to out-of-memory issues.
| def high_ram_requirements():
"""
Used to disable tests that break Travis due to out-of-memory issues.
"""
if os.environ.get("TRAVIS", False):
return unittest.skip("High-ram requirement unit-tests disabled on Travis")
return lambda func: func | [
"def",
"high_ram_requirements",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"TRAVIS\"",
",",
"False",
")",
":",
"return",
"unittest",
".",
"skip",
"(",
"\"High-ram requirement unit-tests disabled on Travis\"",
")",
"return",
"lambda",
"func",
"... | [
52,
0
] | [
58,
28
] | python | en | ['en', 'error', 'th'] | False |
spread_purelib_into_root | (wheel_dir: str) | Unpacks purelib directories into the root.
Args:
wheel_dir: The root of the extracted wheel directory.
| Unpacks purelib directories into the root. | def spread_purelib_into_root(wheel_dir: str) -> None:
"""Unpacks purelib directories into the root.
Args:
wheel_dir: The root of the extracted wheel directory.
"""
dist_info = wheel.get_dist_info(wheel_dir)
wheel_metadata_file_path = pathlib.Path(dist_info, "WHEEL")
wheel_metadata_dict... | [
"def",
"spread_purelib_into_root",
"(",
"wheel_dir",
":",
"str",
")",
"->",
"None",
":",
"dist_info",
"=",
"wheel",
".",
"get_dist_info",
"(",
"wheel_dir",
")",
"wheel_metadata_file_path",
"=",
"pathlib",
".",
"Path",
"(",
"dist_info",
",",
"\"WHEEL\"",
")",
"... | [
7,
0
] | [
37,
45
] | python | en | ['en', 'la', 'en'] | True |
_spread_purelib | (purelib_dir: pathlib.Path, root_dir: str) | Recursively moves all sibling directories of the purelib to the root.
Args:
purelib_dir: The directory of the purelib.
root_dir: The directory to move files into.
| Recursively moves all sibling directories of the purelib to the root. | def _spread_purelib(purelib_dir: pathlib.Path, root_dir: str) -> None:
"""Recursively moves all sibling directories of the purelib to the root.
Args:
purelib_dir: The directory of the purelib.
root_dir: The directory to move files into.
"""
for grandchild in purelib_dir.iterdir():
... | [
"def",
"_spread_purelib",
"(",
"purelib_dir",
":",
"pathlib",
".",
"Path",
",",
"root_dir",
":",
"str",
")",
"->",
"None",
":",
"for",
"grandchild",
"in",
"purelib_dir",
".",
"iterdir",
"(",
")",
":",
"# Some purelib Wheels, like Tensorflow 2.0.0, have directories",... | [
40,
0
] | [
55,
13
] | python | en | ['en', 'en', 'en'] | True |
WorkflowJobNode.wait_for_job | (self, interval=5, timeout=60, **kw) | Waits until node's job exists | Waits until node's job exists | def wait_for_job(self, interval=5, timeout=60, **kw):
"""Waits until node's job exists"""
adjusted_timeout = timeout - seconds_since_date_string(self.created)
poll_until(self.job_exists, interval=interval, timeout=adjusted_timeout, **kw)
return self | [
"def",
"wait_for_job",
"(",
"self",
",",
"interval",
"=",
"5",
",",
"timeout",
"=",
"60",
",",
"*",
"*",
"kw",
")",
":",
"adjusted_timeout",
"=",
"timeout",
"-",
"seconds_since_date_string",
"(",
"self",
".",
"created",
")",
"poll_until",
"(",
"self",
".... | [
7,
4
] | [
13,
19
] | python | en | ['en', 'ca', 'en'] | True |
SubstituteInfTestCase.test_not_inf | (self) |
Non-inf returned unchanged.
|
Non-inf returned unchanged.
| def test_not_inf(self):
"""
Non-inf returned unchanged.
"""
value = 1
self.assertEqual(substitute_inf(value), value) | [
"def",
"test_not_inf",
"(",
"self",
")",
":",
"value",
"=",
"1",
"self",
".",
"assertEqual",
"(",
"substitute_inf",
"(",
"value",
")",
",",
"value",
")"
] | [
34,
4
] | [
39,
54
] | python | en | ['en', 'error', 'th'] | False |
SubstituteInfTestCase.test_inf | (self) |
inf substituted to "Infinity".
|
inf substituted to "Infinity".
| def test_inf(self):
"""
inf substituted to "Infinity".
"""
value = float("inf")
self.assertEqual(substitute_inf(value), "Infinity") | [
"def",
"test_inf",
"(",
"self",
")",
":",
"value",
"=",
"float",
"(",
"\"inf\"",
")",
"self",
".",
"assertEqual",
"(",
"substitute_inf",
"(",
"value",
")",
",",
"\"Infinity\"",
")"
] | [
41,
4
] | [
46,
59
] | python | en | ['en', 'error', 'th'] | False |
SubstituteInfTestCase.test_non_default_subst | (self) |
NaN substitute to non default.
|
NaN substitute to non default.
| def test_non_default_subst(self):
"""
NaN substitute to non default.
"""
value = float("inf")
self.assertEqual(substitute_inf(value, 99), 99) | [
"def",
"test_non_default_subst",
"(",
"self",
")",
":",
"value",
"=",
"float",
"(",
"\"inf\"",
")",
"self",
".",
"assertEqual",
"(",
"substitute_inf",
"(",
"value",
",",
"99",
")",
",",
"99",
")"
] | [
48,
4
] | [
53,
55
] | python | en | ['en', 'error', 'th'] | False |
SubstituteNanTestCase.test_not_nan | (self) |
Non-NaN returned unchanged.
|
Non-NaN returned unchanged.
| def test_not_nan(self):
"""
Non-NaN returned unchanged.
"""
value = 1
self.assertEqual(substitute_nan(value), value) | [
"def",
"test_not_nan",
"(",
"self",
")",
":",
"value",
"=",
"1",
"self",
".",
"assertEqual",
"(",
"substitute_nan",
"(",
"value",
")",
",",
"value",
")"
] | [
56,
4
] | [
61,
54
] | python | en | ['en', 'error', 'th'] | False |
SubstituteNanTestCase.test_nan | (self) |
NaN substituted to 0.
|
NaN substituted to 0.
| def test_nan(self):
"""
NaN substituted to 0.
"""
value = float("nan")
self.assertEqual(substitute_nan(value), 0.0) | [
"def",
"test_nan",
"(",
"self",
")",
":",
"value",
"=",
"float",
"(",
"\"nan\"",
")",
"self",
".",
"assertEqual",
"(",
"substitute_nan",
"(",
"value",
")",
",",
"0.0",
")"
] | [
63,
4
] | [
68,
52
] | python | en | ['en', 'error', 'th'] | False |
SubstituteNanTestCase.test_non_default_subst | (self) |
NaN substitute to non default.
|
NaN substitute to non default.
| def test_non_default_subst(self):
"""
NaN substitute to non default.
"""
value = float("nan")
self.assertEqual(substitute_nan(value, 99), 99) | [
"def",
"test_non_default_subst",
"(",
"self",
")",
":",
"value",
"=",
"float",
"(",
"\"nan\"",
")",
"self",
".",
"assertEqual",
"(",
"substitute_nan",
"(",
"value",
",",
"99",
")",
",",
"99",
")"
] | [
70,
4
] | [
75,
55
] | python | en | ['en', 'error', 'th'] | False |
bech32_polymod | (values: List[int]) | Internal function that computes the Bech32 checksum. | Internal function that computes the Bech32 checksum. | def bech32_polymod(values: List[int]) -> int:
"""Internal function that computes the Bech32 checksum."""
generator = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1FFFFFF) << 5 ^ value
for i in range(5):
... | [
"def",
"bech32_polymod",
"(",
"values",
":",
"List",
"[",
"int",
"]",
")",
"->",
"int",
":",
"generator",
"=",
"[",
"0x3B6A57B2",
",",
"0x26508E6D",
",",
"0x1EA119FA",
",",
"0x3D4233DD",
",",
"0x2A1462B3",
"]",
"chk",
"=",
"1",
"for",
"value",
"in",
"v... | [
31,
0
] | [
40,
14
] | python | en | ['en', 'en', 'en'] | True |
bech32_hrp_expand | (hrp: str) | Expand the HRP into values for checksum computation. | Expand the HRP into values for checksum computation. | def bech32_hrp_expand(hrp: str) -> List[int]:
"""Expand the HRP into values for checksum computation."""
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] | [
"def",
"bech32_hrp_expand",
"(",
"hrp",
":",
"str",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"[",
"ord",
"(",
"x",
")",
">>",
"5",
"for",
"x",
"in",
"hrp",
"]",
"+",
"[",
"0",
"]",
"+",
"[",
"ord",
"(",
"x",
")",
"&",
"31",
"for",... | [
43,
0
] | [
45,
72
] | python | en | ['en', 'en', 'en'] | True |
bech32_encode | (hrp: str, data: List[int]) | Compute a Bech32 string given HRP and data values. | Compute a Bech32 string given HRP and data values. | def bech32_encode(hrp: str, data: List[int]) -> str:
"""Compute a Bech32 string given HRP and data values."""
combined = data + bech32_create_checksum(hrp, data)
return hrp + "1" + "".join([CHARSET[d] for d in combined]) | [
"def",
"bech32_encode",
"(",
"hrp",
":",
"str",
",",
"data",
":",
"List",
"[",
"int",
"]",
")",
"->",
"str",
":",
"combined",
"=",
"data",
"+",
"bech32_create_checksum",
"(",
"hrp",
",",
"data",
")",
"return",
"hrp",
"+",
"\"1\"",
"+",
"\"\"",
".",
... | [
61,
0
] | [
64,
62
] | python | en | ['en', 'en', 'en'] | True |
bech32_decode | (bech: str) | Validate a Bech32 string, and determine HRP and data. | Validate a Bech32 string, and determine HRP and data. | def bech32_decode(bech: str) -> Tuple[Optional[str], Optional[List[int]]]:
"""Validate a Bech32 string, and determine HRP and data."""
if (any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech):
return (None, None)
bech = bech.lower()
pos = bech.rfind(... | [
"def",
"bech32_decode",
"(",
"bech",
":",
"str",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"]",
":",
"if",
"(",
"any",
"(",
"ord",
"(",
"x",
")",
"<",
"33",
"or",
"ord",
"(",
"x"... | [
67,
0
] | [
81,
25
] | python | en | ['en', 'en', 'en'] | True |
convertbits | (data: List[int], frombits: int, tobits: int, pad: bool = True) | General power-of-2 base conversion. | General power-of-2 base conversion. | def convertbits(data: List[int], frombits: int, tobits: int, pad: bool = True) -> List[int]:
"""General power-of-2 base conversion."""
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits... | [
"def",
"convertbits",
"(",
"data",
":",
"List",
"[",
"int",
"]",
",",
"frombits",
":",
"int",
",",
"tobits",
":",
"int",
",",
"pad",
":",
"bool",
"=",
"True",
")",
"->",
"List",
"[",
"int",
"]",
":",
"acc",
"=",
"0",
"bits",
"=",
"0",
"ret",
... | [
84,
0
] | [
104,
14
] | python | en | ['pl', 'en', 'en'] | True |
_update_m2m_from_groups | (user, ldap_user, related, opts, remove=True) |
Hepler function to update m2m relationship based on LDAP group membership.
|
Hepler function to update m2m relationship based on LDAP group membership.
| def _update_m2m_from_groups(user, ldap_user, related, opts, remove=True):
"""
Hepler function to update m2m relationship based on LDAP group membership.
"""
should_add = False
if opts is None:
return
elif not opts:
pass
elif opts is True:
should_add = True
else:
... | [
"def",
"_update_m2m_from_groups",
"(",
"user",
",",
"ldap_user",
",",
"related",
",",
"opts",
",",
"remove",
"=",
"True",
")",
":",
"should_add",
"=",
"False",
"if",
"opts",
"is",
"None",
":",
"return",
"elif",
"not",
"opts",
":",
"pass",
"elif",
"opts",... | [
315,
0
] | [
339,
28
] | python | en | ['en', 'error', 'th'] | False |
on_populate_user | (sender, **kwargs) |
Handle signal from LDAP backend to populate the user object. Update user
organization/team memberships according to their LDAP groups.
|
Handle signal from LDAP backend to populate the user object. Update user
organization/team memberships according to their LDAP groups.
| def on_populate_user(sender, **kwargs):
"""
Handle signal from LDAP backend to populate the user object. Update user
organization/team memberships according to their LDAP groups.
"""
from awx.main.models import Organization, Team
user = kwargs['user']
ldap_user = kwargs['ldap_user']
ba... | [
"def",
"on_populate_user",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"awx",
".",
"main",
".",
"models",
"import",
"Organization",
",",
"Team",
"user",
"=",
"kwargs",
"[",
"'user'",
"]",
"ldap_user",
"=",
"kwargs",
"[",
"'ldap_user'",
"]",... | [
343,
0
] | [
410,
22
] | python | en | ['en', 'error', 'th'] | False |
TowerSAMLIdentityProvider.get_attr | (self, attributes, conf_key, default_attribute) |
Get the attribute 'default_attribute' out of the attributes,
unless self.conf[conf_key] overrides the default by specifying
another attribute to use.
|
Get the attribute 'default_attribute' out of the attributes,
unless self.conf[conf_key] overrides the default by specifying
another attribute to use.
| def get_attr(self, attributes, conf_key, default_attribute):
"""
Get the attribute 'default_attribute' out of the attributes,
unless self.conf[conf_key] overrides the default by specifying
another attribute to use.
"""
key = self.conf.get(conf_key, default_attribute)
... | [
"def",
"get_attr",
"(",
"self",
",",
"attributes",
",",
"conf_key",
",",
"default_attribute",
")",
":",
"key",
"=",
"self",
".",
"conf",
".",
"get",
"(",
"conf_key",
",",
"default_attribute",
")",
"value",
"=",
"attributes",
"[",
"key",
"]",
"if",
"key",... | [
247,
4
] | [
266,
57
] | python | en | ['en', 'error', 'th'] | False |
create_command | (name, **kwargs) |
Create an instance of the Command class with the given name.
|
Create an instance of the Command class with the given name.
| def create_command(name, **kwargs):
# type: (str, **Any) -> Command
"""
Create an instance of the Command class with the given name.
"""
module_path, class_name, summary = commands_dict[name]
module = importlib.import_module(module_path)
command_class = getattr(module, class_name)
comman... | [
"def",
"create_command",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (str, **Any) -> Command",
"module_path",
",",
"class_name",
",",
"summary",
"=",
"commands_dict",
"[",
"name",
"]",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_p... | [
98,
0
] | [
108,
18
] | python | en | ['en', 'error', 'th'] | False |
get_similar_commands | (name) | Command name auto-correct. | Command name auto-correct. | def get_similar_commands(name):
"""Command name auto-correct."""
from difflib import get_close_matches
name = name.lower()
close_commands = get_close_matches(name, commands_dict.keys())
if close_commands:
return close_commands[0]
else:
return False | [
"def",
"get_similar_commands",
"(",
"name",
")",
":",
"from",
"difflib",
"import",
"get_close_matches",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"close_commands",
"=",
"get_close_matches",
"(",
"name",
",",
"commands_dict",
".",
"keys",
"(",
")",
")",
"i... | [
111,
0
] | [
122,
20
] | python | en | ['en', 'sm', 'en'] | True |
Conv.__init__ | (self, args) |
TODO: Write Comment
|
TODO: Write Comment
| def __init__(self, args):
"""
TODO: Write Comment
"""
self.name = 'Convolutional'
self.learn_rate = 0.001
MnistModel.__init__(self, args) | [
"def",
"__init__",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"name",
"=",
"'Convolutional'",
"self",
".",
"learn_rate",
"=",
"0.001",
"MnistModel",
".",
"__init__",
"(",
"self",
",",
"args",
")"
] | [
10,
4
] | [
19,
39
] | python | en | ['en', 'error', 'th'] | False |
Conv.network | (self, img_input) |
TODO: Write Comment
|
TODO: Write Comment
| def network(self, img_input):
"""
TODO: Write Comment
"""
from tensorflow.keras import initializers, layers, regularizers
weight_decay = 0.0001
x = layers.Conv2D(32, (5,5), padding='valid', kernel_initializer=initializers.he_normal(), kernel_regularizer=regularizers.l2... | [
"def",
"network",
"(",
"self",
",",
"img_input",
")",
":",
"from",
"tensorflow",
".",
"keras",
"import",
"initializers",
",",
"layers",
",",
"regularizers",
"weight_decay",
"=",
"0.0001",
"x",
"=",
"layers",
".",
"Conv2D",
"(",
"32",
",",
"(",
"5",
",",
... | [
21,
4
] | [
57,
16
] | python | en | ['en', 'error', 'th'] | False |
Conv.scheduler | (self, epoch) |
TODO: Write Comment
|
TODO: Write Comment
| def scheduler(self, epoch):
"""
TODO: Write Comment
"""
return self.learn_rate | [
"def",
"scheduler",
"(",
"self",
",",
"epoch",
")",
":",
"return",
"self",
".",
"learn_rate"
] | [
60,
4
] | [
65,
30
] | python | en | ['en', 'error', 'th'] | False |
serve | (request, path, document_root=None, show_indexes=False) |
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
... |
Serve static files below a given point in the directory structure. | def serve(request, path, document_root=None, show_indexes=False):
"""
Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
from django.views.static import serve
url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'})
in... | [
"def",
"serve",
"(",
"request",
",",
"path",
",",
"document_root",
"=",
"None",
",",
"show_indexes",
"=",
"False",
")",
":",
"path",
"=",
"posixpath",
".",
"normpath",
"(",
"unquote",
"(",
"path",
")",
")",
".",
"lstrip",
"(",
"'/'",
")",
"fullpath",
... | [
22,
0
] | [
59,
19
] | python | en | ['en', 'error', 'th'] | False |
was_modified_since | (header=None, mtime=0, size=0) |
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
size
This is the size of the item we're talking ab... |
Was something modified since the user last downloaded it? | def was_modified_since(header=None, mtime=0, size=0):
"""
Was something modified since the user last downloaded it?
header
This is the value of the If-Modified-Since header. If this is None,
I'll just return True.
mtime
This is the modification time of the item we're talking about.
... | [
"def",
"was_modified_since",
"(",
"header",
"=",
"None",
",",
"mtime",
"=",
"0",
",",
"size",
"=",
"0",
")",
":",
"try",
":",
"if",
"header",
"is",
"None",
":",
"raise",
"ValueError",
"matches",
"=",
"re",
".",
"match",
"(",
"r\"^([^;]+)(; length=([0-9]+... | [
109,
0
] | [
136,
16
] | python | en | ['en', 'error', 'th'] | False |
UnifiedJob.assert_text_in_stdout | (self, expected_text, replace_spaces=None, replace_newlines=' ') | Assert text is found in stdout, and if not raise exception with entire stdout.
Default behavior is to replace newline characters with a space, but this can be modified, including replacement
with ''. Pass replace_newlines=None to disable.
Additionally, you may replace any ' ' with another char... | Assert text is found in stdout, and if not raise exception with entire stdout. | def assert_text_in_stdout(self, expected_text, replace_spaces=None, replace_newlines=' '):
"""Assert text is found in stdout, and if not raise exception with entire stdout.
Default behavior is to replace newline characters with a space, but this can be modified, including replacement
with ''. P... | [
"def",
"assert_text_in_stdout",
"(",
"self",
",",
"expected_text",
",",
"replace_spaces",
"=",
"None",
",",
"replace_newlines",
"=",
"' '",
")",
":",
"self",
".",
"wait_until_completed",
"(",
")",
"stdout",
"=",
"self",
".",
"result_stdout",
"if",
"replace_newli... | [
36,
4
] | [
54,
137
] | python | en | ['en', 'en', 'en'] | True |
UnifiedJob.is_successful | (self) | Return whether the current has completed successfully.
This means that:
* self.status == 'successful'
* self.has_traceback == False
* self.failed == False
| Return whether the current has completed successfully. | def is_successful(self):
"""Return whether the current has completed successfully.
This means that:
* self.status == 'successful'
* self.has_traceback == False
* self.failed == False
"""
return super(UnifiedJob, self).is_successful and not (self.has_traceback ... | [
"def",
"is_successful",
"(",
"self",
")",
":",
"return",
"super",
"(",
"UnifiedJob",
",",
"self",
")",
".",
"is_successful",
"and",
"not",
"(",
"self",
".",
"has_traceback",
"or",
"self",
".",
"failed",
")"
] | [
57,
4
] | [
65,
96
] | python | en | ['en', 'en', 'en'] | True |
UnifiedJob.has_traceback | (self) | Return whether a traceback has been detected in result_traceback | Return whether a traceback has been detected in result_traceback | def has_traceback(self):
"""Return whether a traceback has been detected in result_traceback"""
try:
tb = str(self.result_traceback)
except AttributeError:
# If record obtained from list view, then traceback isn't given
# and result_stdout is only given for so... | [
"def",
"has_traceback",
"(",
"self",
")",
":",
"try",
":",
"tb",
"=",
"str",
"(",
"self",
".",
"result_traceback",
")",
"except",
"AttributeError",
":",
"# If record obtained from list view, then traceback isn't given",
"# and result_stdout is only given for some types",
"#... | [
78,
4
] | [
88,
32
] | python | en | ['en', 'en', 'en'] | True |
UnifiedJob.job_args | (self) | Helper property to return flattened cmdline arg tokens in a list.
Flattens arg strings for rough inclusion checks:
```assert "thing" in unified_job.job_args```
```assert dict(extra_var=extra_var_val) in unified_job.job_args```
If you need to ensure the job_args are of awx-provided format... | Helper property to return flattened cmdline arg tokens in a list.
Flattens arg strings for rough inclusion checks:
```assert "thing" in unified_job.job_args```
```assert dict(extra_var=extra_var_val) in unified_job.job_args```
If you need to ensure the job_args are of awx-provided format... | def job_args(self):
"""Helper property to return flattened cmdline arg tokens in a list.
Flattens arg strings for rough inclusion checks:
```assert "thing" in unified_job.job_args```
```assert dict(extra_var=extra_var_val) in unified_job.job_args```
If you need to ensure the job_... | [
"def",
"job_args",
"(",
"self",
")",
":",
"def",
"attempt_yaml_load",
"(",
"arg",
")",
":",
"try",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"arg",
")",
"except",
"(",
"yaml",
".",
"parser",
".",
"ParserError",
",",
"yaml",
".",
"scanner",
".",
"... | [
104,
4
] | [
131,
19
] | python | en | ['en', 'de', 'en'] | True |
UnifiedJob.controller_dir | (self) | Returns the path to the private_data_dir on the controller node for the job
This can be used if trying to shell in and inspect the files used by the job
Cannot use job_cwd, because that is path inside EE container
| Returns the path to the private_data_dir on the controller node for the job
This can be used if trying to shell in and inspect the files used by the job
Cannot use job_cwd, because that is path inside EE container
| def controller_dir(self):
"""Returns the path to the private_data_dir on the controller node for the job
This can be used if trying to shell in and inspect the files used by the job
Cannot use job_cwd, because that is path inside EE container
"""
self.get()
job_args = sel... | [
"def",
"controller_dir",
"(",
"self",
")",
":",
"self",
".",
"get",
"(",
")",
"job_args",
"=",
"self",
".",
"job_args",
"expected_prefix",
"=",
"'/tmp/pdd_wrapper_{}'",
".",
"format",
"(",
"self",
".",
"id",
")",
"for",
"arg1",
",",
"arg2",
"in",
"zip",
... | [
134,
4
] | [
150,
9
] | python | en | ['en', 'en', 'en'] | True |
die | (msg) |
Error occurred; report and exit
|
Error occurred; report and exit
| def die(msg):
"""
Error occurred; report and exit
"""
sys.stderr.write(msg + "\n")
exit(1) | [
"def",
"die",
"(",
"msg",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"msg",
"+",
"\"\\n\"",
")",
"exit",
"(",
"1",
")"
] | [
10,
0
] | [
15,
11
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.