repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
CitrineInformatics/pif-dft
dfttopif/parsers/vasp.py
VaspParser._get_bandgap_eigenval
def _get_bandgap_eigenval(eigenval_fname, outcar_fname): """Get the bandgap from the EIGENVAL file""" with open(outcar_fname, "r") as f: parser = OutcarParser() nelec = next(iter(filter(lambda x: "number of electrons" in x, parser.parse(f.readlines()))))["number of electrons"] ...
python
def _get_bandgap_eigenval(eigenval_fname, outcar_fname): """Get the bandgap from the EIGENVAL file""" with open(outcar_fname, "r") as f: parser = OutcarParser() nelec = next(iter(filter(lambda x: "number of electrons" in x, parser.parse(f.readlines()))))["number of electrons"] ...
[ "def", "_get_bandgap_eigenval", "(", "eigenval_fname", ",", "outcar_fname", ")", ":", "with", "open", "(", "outcar_fname", ",", "\"r\"", ")", "as", "f", ":", "parser", "=", "OutcarParser", "(", ")", "nelec", "=", "next", "(", "iter", "(", "filter", "(", ...
Get the bandgap from the EIGENVAL file
[ "Get", "the", "bandgap", "from", "the", "EIGENVAL", "file" ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/vasp.py#L339-L351
train
Get the bandgap from the EIGENVAL file
CitrineInformatics/pif-dft
dfttopif/parsers/vasp.py
VaspParser._get_bandgap_doscar
def _get_bandgap_doscar(filename): """Get the bandgap from the DOSCAR file""" with open(filename) as fp: for i in range(6): l = fp.readline() efermi = float(l.split()[3]) step1 = fp.readline().split()[0] step2 = fp.readline().split()[0] ...
python
def _get_bandgap_doscar(filename): """Get the bandgap from the DOSCAR file""" with open(filename) as fp: for i in range(6): l = fp.readline() efermi = float(l.split()[3]) step1 = fp.readline().split()[0] step2 = fp.readline().split()[0] ...
[ "def", "_get_bandgap_doscar", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "fp", ":", "for", "i", "in", "range", "(", "6", ")", ":", "l", "=", "fp", ".", "readline", "(", ")", "efermi", "=", "float", "(", "l", ".", "spli...
Get the bandgap from the DOSCAR file
[ "Get", "the", "bandgap", "from", "the", "DOSCAR", "file" ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/vasp.py#L354-L380
train
Get the bandgap from the DOSCAR file
CitrineInformatics/pif-dft
dfttopif/parsers/vasp.py
VaspParser.get_band_gap
def get_band_gap(self): """Get the bandgap, either from the EIGENVAL or DOSCAR files""" if self.outcar is not None and self.eignval is not None: bandgap = VaspParser._get_bandgap_eigenval(self.eignval, self.outcar) elif self.doscar is not None: bandgap = VaspParser._get_b...
python
def get_band_gap(self): """Get the bandgap, either from the EIGENVAL or DOSCAR files""" if self.outcar is not None and self.eignval is not None: bandgap = VaspParser._get_bandgap_eigenval(self.eignval, self.outcar) elif self.doscar is not None: bandgap = VaspParser._get_b...
[ "def", "get_band_gap", "(", "self", ")", ":", "if", "self", ".", "outcar", "is", "not", "None", "and", "self", ".", "eignval", "is", "not", "None", ":", "bandgap", "=", "VaspParser", ".", "_get_bandgap_eigenval", "(", "self", ".", "eignval", ",", "self",...
Get the bandgap, either from the EIGENVAL or DOSCAR files
[ "Get", "the", "bandgap", "either", "from", "the", "EIGENVAL", "or", "DOSCAR", "files" ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/vasp.py#L382-L390
train
Get the bandgap from either the EIGENVAL or DOSCAR files
lreis2415/PyGeoC
pygeoc/raster.py
Raster.get_value_by_row_col
def get_value_by_row_col(self, row, col): """Get raster value by (row, col). Args: row: row number. col: col number. Returns: raster value, None if the input are invalid. """ if row < 0 or row >= self.nRows or col < 0 or col >= self.nCols: ...
python
def get_value_by_row_col(self, row, col): """Get raster value by (row, col). Args: row: row number. col: col number. Returns: raster value, None if the input are invalid. """ if row < 0 or row >= self.nRows or col < 0 or col >= self.nCols: ...
[ "def", "get_value_by_row_col", "(", "self", ",", "row", ",", "col", ")", ":", "if", "row", "<", "0", "or", "row", ">=", "self", ".", "nRows", "or", "col", "<", "0", "or", "col", ">=", "self", ".", "nCols", ":", "raise", "ValueError", "(", "\"The ro...
Get raster value by (row, col). Args: row: row number. col: col number. Returns: raster value, None if the input are invalid.
[ "Get", "raster", "value", "by", "(", "row", "col", ")", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L176-L194
train
Get raster value by row and column number.
lreis2415/PyGeoC
pygeoc/raster.py
Raster.get_value_by_xy
def get_value_by_xy(self, x, y): """Get raster value by xy coordinates. Args: x: X Coordinate. y: Y Coordinate. Returns: raster value, None if the input are invalid. """ if x < self.xMin or x > self.xMax or y < self.yMin or y > self.yMax: ...
python
def get_value_by_xy(self, x, y): """Get raster value by xy coordinates. Args: x: X Coordinate. y: Y Coordinate. Returns: raster value, None if the input are invalid. """ if x < self.xMin or x > self.xMax or y < self.yMin or y > self.yMax: ...
[ "def", "get_value_by_xy", "(", "self", ",", "x", ",", "y", ")", ":", "if", "x", "<", "self", ".", "xMin", "or", "x", ">", "self", ".", "xMax", "or", "y", "<", "self", ".", "yMin", "or", "y", ">", "self", ".", "yMax", ":", "return", "None", "#...
Get raster value by xy coordinates. Args: x: X Coordinate. y: Y Coordinate. Returns: raster value, None if the input are invalid.
[ "Get", "raster", "value", "by", "xy", "coordinates", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L196-L216
train
Get raster value by xy coordinates.
lreis2415/PyGeoC
pygeoc/raster.py
Raster.get_central_coors
def get_central_coors(self, row, col): """Get the coordinates of central grid. Args: row: row number, range from 0 to (nRows - 1). col: col number, range from 0 to (nCols - 1). Returns: XY coordinates. If the row or col are invalid, raise ValueError. ...
python
def get_central_coors(self, row, col): """Get the coordinates of central grid. Args: row: row number, range from 0 to (nRows - 1). col: col number, range from 0 to (nCols - 1). Returns: XY coordinates. If the row or col are invalid, raise ValueError. ...
[ "def", "get_central_coors", "(", "self", ",", "row", ",", "col", ")", ":", "if", "row", "<", "0", "or", "row", ">=", "self", ".", "nRows", "or", "col", "<", "0", "or", "col", ">=", "self", ".", "nCols", ":", "raise", "ValueError", "(", "\"The row (...
Get the coordinates of central grid. Args: row: row number, range from 0 to (nRows - 1). col: col number, range from 0 to (nCols - 1). Returns: XY coordinates. If the row or col are invalid, raise ValueError.
[ "Get", "the", "coordinates", "of", "central", "grid", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L218-L234
train
Get the coordinates of central elements of the class.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.read_raster
def read_raster(raster_file): """Read raster by GDAL. Args: raster_file: raster file path. Returns: Raster object. """ ds = gdal_Open(raster_file) band = ds.GetRasterBand(1) data = band.ReadAsArray() xsize = band.XSize ysi...
python
def read_raster(raster_file): """Read raster by GDAL. Args: raster_file: raster file path. Returns: Raster object. """ ds = gdal_Open(raster_file) band = ds.GetRasterBand(1) data = band.ReadAsArray() xsize = band.XSize ysi...
[ "def", "read_raster", "(", "raster_file", ")", ":", "ds", "=", "gdal_Open", "(", "raster_file", ")", "band", "=", "ds", ".", "GetRasterBand", "(", "1", ")", "data", "=", "band", ".", "ReadAsArray", "(", ")", "xsize", "=", "band", ".", "XSize", "ysize",...
Read raster by GDAL. Args: raster_file: raster file path. Returns: Raster object.
[ "Read", "raster", "by", "GDAL", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L249-L275
train
Reads a single raster by GDAL.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.get_mask_from_raster
def get_mask_from_raster(rasterfile, outmaskfile, keep_nodata=False): """Generate mask data from a given raster data. Args: rasterfile: raster file path. outmaskfile: output mask file path. Returns: Raster object of mask data. """ raster_r = ...
python
def get_mask_from_raster(rasterfile, outmaskfile, keep_nodata=False): """Generate mask data from a given raster data. Args: rasterfile: raster file path. outmaskfile: output mask file path. Returns: Raster object of mask data. """ raster_r = ...
[ "def", "get_mask_from_raster", "(", "rasterfile", ",", "outmaskfile", ",", "keep_nodata", "=", "False", ")", ":", "raster_r", "=", "RasterUtilClass", ".", "read_raster", "(", "rasterfile", ")", "xsize", "=", "raster_r", ".", "nCols", "ysize", "=", "raster_r", ...
Generate mask data from a given raster data. Args: rasterfile: raster file path. outmaskfile: output mask file path. Returns: Raster object of mask data.
[ "Generate", "mask", "data", "from", "a", "given", "raster", "data", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L278-L337
train
Generate a mask from a given raster file.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_reclassify
def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32): """Reclassify raster by given classifier dict. Args: srcfile: source raster file. v_dict: classifier dict. dstfile: destination file path. gdaltype (:obj:`pygeoc.raster.GDALDataType`):...
python
def raster_reclassify(srcfile, v_dict, dstfile, gdaltype=GDT_Float32): """Reclassify raster by given classifier dict. Args: srcfile: source raster file. v_dict: classifier dict. dstfile: destination file path. gdaltype (:obj:`pygeoc.raster.GDALDataType`):...
[ "def", "raster_reclassify", "(", "srcfile", ",", "v_dict", ",", "dstfile", ",", "gdaltype", "=", "GDT_Float32", ")", ":", "src_r", "=", "RasterUtilClass", ".", "read_raster", "(", "srcfile", ")", "src_data", "=", "src_r", ".", "data", "dst_data", "=", "numpy...
Reclassify raster by given classifier dict. Args: srcfile: source raster file. v_dict: classifier dict. dstfile: destination file path. gdaltype (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default.
[ "Reclassify", "raster", "by", "given", "classifier", "dict", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L340-L366
train
Reclassify raster by given classifier dict.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.write_gtiff_file
def write_gtiff_file(f_name, n_rows, n_cols, data, geotransform, srs, nodata_value, gdal_type=GDT_Float32): """Output Raster to GeoTiff format file. Args: f_name: output gtiff file name. n_rows: Row count. n_cols: Col count. data:...
python
def write_gtiff_file(f_name, n_rows, n_cols, data, geotransform, srs, nodata_value, gdal_type=GDT_Float32): """Output Raster to GeoTiff format file. Args: f_name: output gtiff file name. n_rows: Row count. n_cols: Col count. data:...
[ "def", "write_gtiff_file", "(", "f_name", ",", "n_rows", ",", "n_cols", ",", "data", ",", "geotransform", ",", "srs", ",", "nodata_value", ",", "gdal_type", "=", "GDT_Float32", ")", ":", "UtilClass", ".", "mkdir", "(", "os", ".", "path", ".", "dirname", ...
Output Raster to GeoTiff format file. Args: f_name: output gtiff file name. n_rows: Row count. n_cols: Col count. data: 2D array data. geotransform: geographic transformation. srs: coordinate system. nodata_value: nodata value....
[ "Output", "Raster", "to", "GeoTiff", "format", "file", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L369-L402
train
Write a 2D array of raster data to a GeoTiff format file.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.write_asc_file
def write_asc_file(filename, data, xsize, ysize, geotransform, nodata_value): """Output Raster to ASCII file. Args: filename: output ASCII filename. data: 2D array data. xsize: Col count. ysize: Row count. geotransform: geographic transformati...
python
def write_asc_file(filename, data, xsize, ysize, geotransform, nodata_value): """Output Raster to ASCII file. Args: filename: output ASCII filename. data: 2D array data. xsize: Col count. ysize: Row count. geotransform: geographic transformati...
[ "def", "write_asc_file", "(", "filename", ",", "data", ",", "xsize", ",", "ysize", ",", "geotransform", ",", "nodata_value", ")", ":", "UtilClass", ".", "mkdir", "(", "os", ".", "path", ".", "dirname", "(", "FileClass", ".", "get_file_fullpath", "(", "file...
Output Raster to ASCII file. Args: filename: output ASCII filename. data: 2D array data. xsize: Col count. ysize: Row count. geotransform: geographic transformation. nodata_value: nodata_flow value.
[ "Output", "Raster", "to", "ASCII", "file", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L405-L432
train
Output Raster to ASCII file.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_to_gtiff
def raster_to_gtiff(tif, geotif, change_nodata=False, change_gdal_type=False): """Converting Raster format to GeoTIFF. Args: tif: source raster file path. geotif: output raster file path. change_nodata: change NoDataValue to -9999 or not. gdal_type (:obj:...
python
def raster_to_gtiff(tif, geotif, change_nodata=False, change_gdal_type=False): """Converting Raster format to GeoTIFF. Args: tif: source raster file path. geotif: output raster file path. change_nodata: change NoDataValue to -9999 or not. gdal_type (:obj:...
[ "def", "raster_to_gtiff", "(", "tif", ",", "geotif", ",", "change_nodata", "=", "False", ",", "change_gdal_type", "=", "False", ")", ":", "rst_file", "=", "RasterUtilClass", ".", "read_raster", "(", "tif", ")", "nodata", "=", "rst_file", ".", "noDataValue", ...
Converting Raster format to GeoTIFF. Args: tif: source raster file path. geotif: output raster file path. change_nodata: change NoDataValue to -9999 or not. gdal_type (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default. change_gdal_type: If Tr...
[ "Converting", "Raster", "format", "to", "GeoTIFF", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L435-L456
train
Converts raster format to GeoTIFF format.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_to_asc
def raster_to_asc(raster_f, asc_f): """Converting Raster format to ASCII raster. Args: raster_f: raster file. asc_f: output ASCII file. """ raster_r = RasterUtilClass.read_raster(raster_f) RasterUtilClass.write_asc_file(asc_f, raster_r.data, raster_r.nCol...
python
def raster_to_asc(raster_f, asc_f): """Converting Raster format to ASCII raster. Args: raster_f: raster file. asc_f: output ASCII file. """ raster_r = RasterUtilClass.read_raster(raster_f) RasterUtilClass.write_asc_file(asc_f, raster_r.data, raster_r.nCol...
[ "def", "raster_to_asc", "(", "raster_f", ",", "asc_f", ")", ":", "raster_r", "=", "RasterUtilClass", ".", "read_raster", "(", "raster_f", ")", "RasterUtilClass", ".", "write_asc_file", "(", "asc_f", ",", "raster_r", ".", "data", ",", "raster_r", ".", "nCols", ...
Converting Raster format to ASCII raster. Args: raster_f: raster file. asc_f: output ASCII file.
[ "Converting", "Raster", "format", "to", "ASCII", "raster", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L459-L468
train
Convert raster format to ASCII file.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_statistics
def raster_statistics(raster_file): """Get basic statistics of raster data. Args: raster_file: raster file path. Returns: min, max, mean, std. """ ds = gdal_Open(raster_file) band = ds.GetRasterBand(1) minv, maxv, meanv, std = band.Comput...
python
def raster_statistics(raster_file): """Get basic statistics of raster data. Args: raster_file: raster file path. Returns: min, max, mean, std. """ ds = gdal_Open(raster_file) band = ds.GetRasterBand(1) minv, maxv, meanv, std = band.Comput...
[ "def", "raster_statistics", "(", "raster_file", ")", ":", "ds", "=", "gdal_Open", "(", "raster_file", ")", "band", "=", "ds", ".", "GetRasterBand", "(", "1", ")", "minv", ",", "maxv", ",", "meanv", ",", "std", "=", "band", ".", "ComputeStatistics", "(", ...
Get basic statistics of raster data. Args: raster_file: raster file path. Returns: min, max, mean, std.
[ "Get", "basic", "statistics", "of", "raster", "data", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L471-L483
train
Get basic statistics of the raster data.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.split_raster
def split_raster(rs, split_shp, field_name, temp_dir): """Split raster by given shapefile and field name. Args: rs: origin raster file. split_shp: boundary (ESRI Shapefile) used to spilt raster. field_name: field name identify the spilt value. temp_dir: d...
python
def split_raster(rs, split_shp, field_name, temp_dir): """Split raster by given shapefile and field name. Args: rs: origin raster file. split_shp: boundary (ESRI Shapefile) used to spilt raster. field_name: field name identify the spilt value. temp_dir: d...
[ "def", "split_raster", "(", "rs", ",", "split_shp", ",", "field_name", ",", "temp_dir", ")", ":", "UtilClass", ".", "rmmkdir", "(", "temp_dir", ")", "ds", "=", "ogr_Open", "(", "split_shp", ")", "lyr", "=", "ds", ".", "GetLayer", "(", "0", ")", "lyr", ...
Split raster by given shapefile and field name. Args: rs: origin raster file. split_shp: boundary (ESRI Shapefile) used to spilt raster. field_name: field name identify the spilt value. temp_dir: directory to store the spilt rasters.
[ "Split", "raster", "by", "given", "shapefile", "and", "field", "name", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L486-L512
train
Split raster by given shapefile and field name.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.get_negative_dem
def get_negative_dem(raw_dem, neg_dem): """Get negative DEM data.""" origin = RasterUtilClass.read_raster(raw_dem) max_v = numpy.max(origin.data) temp = origin.data < 0 neg = numpy.where(temp, origin.noDataValue, max_v - origin.data) RasterUtilClass.write_gtiff_file(neg_d...
python
def get_negative_dem(raw_dem, neg_dem): """Get negative DEM data.""" origin = RasterUtilClass.read_raster(raw_dem) max_v = numpy.max(origin.data) temp = origin.data < 0 neg = numpy.where(temp, origin.noDataValue, max_v - origin.data) RasterUtilClass.write_gtiff_file(neg_d...
[ "def", "get_negative_dem", "(", "raw_dem", ",", "neg_dem", ")", ":", "origin", "=", "RasterUtilClass", ".", "read_raster", "(", "raw_dem", ")", "max_v", "=", "numpy", ".", "max", "(", "origin", ".", "data", ")", "temp", "=", "origin", ".", "data", "<", ...
Get negative DEM data.
[ "Get", "negative", "DEM", "data", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L515-L522
train
Get negative DEM data.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.mask_raster
def mask_raster(in_raster, mask, out_raster): """ Mask raster data. Args: in_raster: list or one raster mask: Mask raster data out_raster: list or one raster """ if is_string(in_raster) and is_string(out_raster): in_raster = [str(i...
python
def mask_raster(in_raster, mask, out_raster): """ Mask raster data. Args: in_raster: list or one raster mask: Mask raster data out_raster: list or one raster """ if is_string(in_raster) and is_string(out_raster): in_raster = [str(i...
[ "def", "mask_raster", "(", "in_raster", ",", "mask", ",", "out_raster", ")", ":", "if", "is_string", "(", "in_raster", ")", "and", "is_string", "(", "out_raster", ")", ":", "in_raster", "=", "[", "str", "(", "in_raster", ")", "]", "out_raster", "=", "[",...
Mask raster data. Args: in_raster: list or one raster mask: Mask raster data out_raster: list or one raster
[ "Mask", "raster", "data", ".", "Args", ":", "in_raster", ":", "list", "or", "one", "raster", "mask", ":", "Mask", "raster", "data", "out_raster", ":", "list", "or", "one", "raster" ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L525-L564
train
Mask raster data.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_binarization
def raster_binarization(given_value, rasterfilename): """Make the raster into binarization. The opening and closing are based on binary image. Therefore we need to make the raster into binarization. Args: given_value: The given value's pixels will be value in 1, ...
python
def raster_binarization(given_value, rasterfilename): """Make the raster into binarization. The opening and closing are based on binary image. Therefore we need to make the raster into binarization. Args: given_value: The given value's pixels will be value in 1, ...
[ "def", "raster_binarization", "(", "given_value", ",", "rasterfilename", ")", ":", "origin_raster", "=", "RasterUtilClass", ".", "read_raster", "(", "rasterfilename", ")", "binary_raster", "=", "numpy", ".", "where", "(", "origin_raster", ".", "data", "==", "given...
Make the raster into binarization. The opening and closing are based on binary image. Therefore we need to make the raster into binarization. Args: given_value: The given value's pixels will be value in 1, other pixels will be value in 0. rasterfilename: The...
[ "Make", "the", "raster", "into", "binarization", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L567-L583
train
This function is used to make the raster into binarization.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_erosion
def raster_erosion(rasterfile): """Erode the raster image. Find the min pixel's value in 8-neighborhood. Then change the compute pixel's value into the min pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1.t...
python
def raster_erosion(rasterfile): """Erode the raster image. Find the min pixel's value in 8-neighborhood. Then change the compute pixel's value into the min pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1.t...
[ "def", "raster_erosion", "(", "rasterfile", ")", ":", "if", "is_string", "(", "rasterfile", ")", ":", "origin_raster", "=", "RasterUtilClass", ".", "read_raster", "(", "str", "(", "rasterfile", ")", ")", "elif", "isinstance", "(", "rasterfile", ",", "Raster", ...
Erode the raster image. Find the min pixel's value in 8-neighborhood. Then change the compute pixel's value into the min pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1.tif"), rasterfile(class Raster) or numpy.nda...
[ "Erode", "the", "raster", "image", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L586-L631
train
Erode the raster image.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.raster_dilation
def raster_dilation(rasterfile): """Dilate the raster image. Find the max pixel's value in 8-neighborhood. Then change the compute pixel's value into the max pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1...
python
def raster_dilation(rasterfile): """Dilate the raster image. Find the max pixel's value in 8-neighborhood. Then change the compute pixel's value into the max pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1...
[ "def", "raster_dilation", "(", "rasterfile", ")", ":", "if", "is_string", "(", "rasterfile", ")", ":", "origin_raster", "=", "RasterUtilClass", ".", "read_raster", "(", "str", "(", "rasterfile", ")", ")", "elif", "isinstance", "(", "rasterfile", ",", "Raster",...
Dilate the raster image. Find the max pixel's value in 8-neighborhood. Then change the compute pixel's value into the max pixel's value. Args: rasterfile: input original raster image, type can be filename(string, like "test1.tif"), rasterfile(class Raster) or numpy.nd...
[ "Dilate", "the", "raster", "image", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L634-L679
train
Dilate the raster image.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.openning
def openning(input_rasterfilename, times): """Do openning. Openning: Erode firstly, then Dilate. Args: input_rasterfilename: input original raster image filename. times: Erode and Dilate times. Returns: openning_raster: raster image after open. ...
python
def openning(input_rasterfilename, times): """Do openning. Openning: Erode firstly, then Dilate. Args: input_rasterfilename: input original raster image filename. times: Erode and Dilate times. Returns: openning_raster: raster image after open. ...
[ "def", "openning", "(", "input_rasterfilename", ",", "times", ")", ":", "input_raster", "=", "RasterUtilClass", ".", "read_raster", "(", "input_rasterfilename", ")", "openning_raster", "=", "input_raster", "for", "i", "in", "range", "(", "times", ")", ":", "open...
Do openning. Openning: Erode firstly, then Dilate. Args: input_rasterfilename: input original raster image filename. times: Erode and Dilate times. Returns: openning_raster: raster image after open.
[ "Do", "openning", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L682-L700
train
Do openning.
lreis2415/PyGeoC
pygeoc/raster.py
RasterUtilClass.closing
def closing(input_rasterfilename, times): """Do closing. Closing: Dilate firstly, then Erode. Args: input_rasterfilename: input original raster image filename. times: Erode and Dilate times. Returns: closing_raster: raster image after close. ...
python
def closing(input_rasterfilename, times): """Do closing. Closing: Dilate firstly, then Erode. Args: input_rasterfilename: input original raster image filename. times: Erode and Dilate times. Returns: closing_raster: raster image after close. ...
[ "def", "closing", "(", "input_rasterfilename", ",", "times", ")", ":", "input_raster", "=", "RasterUtilClass", ".", "read_raster", "(", "input_rasterfilename", ")", "closing_raster", "=", "input_raster", "for", "i", "in", "range", "(", "times", ")", ":", "closin...
Do closing. Closing: Dilate firstly, then Erode. Args: input_rasterfilename: input original raster image filename. times: Erode and Dilate times. Returns: closing_raster: raster image after close.
[ "Do", "closing", "." ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/raster.py#L703-L721
train
Do closing.
PeerAssets/pypeerassets
pypeerassets/transactions.py
calculate_tx_fee
def calculate_tx_fee(tx_size: int) -> Decimal: '''return tx fee from tx size in bytes''' per_kb_cost = 0.01 min_fee = Decimal(0.001) fee = Decimal((tx_size / 1000) * per_kb_cost) if fee <= min_fee: return min_fee else: return fee
python
def calculate_tx_fee(tx_size: int) -> Decimal: '''return tx fee from tx size in bytes''' per_kb_cost = 0.01 min_fee = Decimal(0.001) fee = Decimal((tx_size / 1000) * per_kb_cost) if fee <= min_fee: return min_fee else: return fee
[ "def", "calculate_tx_fee", "(", "tx_size", ":", "int", ")", "->", "Decimal", ":", "per_kb_cost", "=", "0.01", "min_fee", "=", "Decimal", "(", "0.001", ")", "fee", "=", "Decimal", "(", "(", "tx_size", "/", "1000", ")", "*", "per_kb_cost", ")", "if", "fe...
return tx fee from tx size in bytes
[ "return", "tx", "fee", "from", "tx", "size", "in", "bytes" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L214-L225
train
calculate tx fee from tx size in bytes
PeerAssets/pypeerassets
pypeerassets/transactions.py
nulldata_script
def nulldata_script(data: bytes) -> NulldataScript: '''create nulldata (OP_return) script''' stack = StackData.from_bytes(data) return NulldataScript(stack)
python
def nulldata_script(data: bytes) -> NulldataScript: '''create nulldata (OP_return) script''' stack = StackData.from_bytes(data) return NulldataScript(stack)
[ "def", "nulldata_script", "(", "data", ":", "bytes", ")", "->", "NulldataScript", ":", "stack", "=", "StackData", ".", "from_bytes", "(", "data", ")", "return", "NulldataScript", "(", "stack", ")" ]
create nulldata (OP_return) script
[ "create", "nulldata", "(", "OP_return", ")", "script" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L228-L232
train
create nulldata script
PeerAssets/pypeerassets
pypeerassets/transactions.py
p2pkh_script
def p2pkh_script(network: str, address: str) -> P2pkhScript: '''create pay-to-key-hash (P2PKH) script''' network_params = net_query(network) addr = Address.from_string(network=network_params, string=address) return P2pkhScript(addr)
python
def p2pkh_script(network: str, address: str) -> P2pkhScript: '''create pay-to-key-hash (P2PKH) script''' network_params = net_query(network) addr = Address.from_string(network=network_params, string=address) return P2pkhScript(addr)
[ "def", "p2pkh_script", "(", "network", ":", "str", ",", "address", ":", "str", ")", "->", "P2pkhScript", ":", "network_params", "=", "net_query", "(", "network", ")", "addr", "=", "Address", ".", "from_string", "(", "network", "=", "network_params", ",", "...
create pay-to-key-hash (P2PKH) script
[ "create", "pay", "-", "to", "-", "key", "-", "hash", "(", "P2PKH", ")", "script" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L235-L243
train
create pay - to - key - hash script
PeerAssets/pypeerassets
pypeerassets/transactions.py
p2sh_p2pkh_script
def p2sh_p2pkh_script(network: str, address: str) -> P2shScript: '''p2sh embedding p2pkh''' network_params = net_query(network) addr = Address.from_string(network=network_params, string=address) p2pkh = P2pkhScript(addr) return P2shScript(p2pkh)
python
def p2sh_p2pkh_script(network: str, address: str) -> P2shScript: '''p2sh embedding p2pkh''' network_params = net_query(network) addr = Address.from_string(network=network_params, string=address) p2pkh = P2pkhScript(addr) return P2shScript(p2pkh)
[ "def", "p2sh_p2pkh_script", "(", "network", ":", "str", ",", "address", ":", "str", ")", "->", "P2shScript", ":", "network_params", "=", "net_query", "(", "network", ")", "addr", "=", "Address", ".", "from_string", "(", "network", "=", "network_params", ",",...
p2sh embedding p2pkh
[ "p2sh", "embedding", "p2pkh" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L246-L256
train
p2sh embedding p2pkh
PeerAssets/pypeerassets
pypeerassets/transactions.py
tx_output
def tx_output(network: str, value: Decimal, n: int, script: ScriptSig) -> TxOut: '''create TxOut object''' network_params = net_query(network) return TxOut(network=network_params, value=int(value * network_params.to_unit), n=n, script_pubkey=script)
python
def tx_output(network: str, value: Decimal, n: int, script: ScriptSig) -> TxOut: '''create TxOut object''' network_params = net_query(network) return TxOut(network=network_params, value=int(value * network_params.to_unit), n=n, script_pubkey=script)
[ "def", "tx_output", "(", "network", ":", "str", ",", "value", ":", "Decimal", ",", "n", ":", "int", ",", "script", ":", "ScriptSig", ")", "->", "TxOut", ":", "network_params", "=", "net_query", "(", "network", ")", "return", "TxOut", "(", "network", "=...
create TxOut object
[ "create", "TxOut", "object" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L259-L267
train
create TxOut object
PeerAssets/pypeerassets
pypeerassets/transactions.py
make_raw_transaction
def make_raw_transaction( network: str, inputs: list, outputs: list, locktime: Locktime, timestamp: int=int(time()), version: int=1, ) -> MutableTransaction: '''create raw transaction''' network_params = net_query(network) if network_params.name.startswith("peercoin"): retu...
python
def make_raw_transaction( network: str, inputs: list, outputs: list, locktime: Locktime, timestamp: int=int(time()), version: int=1, ) -> MutableTransaction: '''create raw transaction''' network_params = net_query(network) if network_params.name.startswith("peercoin"): retu...
[ "def", "make_raw_transaction", "(", "network", ":", "str", ",", "inputs", ":", "list", ",", "outputs", ":", "list", ",", "locktime", ":", "Locktime", ",", "timestamp", ":", "int", "=", "int", "(", "time", "(", ")", ")", ",", "version", ":", "int", "=...
create raw transaction
[ "create", "raw", "transaction" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L270-L298
train
create raw transaction
PeerAssets/pypeerassets
pypeerassets/transactions.py
find_parent_outputs
def find_parent_outputs(provider: Provider, utxo: TxIn) -> TxOut: '''due to design of the btcpy library, TxIn object must be converted to TxOut object before signing''' network_params = net_query(provider.network) index = utxo.txout # utxo index return TxOut.from_json(provider.getrawtransaction(utxo.t...
python
def find_parent_outputs(provider: Provider, utxo: TxIn) -> TxOut: '''due to design of the btcpy library, TxIn object must be converted to TxOut object before signing''' network_params = net_query(provider.network) index = utxo.txout # utxo index return TxOut.from_json(provider.getrawtransaction(utxo.t...
[ "def", "find_parent_outputs", "(", "provider", ":", "Provider", ",", "utxo", ":", "TxIn", ")", "->", "TxOut", ":", "network_params", "=", "net_query", "(", "provider", ".", "network", ")", "index", "=", "utxo", ".", "txout", "# utxo index", "return", "TxOut"...
due to design of the btcpy library, TxIn object must be converted to TxOut object before signing
[ "due", "to", "design", "of", "the", "btcpy", "library", "TxIn", "object", "must", "be", "converted", "to", "TxOut", "object", "before", "signing" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L301-L308
train
find parent outputs of utxo
PeerAssets/pypeerassets
pypeerassets/transactions.py
sign_transaction
def sign_transaction(provider: Provider, unsigned: MutableTransaction, key: Kutil) -> Transaction: '''sign transaction with Kutil''' parent_outputs = [find_parent_outputs(provider, i) for i in unsigned.ins] return key.sign_transaction(parent_outputs, unsigned)
python
def sign_transaction(provider: Provider, unsigned: MutableTransaction, key: Kutil) -> Transaction: '''sign transaction with Kutil''' parent_outputs = [find_parent_outputs(provider, i) for i in unsigned.ins] return key.sign_transaction(parent_outputs, unsigned)
[ "def", "sign_transaction", "(", "provider", ":", "Provider", ",", "unsigned", ":", "MutableTransaction", ",", "key", ":", "Kutil", ")", "->", "Transaction", ":", "parent_outputs", "=", "[", "find_parent_outputs", "(", "provider", ",", "i", ")", "for", "i", "...
sign transaction with Kutil
[ "sign", "transaction", "with", "Kutil" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L311-L316
train
sign transaction with Kutil
erwanp/publib
publib/main.py
set_style
def set_style(style='basic', **kwargs): ''' Changes Matplotlib basic style to produce high quality graphs. Call this function at the beginning of your script. You can even further improve graphs with a call to fix_style at the end of your script. Parameters ---------- style: string ...
python
def set_style(style='basic', **kwargs): ''' Changes Matplotlib basic style to produce high quality graphs. Call this function at the beginning of your script. You can even further improve graphs with a call to fix_style at the end of your script. Parameters ---------- style: string ...
[ "def", "set_style", "(", "style", "=", "'basic'", ",", "*", "*", "kwargs", ")", ":", "style", "=", "_read_style", "(", "style", ")", "# Add basic style as the first style", "if", "style", "[", "0", "]", "!=", "'basic'", ":", "style", "=", "[", "'basic'", ...
Changes Matplotlib basic style to produce high quality graphs. Call this function at the beginning of your script. You can even further improve graphs with a call to fix_style at the end of your script. Parameters ---------- style: string 'basic', 'article', 'poster', 'B&W', 'talk', 'o...
[ "Changes", "Matplotlib", "basic", "style", "to", "produce", "high", "quality", "graphs", ".", "Call", "this", "function", "at", "the", "beginning", "of", "your", "script", ".", "You", "can", "even", "further", "improve", "graphs", "with", "a", "call", "to", ...
0417e6a31d52e23b816ac74d40b4c11d4b8ba4a6
https://github.com/erwanp/publib/blob/0417e6a31d52e23b816ac74d40b4c11d4b8ba4a6/publib/main.py#L89-L125
train
Changes Matplotlib basic style to produce high quality graphs.
erwanp/publib
publib/main.py
fix_style
def fix_style(style='basic', ax=None, **kwargs): ''' Add an extra formatting layer to an axe, that couldn't be changed directly in matplotlib.rcParams or with styles. Apply this function to every axe you created. Parameters ---------- ax: a matplotlib axe. If None, the last ...
python
def fix_style(style='basic', ax=None, **kwargs): ''' Add an extra formatting layer to an axe, that couldn't be changed directly in matplotlib.rcParams or with styles. Apply this function to every axe you created. Parameters ---------- ax: a matplotlib axe. If None, the last ...
[ "def", "fix_style", "(", "style", "=", "'basic'", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "style", "=", "_read_style", "(", "style", ")", "# Apply all styles", "for", "s", "in", "style", ":", "if", "not", "s", "in", "style_params", ...
Add an extra formatting layer to an axe, that couldn't be changed directly in matplotlib.rcParams or with styles. Apply this function to every axe you created. Parameters ---------- ax: a matplotlib axe. If None, the last axe generated is used style: string or list of string ...
[ "Add", "an", "extra", "formatting", "layer", "to", "an", "axe", "that", "couldn", "t", "be", "changed", "directly", "in", "matplotlib", ".", "rcParams", "or", "with", "styles", ".", "Apply", "this", "function", "to", "every", "axe", "you", "created", "." ]
0417e6a31d52e23b816ac74d40b4c11d4b8ba4a6
https://github.com/erwanp/publib/blob/0417e6a31d52e23b816ac74d40b4c11d4b8ba4a6/publib/main.py#L147-L192
train
Add an extra formatting layer to every axe that can be changed directly by matplotlib. rcParams or with styles.
erwanp/publib
publib/main.py
_read_style
def _read_style(style): ''' Deal with different style format (str, list, tuple)''' if isinstance(style, string_types): style = [style] else: style = list(style) return style
python
def _read_style(style): ''' Deal with different style format (str, list, tuple)''' if isinstance(style, string_types): style = [style] else: style = list(style) return style
[ "def", "_read_style", "(", "style", ")", ":", "if", "isinstance", "(", "style", ",", "string_types", ")", ":", "style", "=", "[", "style", "]", "else", ":", "style", "=", "list", "(", "style", ")", "return", "style" ]
Deal with different style format (str, list, tuple)
[ "Deal", "with", "different", "style", "format", "(", "str", "list", "tuple", ")" ]
0417e6a31d52e23b816ac74d40b4c11d4b8ba4a6
https://github.com/erwanp/publib/blob/0417e6a31d52e23b816ac74d40b4c11d4b8ba4a6/publib/main.py#L261-L269
train
Deal with different style format ( str list tuple )
CitrineInformatics/pif-dft
dfttopif/parsers/abinit.py
AbinitParser._get_label
def _get_label(self): '''Find the label for the output files for this calculation ''' if self._label is None: foundfiles = False for f in self._files: if ".files" in f: foundfiles = True self._label = f.sp...
python
def _get_label(self): '''Find the label for the output files for this calculation ''' if self._label is None: foundfiles = False for f in self._files: if ".files" in f: foundfiles = True self._label = f.sp...
[ "def", "_get_label", "(", "self", ")", ":", "if", "self", ".", "_label", "is", "None", ":", "foundfiles", "=", "False", "for", "f", "in", "self", ".", "_files", ":", "if", "\".files\"", "in", "f", ":", "foundfiles", "=", "True", "self", ".", "_label"...
Find the label for the output files for this calculation
[ "Find", "the", "label", "for", "the", "output", "files", "for", "this", "calculation" ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/abinit.py#L30-L70
train
Find the label for the output files for this calculation
rosshamish/catan-py
catan/states.py
GameStateInGame.next_player
def next_player(self): """ Returns the player whose turn it will be next. Uses regular seat-wise clockwise rotation. Compare to GameStatePreGame's implementation, which uses snake draft. :return Player """ logging.warning('turn={}, players={}'.format( ...
python
def next_player(self): """ Returns the player whose turn it will be next. Uses regular seat-wise clockwise rotation. Compare to GameStatePreGame's implementation, which uses snake draft. :return Player """ logging.warning('turn={}, players={}'.format( ...
[ "def", "next_player", "(", "self", ")", ":", "logging", ".", "warning", "(", "'turn={}, players={}'", ".", "format", "(", "self", ".", "game", ".", "_cur_turn", ",", "self", ".", "game", ".", "players", ")", ")", "return", "self", ".", "game", ".", "pl...
Returns the player whose turn it will be next. Uses regular seat-wise clockwise rotation. Compare to GameStatePreGame's implementation, which uses snake draft. :return Player
[ "Returns", "the", "player", "whose", "turn", "it", "will", "be", "next", "." ]
120438a8f16e39c13322c5d5930e1064e1d3f4be
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/states.py#L184-L198
train
Returns the next player in the game.
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/script_iterator.py
ScriptIterator._estimate_progress
def _estimate_progress(self): """ estimates the current progress that is then used in _receive_signal :return: current progress in percent """ estimate = True # ==== get the current subscript and the time it takes to execute it ===== current_subscript = self._cur...
python
def _estimate_progress(self): """ estimates the current progress that is then used in _receive_signal :return: current progress in percent """ estimate = True # ==== get the current subscript and the time it takes to execute it ===== current_subscript = self._cur...
[ "def", "_estimate_progress", "(", "self", ")", ":", "estimate", "=", "True", "# ==== get the current subscript and the time it takes to execute it =====", "current_subscript", "=", "self", ".", "_current_subscript_stage", "[", "'current_subscript'", "]", "# ==== get the number of...
estimates the current progress that is then used in _receive_signal :return: current progress in percent
[ "estimates", "the", "current", "progress", "that", "is", "then", "used", "in", "_receive_signal" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/script_iterator.py#L242-L338
train
estimate the current progress of the current subscript and time it takes to execute it
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/script_iterator.py
ScriptIterator.plot
def plot(self, figure_list): ''' When each subscript is called, uses its standard plotting Args: figure_list: list of figures passed from the guit ''' #TODO: be smarter about how we plot ScriptIterator if self._current_subscript_stage is not None: ...
python
def plot(self, figure_list): ''' When each subscript is called, uses its standard plotting Args: figure_list: list of figures passed from the guit ''' #TODO: be smarter about how we plot ScriptIterator if self._current_subscript_stage is not None: ...
[ "def", "plot", "(", "self", ",", "figure_list", ")", ":", "#TODO: be smarter about how we plot ScriptIterator", "if", "self", ".", "_current_subscript_stage", "is", "not", "None", ":", "if", "self", ".", "_current_subscript_stage", "[", "'current_subscript'", "]", "is...
When each subscript is called, uses its standard plotting Args: figure_list: list of figures passed from the guit
[ "When", "each", "subscript", "is", "called", "uses", "its", "standard", "plotting" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/script_iterator.py#L360-L392
train
This function is called by the plot function of the last subscript.
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/script_iterator.py
ScriptIterator.get_default_settings
def get_default_settings(sub_scripts, script_order, script_execution_freq, iterator_type): """ assigning the actual script settings depending on the iterator type this might be overwritten by classes that inherit form ScriptIterator Args: sub_scripts: dictionary with the su...
python
def get_default_settings(sub_scripts, script_order, script_execution_freq, iterator_type): """ assigning the actual script settings depending on the iterator type this might be overwritten by classes that inherit form ScriptIterator Args: sub_scripts: dictionary with the su...
[ "def", "get_default_settings", "(", "sub_scripts", ",", "script_order", ",", "script_execution_freq", ",", "iterator_type", ")", ":", "def", "populate_sweep_param", "(", "scripts", ",", "parameter_list", ",", "trace", "=", "''", ")", ":", "'''\n\n Args:\n ...
assigning the actual script settings depending on the iterator type this might be overwritten by classes that inherit form ScriptIterator Args: sub_scripts: dictionary with the subscripts script_order: execution order of subscripts script_execution_freq: execution f...
[ "assigning", "the", "actual", "script", "settings", "depending", "on", "the", "iterator", "type" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/script_iterator.py#L451-L552
train
This function returns the default settings for the given scripts and scripts.
lreis2415/PyGeoC
pygeoc/vector.py
VectorUtilClass.raster2shp
def raster2shp(rasterfile, vectorshp, layername=None, fieldname=None, band_num=1, mask='default'): """Convert raster to ESRI shapefile""" FileClass.remove_files(vectorshp) FileClass.check_file_exists(rasterfile) # this allows GDAL to throw Python Exceptions gda...
python
def raster2shp(rasterfile, vectorshp, layername=None, fieldname=None, band_num=1, mask='default'): """Convert raster to ESRI shapefile""" FileClass.remove_files(vectorshp) FileClass.check_file_exists(rasterfile) # this allows GDAL to throw Python Exceptions gda...
[ "def", "raster2shp", "(", "rasterfile", ",", "vectorshp", ",", "layername", "=", "None", ",", "fieldname", "=", "None", ",", "band_num", "=", "1", ",", "mask", "=", "'default'", ")", ":", "FileClass", ".", "remove_files", "(", "vectorshp", ")", "FileClass"...
Convert raster to ESRI shapefile
[ "Convert", "raster", "to", "ESRI", "shapefile" ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/vector.py#L36-L77
train
Convert raster to ESRI shapefile
lreis2415/PyGeoC
pygeoc/vector.py
VectorUtilClass.convert2geojson
def convert2geojson(jsonfile, src_srs, dst_srs, src_file): """convert shapefile to geojson file""" if os.path.exists(jsonfile): os.remove(jsonfile) if sysstr == 'Windows': exepath = '"%s/Lib/site-packages/osgeo/ogr2ogr"' % sys.exec_prefix else: exepath...
python
def convert2geojson(jsonfile, src_srs, dst_srs, src_file): """convert shapefile to geojson file""" if os.path.exists(jsonfile): os.remove(jsonfile) if sysstr == 'Windows': exepath = '"%s/Lib/site-packages/osgeo/ogr2ogr"' % sys.exec_prefix else: exepath...
[ "def", "convert2geojson", "(", "jsonfile", ",", "src_srs", ",", "dst_srs", ",", "src_file", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "jsonfile", ")", ":", "os", ".", "remove", "(", "jsonfile", ")", "if", "sysstr", "==", "'Windows'", ":", ...
convert shapefile to geojson file
[ "convert", "shapefile", "to", "geojson", "file" ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/vector.py#L80-L91
train
convert shapefile to geojson file
lreis2415/PyGeoC
pygeoc/vector.py
VectorUtilClass.write_line_shp
def write_line_shp(line_list, out_shp): """Export ESRI Shapefile -- Line feature""" print('Write line shapefile: %s' % out_shp) driver = ogr_GetDriverByName(str('ESRI Shapefile')) if driver is None: print('ESRI Shapefile driver not available.') sys.exit(1) ...
python
def write_line_shp(line_list, out_shp): """Export ESRI Shapefile -- Line feature""" print('Write line shapefile: %s' % out_shp) driver = ogr_GetDriverByName(str('ESRI Shapefile')) if driver is None: print('ESRI Shapefile driver not available.') sys.exit(1) ...
[ "def", "write_line_shp", "(", "line_list", ",", "out_shp", ")", ":", "print", "(", "'Write line shapefile: %s'", "%", "out_shp", ")", "driver", "=", "ogr_GetDriverByName", "(", "str", "(", "'ESRI Shapefile'", ")", ")", "if", "driver", "is", "None", ":", "print...
Export ESRI Shapefile -- Line feature
[ "Export", "ESRI", "Shapefile", "--", "Line", "feature" ]
9a92d1a229bb74298e3c57f27c97079980b5f729
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/vector.py#L94-L117
train
Export ESRI Shapefile -- Line feature
etal/biofrills
biofrills/consensus.py
consensus
def consensus(aln, weights=None, gap_threshold=0.5, simple=False, trim_ends=True): """Get the consensus of an alignment, as a string. Emit gap characters for majority-gap columns; apply various strategies to choose the consensus amino acid type for the remaining columns. Parameters ---------- ...
python
def consensus(aln, weights=None, gap_threshold=0.5, simple=False, trim_ends=True): """Get the consensus of an alignment, as a string. Emit gap characters for majority-gap columns; apply various strategies to choose the consensus amino acid type for the remaining columns. Parameters ---------- ...
[ "def", "consensus", "(", "aln", ",", "weights", "=", "None", ",", "gap_threshold", "=", "0.5", ",", "simple", "=", "False", ",", "trim_ends", "=", "True", ")", ":", "# Choose your algorithms!", "if", "simple", ":", "# Use the simple, unweighted algorithm", "col_...
Get the consensus of an alignment, as a string. Emit gap characters for majority-gap columns; apply various strategies to choose the consensus amino acid type for the remaining columns. Parameters ---------- simple : bool If True, use simple plurality to determine the consensus amino acid...
[ "Get", "the", "consensus", "of", "an", "alignment", "as", "a", "string", "." ]
36684bb6c7632f96215e8b2b4ebc86640f331bcd
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/consensus.py#L10-L130
train
Return the consensus sequence of an alignment as a string.
etal/biofrills
biofrills/consensus.py
make_entropy_col_consensus
def make_entropy_col_consensus(bg_freqs): """Consensus according to maximal relative entropy term (MET). For a given column i, choose the residue j with the highest relative entropy term:: f_ij ln(f_ij/b_j) where f_ij = column aa frequency, b_j = background aa frequency. Source: http://b...
python
def make_entropy_col_consensus(bg_freqs): """Consensus according to maximal relative entropy term (MET). For a given column i, choose the residue j with the highest relative entropy term:: f_ij ln(f_ij/b_j) where f_ij = column aa frequency, b_j = background aa frequency. Source: http://b...
[ "def", "make_entropy_col_consensus", "(", "bg_freqs", ")", ":", "def", "col_consensus", "(", "col", ")", ":", "col_freqs", "=", "sequtils", ".", "aa_frequencies", "(", "col", ")", "entroper", "=", "entropy_func", "(", "col_freqs", ",", "bg_freqs", ")", "return...
Consensus according to maximal relative entropy term (MET). For a given column i, choose the residue j with the highest relative entropy term:: f_ij ln(f_ij/b_j) where f_ij = column aa frequency, b_j = background aa frequency. Source: http://bioinformatics.oxfordjournals.org/content/24/18/19...
[ "Consensus", "according", "to", "maximal", "relative", "entropy", "term", "(", "MET", ")", "." ]
36684bb6c7632f96215e8b2b4ebc86640f331bcd
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/consensus.py#L143-L159
train
Consensus function for a given column.
etal/biofrills
biofrills/consensus.py
make_simple_col_consensus
def make_simple_col_consensus(bg_freqs): """Consensus by simple plurality, unweighted. Resolves ties by two heuristics: 1. Prefer the aa that follows the preceding consensus aa type most often in the original sequences. 2. Finally, prefer the less-common aa type. """ # Hack: use default...
python
def make_simple_col_consensus(bg_freqs): """Consensus by simple plurality, unweighted. Resolves ties by two heuristics: 1. Prefer the aa that follows the preceding consensus aa type most often in the original sequences. 2. Finally, prefer the less-common aa type. """ # Hack: use default...
[ "def", "make_simple_col_consensus", "(", "bg_freqs", ")", ":", "# Hack: use default kwargs to persist across iterations", "def", "col_consensus", "(", "col", ",", "prev_col", "=", "[", "]", ",", "prev_char", "=", "[", "]", ")", ":", "# Count the amino acid types in this...
Consensus by simple plurality, unweighted. Resolves ties by two heuristics: 1. Prefer the aa that follows the preceding consensus aa type most often in the original sequences. 2. Finally, prefer the less-common aa type.
[ "Consensus", "by", "simple", "plurality", "unweighted", "." ]
36684bb6c7632f96215e8b2b4ebc86640f331bcd
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/consensus.py#L166-L209
train
Create a simple column of amino acid types.
etal/biofrills
biofrills/consensus.py
supported
def supported(aln): """Get only the supported consensus residues in each column. Meaning: - Omit majority-gap columns - Omit columns where no residue type appears more than once - In case of a tie, return all the top-scoring residue types (no prioritization) Returns a *list* -- not a str...
python
def supported(aln): """Get only the supported consensus residues in each column. Meaning: - Omit majority-gap columns - Omit columns where no residue type appears more than once - In case of a tie, return all the top-scoring residue types (no prioritization) Returns a *list* -- not a str...
[ "def", "supported", "(", "aln", ")", ":", "def", "col_consensus", "(", "columns", ")", ":", "\"\"\"Calculate the consensus chars for an iterable of columns.\"\"\"", "for", "col", "in", "columns", ":", "if", "(", "# Majority gap chars", "(", "col", ".", "count", "(",...
Get only the supported consensus residues in each column. Meaning: - Omit majority-gap columns - Omit columns where no residue type appears more than once - In case of a tie, return all the top-scoring residue types (no prioritization) Returns a *list* -- not a string! -- where elements are ...
[ "Get", "only", "the", "supported", "consensus", "residues", "in", "each", "column", "." ]
36684bb6c7632f96215e8b2b4ebc86640f331bcd
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/consensus.py#L215-L261
train
Return only the supported consensus residues in each column.
zero-os/zerotier_client
zerotier/NetworkConfig.py
NetworkConfig.create
def create(authorizedMemberCount=None, clock=None, controllerInstanceId=None, creationTime=None, ipAssignmentPools=None, ipLocalRoutes=None, memberRevisionCounter=None, multicastLimit=None, name=None, nwid=None, private=None, relays=None, revision=None, rules=None, v4AssignMode=None, v6AssignMode=None): """ ...
python
def create(authorizedMemberCount=None, clock=None, controllerInstanceId=None, creationTime=None, ipAssignmentPools=None, ipLocalRoutes=None, memberRevisionCounter=None, multicastLimit=None, name=None, nwid=None, private=None, relays=None, revision=None, rules=None, v4AssignMode=None, v6AssignMode=None): """ ...
[ "def", "create", "(", "authorizedMemberCount", "=", "None", ",", "clock", "=", "None", ",", "controllerInstanceId", "=", "None", ",", "creationTime", "=", "None", ",", "ipAssignmentPools", "=", "None", ",", "ipLocalRoutes", "=", "None", ",", "memberRevisionCount...
:type authorizedMemberCount: int :type clock: int :type controllerInstanceId: str :type creationTime: int :type ipAssignmentPools: list[NetworkIpAssignmentPool] :type ipLocalRoutes: list[str] :type memberRevisionCounter: int :type multicastLimit: int :type...
[ ":", "type", "authorizedMemberCount", ":", "int", ":", "type", "clock", ":", "int", ":", "type", "controllerInstanceId", ":", "str", ":", "type", "creationTime", ":", "int", ":", "type", "ipAssignmentPools", ":", "list", "[", "NetworkIpAssignmentPool", "]", ":...
03993da11e69d837a0308a2f41ae7b378692fd82
https://github.com/zero-os/zerotier_client/blob/03993da11e69d837a0308a2f41ae7b378692fd82/zerotier/NetworkConfig.py#L17-L55
train
create a new NetworkConfig object
idlesign/django-sitecats
sitecats/templatetags/sitecats.py
detect_clause
def detect_clause(parser, clause_name, tokens, as_filter_expr=True): """Helper function detects a certain clause in tag tokens list. Returns its value. """ if clause_name in tokens: t_index = tokens.index(clause_name) clause_value = tokens[t_index + 1] if as_filter_expr: ...
python
def detect_clause(parser, clause_name, tokens, as_filter_expr=True): """Helper function detects a certain clause in tag tokens list. Returns its value. """ if clause_name in tokens: t_index = tokens.index(clause_name) clause_value = tokens[t_index + 1] if as_filter_expr: ...
[ "def", "detect_clause", "(", "parser", ",", "clause_name", ",", "tokens", ",", "as_filter_expr", "=", "True", ")", ":", "if", "clause_name", "in", "tokens", ":", "t_index", "=", "tokens", ".", "index", "(", "clause_name", ")", "clause_value", "=", "tokens", ...
Helper function detects a certain clause in tag tokens list. Returns its value.
[ "Helper", "function", "detects", "a", "certain", "clause", "in", "tag", "tokens", "list", ".", "Returns", "its", "value", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/templatetags/sitecats.py#L102-L115
train
Helper function detects a certain clause in tag tokens list.
toros-astro/corral
corral/cli/commands.py
Notebook.install_kernel_spec
def install_kernel_spec(self, app, dir_name, display_name, settings_module, ipython_arguments): """install an IPython >= 3.0 kernelspec that loads corral env Thanks: django extensions """ ksm = app.kernel_spec_manager try_spec_names = ['python3' if s...
python
def install_kernel_spec(self, app, dir_name, display_name, settings_module, ipython_arguments): """install an IPython >= 3.0 kernelspec that loads corral env Thanks: django extensions """ ksm = app.kernel_spec_manager try_spec_names = ['python3' if s...
[ "def", "install_kernel_spec", "(", "self", ",", "app", ",", "dir_name", ",", "display_name", ",", "settings_module", ",", "ipython_arguments", ")", ":", "ksm", "=", "app", ".", "kernel_spec_manager", "try_spec_names", "=", "[", "'python3'", "if", "six", ".", "...
install an IPython >= 3.0 kernelspec that loads corral env Thanks: django extensions
[ "install", "an", "IPython", ">", "=", "3", ".", "0", "kernelspec", "that", "loads", "corral", "env" ]
75474b38ff366330d33644461a902d07374a5bbc
https://github.com/toros-astro/corral/blob/75474b38ff366330d33644461a902d07374a5bbc/corral/cli/commands.py#L250-L289
train
install an IPython > = 3. 0 kernelspec that loads corral env
idlesign/django-sitecats
sitecats/utils.py
Cache._cache_init
def _cache_init(self): """Initializes local cache from Django cache if required.""" cache_ = cache.get(self.CACHE_ENTRY_NAME) if cache_ is None: categories = get_category_model().objects.order_by('sort_order') ids = {category.id: category for category in categories} ...
python
def _cache_init(self): """Initializes local cache from Django cache if required.""" cache_ = cache.get(self.CACHE_ENTRY_NAME) if cache_ is None: categories = get_category_model().objects.order_by('sort_order') ids = {category.id: category for category in categories} ...
[ "def", "_cache_init", "(", "self", ")", ":", "cache_", "=", "cache", ".", "get", "(", "self", ".", "CACHE_ENTRY_NAME", ")", "if", "cache_", "is", "None", ":", "categories", "=", "get_category_model", "(", ")", ".", "objects", ".", "order_by", "(", "'sort...
Initializes local cache from Django cache if required.
[ "Initializes", "local", "cache", "from", "Django", "cache", "if", "required", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L57-L85
train
Initializes local cache from Django cache if required.
idlesign/django-sitecats
sitecats/utils.py
Cache._cache_get_entry
def _cache_get_entry(self, entry_name, key=ENTIRE_ENTRY_KEY, default=False): """Returns cache entry parameter value by its name. :param str entry_name: :param str key: :param type default: :return: """ if key is self.ENTIRE_ENTRY_KEY: return self._cac...
python
def _cache_get_entry(self, entry_name, key=ENTIRE_ENTRY_KEY, default=False): """Returns cache entry parameter value by its name. :param str entry_name: :param str key: :param type default: :return: """ if key is self.ENTIRE_ENTRY_KEY: return self._cac...
[ "def", "_cache_get_entry", "(", "self", ",", "entry_name", ",", "key", "=", "ENTIRE_ENTRY_KEY", ",", "default", "=", "False", ")", ":", "if", "key", "is", "self", ".", "ENTIRE_ENTRY_KEY", ":", "return", "self", ".", "_cache", "[", "entry_name", "]", "retur...
Returns cache entry parameter value by its name. :param str entry_name: :param str key: :param type default: :return:
[ "Returns", "cache", "entry", "parameter", "value", "by", "its", "name", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L94-L104
train
Returns the cache entry parameter value by its name.
idlesign/django-sitecats
sitecats/utils.py
Cache.sort_aliases
def sort_aliases(self, aliases): """Sorts the given aliases list, returns a sorted list. :param list aliases: :return: sorted aliases list """ self._cache_init() if not aliases: return aliases parent_aliases = self._cache_get_entry(self.CACHE_NAME_PAR...
python
def sort_aliases(self, aliases): """Sorts the given aliases list, returns a sorted list. :param list aliases: :return: sorted aliases list """ self._cache_init() if not aliases: return aliases parent_aliases = self._cache_get_entry(self.CACHE_NAME_PAR...
[ "def", "sort_aliases", "(", "self", ",", "aliases", ")", ":", "self", ".", "_cache_init", "(", ")", "if", "not", "aliases", ":", "return", "aliases", "parent_aliases", "=", "self", ".", "_cache_get_entry", "(", "self", ".", "CACHE_NAME_PARENTS", ")", ".", ...
Sorts the given aliases list, returns a sorted list. :param list aliases: :return: sorted aliases list
[ "Sorts", "the", "given", "aliases", "list", "returns", "a", "sorted", "list", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L106-L116
train
Sorts the given aliases list returns a sorted list.
idlesign/django-sitecats
sitecats/utils.py
Cache.get_parents_for
def get_parents_for(self, child_ids): """Returns parent aliases for a list of child IDs. :param list child_ids: :rtype: set :return: a set of parent aliases """ self._cache_init() parent_candidates = [] for parent, children in self._cache_get_entry(self.C...
python
def get_parents_for(self, child_ids): """Returns parent aliases for a list of child IDs. :param list child_ids: :rtype: set :return: a set of parent aliases """ self._cache_init() parent_candidates = [] for parent, children in self._cache_get_entry(self.C...
[ "def", "get_parents_for", "(", "self", ",", "child_ids", ")", ":", "self", ".", "_cache_init", "(", ")", "parent_candidates", "=", "[", "]", "for", "parent", ",", "children", "in", "self", ".", "_cache_get_entry", "(", "self", ".", "CACHE_NAME_PARENTS", ")",...
Returns parent aliases for a list of child IDs. :param list child_ids: :rtype: set :return: a set of parent aliases
[ "Returns", "parent", "aliases", "for", "a", "list", "of", "child", "IDs", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L118-L130
train
Returns a set of parent aliases for a list of child IDs.
idlesign/django-sitecats
sitecats/utils.py
Cache.get_children_for
def get_children_for(self, parent_alias=None, only_with_aliases=False): """Returns a list with with categories under the given parent. :param str|None parent_alias: Parent category alias or None for categories under root :param bool only_with_aliases: Flag to return only children with aliases ...
python
def get_children_for(self, parent_alias=None, only_with_aliases=False): """Returns a list with with categories under the given parent. :param str|None parent_alias: Parent category alias or None for categories under root :param bool only_with_aliases: Flag to return only children with aliases ...
[ "def", "get_children_for", "(", "self", ",", "parent_alias", "=", "None", ",", "only_with_aliases", "=", "False", ")", ":", "self", ".", "_cache_init", "(", ")", "child_ids", "=", "self", ".", "get_child_ids", "(", "parent_alias", ")", "if", "only_with_aliases...
Returns a list with with categories under the given parent. :param str|None parent_alias: Parent category alias or None for categories under root :param bool only_with_aliases: Flag to return only children with aliases :return: a list of category objects
[ "Returns", "a", "list", "with", "with", "categories", "under", "the", "given", "parent", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L132-L148
train
Returns a list with categories under the given parent.
idlesign/django-sitecats
sitecats/utils.py
Cache.get_child_ids
def get_child_ids(self, parent_alias): """Returns child IDs of the given parent category :param str parent_alias: Parent category alias :rtype: list :return: a list of child IDs """ self._cache_init() return self._cache_get_entry(self.CACHE_NAME_PARENTS, parent_a...
python
def get_child_ids(self, parent_alias): """Returns child IDs of the given parent category :param str parent_alias: Parent category alias :rtype: list :return: a list of child IDs """ self._cache_init() return self._cache_get_entry(self.CACHE_NAME_PARENTS, parent_a...
[ "def", "get_child_ids", "(", "self", ",", "parent_alias", ")", ":", "self", ".", "_cache_init", "(", ")", "return", "self", ".", "_cache_get_entry", "(", "self", ".", "CACHE_NAME_PARENTS", ",", "parent_alias", ",", "[", "]", ")" ]
Returns child IDs of the given parent category :param str parent_alias: Parent category alias :rtype: list :return: a list of child IDs
[ "Returns", "child", "IDs", "of", "the", "given", "parent", "category" ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L150-L158
train
Returns the child IDs of the given parent category
idlesign/django-sitecats
sitecats/utils.py
Cache.get_category_by_alias
def get_category_by_alias(self, alias): """Returns Category object by its alias. :param str alias: :rtype: Category|None :return: category object """ self._cache_init() return self._cache_get_entry(self.CACHE_NAME_ALIASES, alias, None)
python
def get_category_by_alias(self, alias): """Returns Category object by its alias. :param str alias: :rtype: Category|None :return: category object """ self._cache_init() return self._cache_get_entry(self.CACHE_NAME_ALIASES, alias, None)
[ "def", "get_category_by_alias", "(", "self", ",", "alias", ")", ":", "self", ".", "_cache_init", "(", ")", "return", "self", ".", "_cache_get_entry", "(", "self", ".", "CACHE_NAME_ALIASES", ",", "alias", ",", "None", ")" ]
Returns Category object by its alias. :param str alias: :rtype: Category|None :return: category object
[ "Returns", "Category", "object", "by", "its", "alias", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L160-L168
train
Returns Category object by its alias.
idlesign/django-sitecats
sitecats/utils.py
Cache.get_category_by_id
def get_category_by_id(self, cid): """Returns Category object by its id. :param str cid: :rtype: Category :return: category object """ self._cache_init() return self._cache_get_entry(self.CACHE_NAME_IDS, cid)
python
def get_category_by_id(self, cid): """Returns Category object by its id. :param str cid: :rtype: Category :return: category object """ self._cache_init() return self._cache_get_entry(self.CACHE_NAME_IDS, cid)
[ "def", "get_category_by_id", "(", "self", ",", "cid", ")", ":", "self", ".", "_cache_init", "(", ")", "return", "self", ".", "_cache_get_entry", "(", "self", ".", "CACHE_NAME_IDS", ",", "cid", ")" ]
Returns Category object by its id. :param str cid: :rtype: Category :return: category object
[ "Returns", "Category", "object", "by", "its", "id", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L170-L178
train
Returns Category object by its id.
idlesign/django-sitecats
sitecats/utils.py
Cache.find_category
def find_category(self, parent_alias, title): """Searches parent category children for the given title (case independent). :param str parent_alias: :param str title: :rtype: Category|None :return: None if not found; otherwise - found Category """ found = None ...
python
def find_category(self, parent_alias, title): """Searches parent category children for the given title (case independent). :param str parent_alias: :param str title: :rtype: Category|None :return: None if not found; otherwise - found Category """ found = None ...
[ "def", "find_category", "(", "self", ",", "parent_alias", ",", "title", ")", ":", "found", "=", "None", "child_ids", "=", "self", ".", "get_child_ids", "(", "parent_alias", ")", "for", "cid", "in", "child_ids", ":", "category", "=", "self", ".", "get_categ...
Searches parent category children for the given title (case independent). :param str parent_alias: :param str title: :rtype: Category|None :return: None if not found; otherwise - found Category
[ "Searches", "parent", "category", "children", "for", "the", "given", "title", "(", "case", "independent", ")", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L180-L195
train
Searches parent category children for the given title.
idlesign/django-sitecats
sitecats/utils.py
Cache.get_ties_stats
def get_ties_stats(self, categories, target_model=None): """Returns a dict with categories popularity stats. :param list categories: :param Model|None target_model: :return: """ filter_kwargs = { 'category_id__in': categories } if target_model...
python
def get_ties_stats(self, categories, target_model=None): """Returns a dict with categories popularity stats. :param list categories: :param Model|None target_model: :return: """ filter_kwargs = { 'category_id__in': categories } if target_model...
[ "def", "get_ties_stats", "(", "self", ",", "categories", ",", "target_model", "=", "None", ")", ":", "filter_kwargs", "=", "{", "'category_id__in'", ":", "categories", "}", "if", "target_model", "is", "not", "None", ":", "is_cls", "=", "hasattr", "(", "targe...
Returns a dict with categories popularity stats. :param list categories: :param Model|None target_model: :return:
[ "Returns", "a", "dict", "with", "categories", "popularity", "stats", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L197-L221
train
Returns a dict with categories popularity stats.
idlesign/django-sitecats
sitecats/utils.py
Cache.get_categories
def get_categories(self, parent_aliases=None, target_object=None, tied_only=True): """Returns subcategories (or ties if `target_object` is set) for the given parent category. :param str|None|list parent_aliases: :param ModelWithCategory|Model target_object: :param bool tied_only...
python
def get_categories(self, parent_aliases=None, target_object=None, tied_only=True): """Returns subcategories (or ties if `target_object` is set) for the given parent category. :param str|None|list parent_aliases: :param ModelWithCategory|Model target_object: :param bool tied_only...
[ "def", "get_categories", "(", "self", ",", "parent_aliases", "=", "None", ",", "target_object", "=", "None", ",", "tied_only", "=", "True", ")", ":", "single_mode", "=", "False", "if", "not", "isinstance", "(", "parent_aliases", ",", "list", ")", ":", "sin...
Returns subcategories (or ties if `target_object` is set) for the given parent category. :param str|None|list parent_aliases: :param ModelWithCategory|Model target_object: :param bool tied_only: Flag to get only categories with ties. Ties stats are stored in `ties_num` attrs. :r...
[ "Returns", "subcategories", "(", "or", "ties", "if", "target_object", "is", "set", ")", "for", "the", "given", "parent", "category", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/utils.py#L223-L273
train
Returns a list of subcategories or ties objects extended with information from their categories.
PeerAssets/pypeerassets
pypeerassets/pautils.py
load_p2th_privkey_into_local_node
def load_p2th_privkey_into_local_node(provider: RpcNode, prod: bool=True) -> None: '''Load PeerAssets P2TH privkey into the local node.''' assert isinstance(provider, RpcNode), {"error": "Import only works with local node."} error = {"error": "Loading P2TH privkey failed."} pa_params = param_query(prov...
python
def load_p2th_privkey_into_local_node(provider: RpcNode, prod: bool=True) -> None: '''Load PeerAssets P2TH privkey into the local node.''' assert isinstance(provider, RpcNode), {"error": "Import only works with local node."} error = {"error": "Loading P2TH privkey failed."} pa_params = param_query(prov...
[ "def", "load_p2th_privkey_into_local_node", "(", "provider", ":", "RpcNode", ",", "prod", ":", "bool", "=", "True", ")", "->", "None", ":", "assert", "isinstance", "(", "provider", ",", "RpcNode", ")", ",", "{", "\"error\"", ":", "\"Import only works with local ...
Load PeerAssets P2TH privkey into the local node.
[ "Load", "PeerAssets", "P2TH", "privkey", "into", "the", "local", "node", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L30-L45
train
Load PeerAssets P2TH privkey into the local node.
PeerAssets/pypeerassets
pypeerassets/pautils.py
find_tx_sender
def find_tx_sender(provider: Provider, raw_tx: dict) -> str: '''find transaction sender, vin[0] is used in this case.''' vin = raw_tx["vin"][0] txid = vin["txid"] index = vin["vout"] return provider.getrawtransaction(txid, 1)["vout"][index]["scriptPubKey"]["addresses"][0]
python
def find_tx_sender(provider: Provider, raw_tx: dict) -> str: '''find transaction sender, vin[0] is used in this case.''' vin = raw_tx["vin"][0] txid = vin["txid"] index = vin["vout"] return provider.getrawtransaction(txid, 1)["vout"][index]["scriptPubKey"]["addresses"][0]
[ "def", "find_tx_sender", "(", "provider", ":", "Provider", ",", "raw_tx", ":", "dict", ")", "->", "str", ":", "vin", "=", "raw_tx", "[", "\"vin\"", "]", "[", "0", "]", "txid", "=", "vin", "[", "\"txid\"", "]", "index", "=", "vin", "[", "\"vout\"", ...
find transaction sender, vin[0] is used in this case.
[ "find", "transaction", "sender", "vin", "[", "0", "]", "is", "used", "in", "this", "case", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L48-L54
train
find transaction sender vin [ 0 is used in this case.
PeerAssets/pypeerassets
pypeerassets/pautils.py
find_deck_spawns
def find_deck_spawns(provider: Provider, prod: bool=True) -> Iterable[str]: '''find deck spawn transactions via Provider, it requires that Deck spawn P2TH were imported in local node or that remote API knows about P2TH address.''' pa_params = param_query(provider.network) if isinstance(provider, R...
python
def find_deck_spawns(provider: Provider, prod: bool=True) -> Iterable[str]: '''find deck spawn transactions via Provider, it requires that Deck spawn P2TH were imported in local node or that remote API knows about P2TH address.''' pa_params = param_query(provider.network) if isinstance(provider, R...
[ "def", "find_deck_spawns", "(", "provider", ":", "Provider", ",", "prod", ":", "bool", "=", "True", ")", "->", "Iterable", "[", "str", "]", ":", "pa_params", "=", "param_query", "(", "provider", ".", "network", ")", "if", "isinstance", "(", "provider", "...
find deck spawn transactions via Provider, it requires that Deck spawn P2TH were imported in local node or that remote API knows about P2TH address.
[ "find", "deck", "spawn", "transactions", "via", "Provider", "it", "requires", "that", "Deck", "spawn", "P2TH", "were", "imported", "in", "local", "node", "or", "that", "remote", "API", "knows", "about", "P2TH", "address", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L57-L78
train
find deck spawn transactions via Provider prod means that Deck spawn P2TH was imported in local node or remote API knows about P2TH address.
PeerAssets/pypeerassets
pypeerassets/pautils.py
deck_parser
def deck_parser(args: Tuple[Provider, dict, int, str], prod: bool=True) -> Optional[Deck]: '''deck parser function''' provider = args[0] raw_tx = args[1] deck_version = args[2] p2th = args[3] try: validate_deckspawn_p2th(provider, raw_tx, p2th) d = parse_decksp...
python
def deck_parser(args: Tuple[Provider, dict, int, str], prod: bool=True) -> Optional[Deck]: '''deck parser function''' provider = args[0] raw_tx = args[1] deck_version = args[2] p2th = args[3] try: validate_deckspawn_p2th(provider, raw_tx, p2th) d = parse_decksp...
[ "def", "deck_parser", "(", "args", ":", "Tuple", "[", "Provider", ",", "dict", ",", "int", ",", "str", "]", ",", "prod", ":", "bool", "=", "True", ")", "->", "Optional", "[", "Deck", "]", ":", "provider", "=", "args", "[", "0", "]", "raw_tx", "="...
deck parser function
[ "deck", "parser", "function" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L81-L113
train
deck parser function
PeerAssets/pypeerassets
pypeerassets/pautils.py
tx_serialization_order
def tx_serialization_order(provider: Provider, blockhash: str, txid: str) -> int: '''find index of this tx in the blockid''' return provider.getblock(blockhash)["tx"].index(txid)
python
def tx_serialization_order(provider: Provider, blockhash: str, txid: str) -> int: '''find index of this tx in the blockid''' return provider.getblock(blockhash)["tx"].index(txid)
[ "def", "tx_serialization_order", "(", "provider", ":", "Provider", ",", "blockhash", ":", "str", ",", "txid", ":", "str", ")", "->", "int", ":", "return", "provider", ".", "getblock", "(", "blockhash", ")", "[", "\"tx\"", "]", ".", "index", "(", "txid", ...
find index of this tx in the blockid
[ "find", "index", "of", "this", "tx", "in", "the", "blockid" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L116-L119
train
find the index of this tx in the blockid
PeerAssets/pypeerassets
pypeerassets/pautils.py
read_tx_opreturn
def read_tx_opreturn(vout: dict) -> bytes: '''Decode OP_RETURN message from vout[1]''' asm = vout['scriptPubKey']['asm'] n = asm.find('OP_RETURN') if n == -1: raise InvalidNulldataOutput({'error': 'OP_RETURN not found.'}) else: # add 10 because 'OP_RETURN ' is 10 characters ...
python
def read_tx_opreturn(vout: dict) -> bytes: '''Decode OP_RETURN message from vout[1]''' asm = vout['scriptPubKey']['asm'] n = asm.find('OP_RETURN') if n == -1: raise InvalidNulldataOutput({'error': 'OP_RETURN not found.'}) else: # add 10 because 'OP_RETURN ' is 10 characters ...
[ "def", "read_tx_opreturn", "(", "vout", ":", "dict", ")", "->", "bytes", ":", "asm", "=", "vout", "[", "'scriptPubKey'", "]", "[", "'asm'", "]", "n", "=", "asm", ".", "find", "(", "'OP_RETURN'", ")", "if", "n", "==", "-", "1", ":", "raise", "Invali...
Decode OP_RETURN message from vout[1]
[ "Decode", "OP_RETURN", "message", "from", "vout", "[", "1", "]" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L122-L138
train
Decode OP_RETURN message from vout [ 1 ]
PeerAssets/pypeerassets
pypeerassets/pautils.py
deck_issue_mode
def deck_issue_mode(proto: DeckSpawnProto) -> Iterable[str]: '''interpret issue mode bitfeg''' if proto.issue_mode == 0: yield "NONE" return for mode, value in proto.MODE.items(): if value > proto.issue_mode: continue if value & proto.issue_mode: yie...
python
def deck_issue_mode(proto: DeckSpawnProto) -> Iterable[str]: '''interpret issue mode bitfeg''' if proto.issue_mode == 0: yield "NONE" return for mode, value in proto.MODE.items(): if value > proto.issue_mode: continue if value & proto.issue_mode: yie...
[ "def", "deck_issue_mode", "(", "proto", ":", "DeckSpawnProto", ")", "->", "Iterable", "[", "str", "]", ":", "if", "proto", ".", "issue_mode", "==", "0", ":", "yield", "\"NONE\"", "return", "for", "mode", ",", "value", "in", "proto", ".", "MODE", ".", "...
interpret issue mode bitfeg
[ "interpret", "issue", "mode", "bitfeg" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L141-L152
train
interpret issue mode bitfeg yield list of names
PeerAssets/pypeerassets
pypeerassets/pautils.py
issue_mode_to_enum
def issue_mode_to_enum(deck: DeckSpawnProto, issue_mode: list) -> int: '''encode issue mode(s) as bitfeg''' # case where there are multiple issue modes specified if isinstance(issue_mode, list) and len(issue_mode) > 1: r = 0 for mode in issue_mode: r += deck.MODE.Value(mode) ...
python
def issue_mode_to_enum(deck: DeckSpawnProto, issue_mode: list) -> int: '''encode issue mode(s) as bitfeg''' # case where there are multiple issue modes specified if isinstance(issue_mode, list) and len(issue_mode) > 1: r = 0 for mode in issue_mode: r += deck.MODE.Value(mode) ...
[ "def", "issue_mode_to_enum", "(", "deck", ":", "DeckSpawnProto", ",", "issue_mode", ":", "list", ")", "->", "int", ":", "# case where there are multiple issue modes specified", "if", "isinstance", "(", "issue_mode", ",", "list", ")", "and", "len", "(", "issue_mode",...
encode issue mode(s) as bitfeg
[ "encode", "issue", "mode", "(", "s", ")", "as", "bitfeg" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L155-L169
train
encode issue mode s as bitfeg
PeerAssets/pypeerassets
pypeerassets/pautils.py
parse_deckspawn_metainfo
def parse_deckspawn_metainfo(protobuf: bytes, version: int) -> dict: '''Decode deck_spawn tx op_return protobuf message and validate it, Raise error if deck_spawn metainfo incomplete or version mistmatch.''' deck = DeckSpawnProto() deck.ParseFromString(protobuf) error = {"error": "Deck ({deck})...
python
def parse_deckspawn_metainfo(protobuf: bytes, version: int) -> dict: '''Decode deck_spawn tx op_return protobuf message and validate it, Raise error if deck_spawn metainfo incomplete or version mistmatch.''' deck = DeckSpawnProto() deck.ParseFromString(protobuf) error = {"error": "Deck ({deck})...
[ "def", "parse_deckspawn_metainfo", "(", "protobuf", ":", "bytes", ",", "version", ":", "int", ")", "->", "dict", ":", "deck", "=", "DeckSpawnProto", "(", ")", "deck", ".", "ParseFromString", "(", "protobuf", ")", "error", "=", "{", "\"error\"", ":", "\"Dec...
Decode deck_spawn tx op_return protobuf message and validate it, Raise error if deck_spawn metainfo incomplete or version mistmatch.
[ "Decode", "deck_spawn", "tx", "op_return", "protobuf", "message", "and", "validate", "it", "Raise", "error", "if", "deck_spawn", "metainfo", "incomplete", "or", "version", "mistmatch", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L172-L193
train
Decode deck_spawn tx op_return protobuf message and validate it raise InvalidDeckVersion Raise error if deck_spawn metainfo incomplete or version mistmatch.
PeerAssets/pypeerassets
pypeerassets/pautils.py
validate_deckspawn_p2th
def validate_deckspawn_p2th(provider: Provider, rawtx: dict, p2th: str) -> bool: '''Return True if deck spawn pays to p2th in vout[0] and if the P2TH address is correct. Otherwise raises InvalidDeckSpawn. ''' try: vout = rawtx["vout"][0]["scriptPubKey"].get("addresses")[0] except TypeError:...
python
def validate_deckspawn_p2th(provider: Provider, rawtx: dict, p2th: str) -> bool: '''Return True if deck spawn pays to p2th in vout[0] and if the P2TH address is correct. Otherwise raises InvalidDeckSpawn. ''' try: vout = rawtx["vout"][0]["scriptPubKey"].get("addresses")[0] except TypeError:...
[ "def", "validate_deckspawn_p2th", "(", "provider", ":", "Provider", ",", "rawtx", ":", "dict", ",", "p2th", ":", "str", ")", "->", "bool", ":", "try", ":", "vout", "=", "rawtx", "[", "\"vout\"", "]", "[", "0", "]", "[", "\"scriptPubKey\"", "]", ".", ...
Return True if deck spawn pays to p2th in vout[0] and if the P2TH address is correct. Otherwise raises InvalidDeckSpawn.
[ "Return", "True", "if", "deck", "spawn", "pays", "to", "p2th", "in", "vout", "[", "0", "]", "and", "if", "the", "P2TH", "address", "is", "correct", ".", "Otherwise", "raises", "InvalidDeckSpawn", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L196-L210
train
Return True if deck spawn pays to p2th in vout [ 0 ] and the P2TH address is correct. Otherwise raises InvalidDeckSpawn.
PeerAssets/pypeerassets
pypeerassets/pautils.py
load_deck_p2th_into_local_node
def load_deck_p2th_into_local_node(provider: RpcNode, deck: Deck) -> None: ''' load deck p2th into local node via "importprivke", this allows building of proof-of-timeline for this deck ''' assert isinstance(provider, RpcNode), {"error": "You can load privkeys only into local node."} error = {"...
python
def load_deck_p2th_into_local_node(provider: RpcNode, deck: Deck) -> None: ''' load deck p2th into local node via "importprivke", this allows building of proof-of-timeline for this deck ''' assert isinstance(provider, RpcNode), {"error": "You can load privkeys only into local node."} error = {"...
[ "def", "load_deck_p2th_into_local_node", "(", "provider", ":", "RpcNode", ",", "deck", ":", "Deck", ")", "->", "None", ":", "assert", "isinstance", "(", "provider", ",", "RpcNode", ")", ",", "{", "\"error\"", ":", "\"You can load privkeys only into local node.\"", ...
load deck p2th into local node via "importprivke", this allows building of proof-of-timeline for this deck
[ "load", "deck", "p2th", "into", "local", "node", "via", "importprivke", "this", "allows", "building", "of", "proof", "-", "of", "-", "timeline", "for", "this", "deck" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L213-L226
train
Load deck p2th into local node via importprivke
PeerAssets/pypeerassets
pypeerassets/pautils.py
validate_card_transfer_p2th
def validate_card_transfer_p2th(deck: Deck, vout: dict) -> None: '''validate if card_transfer transaction pays to deck p2th in vout[0]''' error = {"error": "Card transfer is not properly tagged."} try: address = vout["scriptPubKey"].get("addresses")[0] if not address == deck.p2th_address: ...
python
def validate_card_transfer_p2th(deck: Deck, vout: dict) -> None: '''validate if card_transfer transaction pays to deck p2th in vout[0]''' error = {"error": "Card transfer is not properly tagged."} try: address = vout["scriptPubKey"].get("addresses")[0] if not address == deck.p2th_address: ...
[ "def", "validate_card_transfer_p2th", "(", "deck", ":", "Deck", ",", "vout", ":", "dict", ")", "->", "None", ":", "error", "=", "{", "\"error\"", ":", "\"Card transfer is not properly tagged.\"", "}", "try", ":", "address", "=", "vout", "[", "\"scriptPubKey\"", ...
validate if card_transfer transaction pays to deck p2th in vout[0]
[ "validate", "if", "card_transfer", "transaction", "pays", "to", "deck", "p2th", "in", "vout", "[", "0", "]" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L229-L239
train
validate if card_transfer transaction pays to deck p2th in vout [ 0 ]
PeerAssets/pypeerassets
pypeerassets/pautils.py
parse_card_transfer_metainfo
def parse_card_transfer_metainfo(protobuf: bytes, deck_version: int) -> dict: '''decode card_spawn protobuf message and validate it against deck.version :protobuf - bytes from op_return message :deck_version - integer ''' card = CardTransferProto() card.ParseFromString(protobuf) if not car...
python
def parse_card_transfer_metainfo(protobuf: bytes, deck_version: int) -> dict: '''decode card_spawn protobuf message and validate it against deck.version :protobuf - bytes from op_return message :deck_version - integer ''' card = CardTransferProto() card.ParseFromString(protobuf) if not car...
[ "def", "parse_card_transfer_metainfo", "(", "protobuf", ":", "bytes", ",", "deck_version", ":", "int", ")", "->", "dict", ":", "card", "=", "CardTransferProto", "(", ")", "card", ".", "ParseFromString", "(", "protobuf", ")", "if", "not", "card", ".", "versio...
decode card_spawn protobuf message and validate it against deck.version :protobuf - bytes from op_return message :deck_version - integer
[ "decode", "card_spawn", "protobuf", "message", "and", "validate", "it", "against", "deck", ".", "version", ":", "protobuf", "-", "bytes", "from", "op_return", "message", ":", "deck_version", "-", "integer" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L242-L259
train
decode card spawn protobuf message and validate it against deck. version
PeerAssets/pypeerassets
pypeerassets/pautils.py
card_bundle_parser
def card_bundle_parser(bundle: CardBundle, debug=False) -> Iterator: '''this function wraps all the card transfer parsing''' try: # first vout of the bundle must pay to deck.p2th validate_card_transfer_p2th(bundle.deck, bundle.vouts[0]) # second vout must be OP_RETURN with card_metainf...
python
def card_bundle_parser(bundle: CardBundle, debug=False) -> Iterator: '''this function wraps all the card transfer parsing''' try: # first vout of the bundle must pay to deck.p2th validate_card_transfer_p2th(bundle.deck, bundle.vouts[0]) # second vout must be OP_RETURN with card_metainf...
[ "def", "card_bundle_parser", "(", "bundle", ":", "CardBundle", ",", "debug", "=", "False", ")", "->", "Iterator", ":", "try", ":", "# first vout of the bundle must pay to deck.p2th", "validate_card_transfer_p2th", "(", "bundle", ".", "deck", ",", "bundle", ".", "vou...
this function wraps all the card transfer parsing
[ "this", "function", "wraps", "all", "the", "card", "transfer", "parsing" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pautils.py#L283-L333
train
this function wraps all the card transfer parsing
moonso/ped_parser
ped_parser/log.py
init_log
def init_log(logger, filename=None, loglevel=None): """ Initializes the log file in the proper format. Arguments: filename (str): Path to a file. Or None if logging is to be disabled. loglevel (str): Determines the level of the log output. """ ...
python
def init_log(logger, filename=None, loglevel=None): """ Initializes the log file in the proper format. Arguments: filename (str): Path to a file. Or None if logging is to be disabled. loglevel (str): Determines the level of the log output. """ ...
[ "def", "init_log", "(", "logger", ",", "filename", "=", "None", ",", "loglevel", "=", "None", ")", ":", "formatter", "=", "logging", ".", "Formatter", "(", "'[%(asctime)s] %(levelname)s: %(name)s: %(message)s'", ")", "if", "loglevel", ":", "logger", ".", "setLev...
Initializes the log file in the proper format. Arguments: filename (str): Path to a file. Or None if logging is to be disabled. loglevel (str): Determines the level of the log output.
[ "Initializes", "the", "log", "file", "in", "the", "proper", "format", ".", "Arguments", ":", "filename", "(", "str", ")", ":", "Path", "to", "a", "file", ".", "Or", "None", "if", "logging", "is", "to", "be", "disabled", ".", "loglevel", "(", "str", "...
a7393e47139532782ea3c821aabea33d46f94323
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/log.py#L5-L40
train
Initializes the log file in the proper format.
PeerAssets/pypeerassets
pypeerassets/pa_constants.py
param_query
def param_query(name: str) -> PAParams: '''Find the PAParams for a network by its long or short name. Raises UnsupportedNetwork if no PAParams is found. ''' for pa_params in params: if name in (pa_params.network_name, pa_params.network_shortname,): return pa_params raise Unsupp...
python
def param_query(name: str) -> PAParams: '''Find the PAParams for a network by its long or short name. Raises UnsupportedNetwork if no PAParams is found. ''' for pa_params in params: if name in (pa_params.network_name, pa_params.network_shortname,): return pa_params raise Unsupp...
[ "def", "param_query", "(", "name", ":", "str", ")", "->", "PAParams", ":", "for", "pa_params", "in", "params", ":", "if", "name", "in", "(", "pa_params", ".", "network_name", ",", "pa_params", ".", "network_shortname", ",", ")", ":", "return", "pa_params",...
Find the PAParams for a network by its long or short name. Raises UnsupportedNetwork if no PAParams is found.
[ "Find", "the", "PAParams", "for", "a", "network", "by", "its", "long", "or", "short", "name", ".", "Raises", "UnsupportedNetwork", "if", "no", "PAParams", "is", "found", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/pa_constants.py#L33-L42
train
Find the PAParams for a network by its long or short name. Raises UnsupportedNetwork if no PAParams is found.
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/gui/qt_b26_gui.py
ControlMainWindow.closeEvent
def closeEvent(self, event): """ things to be done when gui closes, like save the settings """ self.script_thread.quit() self.read_probes.quit() if self.config_filename: fname = self.config_filename self.save_config(fname) event.accept() ...
python
def closeEvent(self, event): """ things to be done when gui closes, like save the settings """ self.script_thread.quit() self.read_probes.quit() if self.config_filename: fname = self.config_filename self.save_config(fname) event.accept() ...
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "self", ".", "script_thread", ".", "quit", "(", ")", "self", ".", "read_probes", ".", "quit", "(", ")", "if", "self", ".", "config_filename", ":", "fname", "=", "self", ".", "config_filename", "...
things to be done when gui closes, like save the settings
[ "things", "to", "be", "done", "when", "gui", "closes", "like", "save", "the", "settings" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_gui.py#L265-L280
train
This function is called when the GUI closes.
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/gui/qt_b26_gui.py
ControlMainWindow.plot_clicked
def plot_clicked(self, mouse_event): """ gets activated when the user clicks on a plot Args: mouse_event: """ if isinstance(self.current_script, SelectPoints) and self.current_script.is_running: if (not (mouse_event.xdata == None)): if (mou...
python
def plot_clicked(self, mouse_event): """ gets activated when the user clicks on a plot Args: mouse_event: """ if isinstance(self.current_script, SelectPoints) and self.current_script.is_running: if (not (mouse_event.xdata == None)): if (mou...
[ "def", "plot_clicked", "(", "self", ",", "mouse_event", ")", ":", "if", "isinstance", "(", "self", ".", "current_script", ",", "SelectPoints", ")", "and", "self", ".", "current_script", ".", "is_running", ":", "if", "(", "not", "(", "mouse_event", ".", "xd...
gets activated when the user clicks on a plot Args: mouse_event:
[ "gets", "activated", "when", "the", "user", "clicks", "on", "a", "plot", "Args", ":", "mouse_event", ":" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_gui.py#L413-L452
train
This function is called when the user clicks on a plot in the tree.
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/gui/qt_b26_gui.py
ControlMainWindow.load_scripts
def load_scripts(self): """ opens file dialog to load scripts into gui """ # update scripts so that current settings do not get lost for index in range(self.tree_scripts.topLevelItemCount()): script_item = self.tree_scripts.topLevelItem(index...
python
def load_scripts(self): """ opens file dialog to load scripts into gui """ # update scripts so that current settings do not get lost for index in range(self.tree_scripts.topLevelItemCount()): script_item = self.tree_scripts.topLevelItem(index...
[ "def", "load_scripts", "(", "self", ")", ":", "# update scripts so that current settings do not get lost", "for", "index", "in", "range", "(", "self", ".", "tree_scripts", ".", "topLevelItemCount", "(", ")", ")", ":", "script_item", "=", "self", ".", "tree_scripts",...
opens file dialog to load scripts into gui
[ "opens", "file", "dialog", "to", "load", "scripts", "into", "gui" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_gui.py#L523-L558
train
Opens file dialog to load scripts into the GUI
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/gui/qt_b26_gui.py
ControlMainWindow.edit_tree_item
def edit_tree_item(self): """ if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath this filepath will be updated in the field of self.tree_gui_settings that has been double clicked """ def open_path_dialog(path): """ open...
python
def edit_tree_item(self): """ if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath this filepath will be updated in the field of self.tree_gui_settings that has been double clicked """ def open_path_dialog(path): """ open...
[ "def", "edit_tree_item", "(", "self", ")", ":", "def", "open_path_dialog", "(", "path", ")", ":", "\"\"\"\n opens a file dialog to get the path to a file and\n \"\"\"", "dialog", "=", "QtWidgets", ".", "QFileDialog", "(", ")", "dialog", ".", "setFile...
if sender is self.tree_gui_settings this will open a filedialog and ask for a filepath this filepath will be updated in the field of self.tree_gui_settings that has been double clicked
[ "if", "sender", "is", "self", ".", "tree_gui_settings", "this", "will", "open", "a", "filedialog", "and", "ask", "for", "a", "filepath", "this", "filepath", "will", "be", "updated", "in", "the", "field", "of", "self", ".", "tree_gui_settings", "that", "has",...
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_gui.py#L1148-L1180
train
Edit the tree item with the current filepath
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/gui/qt_b26_gui.py
ControlMainWindow.load_config
def load_config(self, file_name): """ checks if the file is a valid config file Args: file_name: """ # load config or default if invalid def load_settings(file_name): """ loads a old_gui settings file (a json dictionary) ...
python
def load_config(self, file_name): """ checks if the file is a valid config file Args: file_name: """ # load config or default if invalid def load_settings(file_name): """ loads a old_gui settings file (a json dictionary) ...
[ "def", "load_config", "(", "self", ",", "file_name", ")", ":", "# load config or default if invalid", "def", "load_settings", "(", "file_name", ")", ":", "\"\"\"\n loads a old_gui settings file (a json dictionary)\n - path_to_file: path to file that contains the d...
checks if the file is a valid config file Args: file_name:
[ "checks", "if", "the", "file", "is", "a", "valid", "config", "file", "Args", ":", "file_name", ":" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_gui.py#L1225-L1317
train
loads a config file and returns a tuple of instruments scripts probes and settings
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/gui/qt_b26_gui.py
ControlMainWindow.save_config
def save_config(self, out_file_name): """ saves gui configuration to out_file_name Args: out_file_name: name of file """ def get_hidden_parameter(item): numer_of_sub_elements = item.childCount() if numer_of_sub_elements == 0: ...
python
def save_config(self, out_file_name): """ saves gui configuration to out_file_name Args: out_file_name: name of file """ def get_hidden_parameter(item): numer_of_sub_elements = item.childCount() if numer_of_sub_elements == 0: ...
[ "def", "save_config", "(", "self", ",", "out_file_name", ")", ":", "def", "get_hidden_parameter", "(", "item", ")", ":", "numer_of_sub_elements", "=", "item", ".", "childCount", "(", ")", "if", "numer_of_sub_elements", "==", "0", ":", "dictator", "=", "{", "...
saves gui configuration to out_file_name Args: out_file_name: name of file
[ "saves", "gui", "configuration", "to", "out_file_name", "Args", ":", "out_file_name", ":", "name", "of", "file" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_gui.py#L1354-L1401
train
Save the gui configuration to a file.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.getblockhash
def getblockhash(self, index: int) -> str: '''Returns the hash of the block at ; index 0 is the genesis block.''' return cast(str, self.api_fetch('getblockhash?index=' + str(index)))
python
def getblockhash(self, index: int) -> str: '''Returns the hash of the block at ; index 0 is the genesis block.''' return cast(str, self.api_fetch('getblockhash?index=' + str(index)))
[ "def", "getblockhash", "(", "self", ",", "index", ":", "int", ")", "->", "str", ":", "return", "cast", "(", "str", ",", "self", ".", "api_fetch", "(", "'getblockhash?index='", "+", "str", "(", "index", ")", ")", ")" ]
Returns the hash of the block at ; index 0 is the genesis block.
[ "Returns", "the", "hash", "of", "the", "block", "at", ";", "index", "0", "is", "the", "genesis", "block", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L73-L76
train
Returns the hash of the block at the specified index.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.getblock
def getblock(self, hash: str) -> dict: '''Returns information about the block with the given hash.''' return cast(dict, self.api_fetch('getblock?hash=' + hash))
python
def getblock(self, hash: str) -> dict: '''Returns information about the block with the given hash.''' return cast(dict, self.api_fetch('getblock?hash=' + hash))
[ "def", "getblock", "(", "self", ",", "hash", ":", "str", ")", "->", "dict", ":", "return", "cast", "(", "dict", ",", "self", ".", "api_fetch", "(", "'getblock?hash='", "+", "hash", ")", ")" ]
Returns information about the block with the given hash.
[ "Returns", "information", "about", "the", "block", "with", "the", "given", "hash", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L78-L81
train
Returns information about the block with the given hash.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.getrawtransaction
def getrawtransaction(self, txid: str, decrypt: int=0) -> dict: '''Returns raw transaction representation for given transaction id. decrypt can be set to 0(false) or 1(true).''' q = 'getrawtransaction?txid={txid}&decrypt={decrypt}'.format(txid=txid, decrypt=decrypt) return cast(dict, s...
python
def getrawtransaction(self, txid: str, decrypt: int=0) -> dict: '''Returns raw transaction representation for given transaction id. decrypt can be set to 0(false) or 1(true).''' q = 'getrawtransaction?txid={txid}&decrypt={decrypt}'.format(txid=txid, decrypt=decrypt) return cast(dict, s...
[ "def", "getrawtransaction", "(", "self", ",", "txid", ":", "str", ",", "decrypt", ":", "int", "=", "0", ")", "->", "dict", ":", "q", "=", "'getrawtransaction?txid={txid}&decrypt={decrypt}'", ".", "format", "(", "txid", "=", "txid", ",", "decrypt", "=", "de...
Returns raw transaction representation for given transaction id. decrypt can be set to 0(false) or 1(true).
[ "Returns", "raw", "transaction", "representation", "for", "given", "transaction", "id", ".", "decrypt", "can", "be", "set", "to", "0", "(", "false", ")", "or", "1", "(", "true", ")", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L83-L89
train
Returns raw transaction representation for given transaction id.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.getaddress
def getaddress(self, address: str) -> dict: '''Returns information for given address.''' return cast(dict, self.ext_fetch('getaddress/' + address))
python
def getaddress(self, address: str) -> dict: '''Returns information for given address.''' return cast(dict, self.ext_fetch('getaddress/' + address))
[ "def", "getaddress", "(", "self", ",", "address", ":", "str", ")", "->", "dict", ":", "return", "cast", "(", "dict", ",", "self", ".", "ext_fetch", "(", "'getaddress/'", "+", "address", ")", ")" ]
Returns information for given address.
[ "Returns", "information", "for", "given", "address", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L106-L109
train
Returns information for given address.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.listunspent
def listunspent(self, address: str) -> list: '''Returns unspent transactions for given address.''' try: return cast(dict, self.ext_fetch('listunspent/' + address))['unspent_outputs'] except KeyError: raise InsufficientFunds('Insufficient funds.')
python
def listunspent(self, address: str) -> list: '''Returns unspent transactions for given address.''' try: return cast(dict, self.ext_fetch('listunspent/' + address))['unspent_outputs'] except KeyError: raise InsufficientFunds('Insufficient funds.')
[ "def", "listunspent", "(", "self", ",", "address", ":", "str", ")", "->", "list", ":", "try", ":", "return", "cast", "(", "dict", ",", "self", ".", "ext_fetch", "(", "'listunspent/'", "+", "address", ")", ")", "[", "'unspent_outputs'", "]", "except", "...
Returns unspent transactions for given address.
[ "Returns", "unspent", "transactions", "for", "given", "address", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L111-L117
train
Returns unspent transactions for given address.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.txinfo
def txinfo(self, txid: str) -> dict: '''Returns information about given transaction.''' return cast(dict, self.ext_fetch('txinfo/' + txid))
python
def txinfo(self, txid: str) -> dict: '''Returns information about given transaction.''' return cast(dict, self.ext_fetch('txinfo/' + txid))
[ "def", "txinfo", "(", "self", ",", "txid", ":", "str", ")", "->", "dict", ":", "return", "cast", "(", "dict", ",", "self", ".", "ext_fetch", "(", "'txinfo/'", "+", "txid", ")", ")" ]
Returns information about given transaction.
[ "Returns", "information", "about", "given", "transaction", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L141-L144
train
Returns information about given transaction.
PeerAssets/pypeerassets
pypeerassets/provider/explorer.py
Explorer.getbalance
def getbalance(self, address: str) -> Decimal: '''Returns current balance of given address.''' try: return Decimal(cast(float, self.ext_fetch('getbalance/' + address))) except TypeError: return Decimal(0)
python
def getbalance(self, address: str) -> Decimal: '''Returns current balance of given address.''' try: return Decimal(cast(float, self.ext_fetch('getbalance/' + address))) except TypeError: return Decimal(0)
[ "def", "getbalance", "(", "self", ",", "address", ":", "str", ")", "->", "Decimal", ":", "try", ":", "return", "Decimal", "(", "cast", "(", "float", ",", "self", ".", "ext_fetch", "(", "'getbalance/'", "+", "address", ")", ")", ")", "except", "TypeErro...
Returns current balance of given address.
[ "Returns", "current", "balance", "of", "given", "address", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/explorer.py#L146-L152
train
Returns current balance of given address.
LISE-B26/pylabcontrol
build/lib/scripts/script_wait.py
Wait._function
def _function(self): """ Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click. """ start_time = datetime.datetime.now() # calculate stop time if self.settings['wait_mode'] == 'absolute': stop_time = start_time...
python
def _function(self): """ Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click. """ start_time = datetime.datetime.now() # calculate stop time if self.settings['wait_mode'] == 'absolute': stop_time = start_time...
[ "def", "_function", "(", "self", ")", ":", "start_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "# calculate stop time", "if", "self", ".", "settings", "[", "'wait_mode'", "]", "==", "'absolute'", ":", "stop_time", "=", "start_time", "+", ...
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
[ "Waits", "until", "stopped", "to", "keep", "script", "live", ".", "Gui", "must", "handle", "calling", "of", "Toggle_NV", "function", "on", "mouse", "click", "." ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/scripts/script_wait.py#L49-L86
train
Function that is called when the user clicks on a Toggle_NV button.
johnnoone/json-spec
src/jsonspec/pointer/bases.py
DocumentPointer.extract
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to pointer. It assums that document is the object. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ return self.pointer.extract(obj, bypass_ref)
python
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to pointer. It assums that document is the object. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ return self.pointer.extract(obj, bypass_ref)
[ "def", "extract", "(", "self", ",", "obj", ",", "bypass_ref", "=", "False", ")", ":", "return", "self", ".", "pointer", ".", "extract", "(", "obj", ",", "bypass_ref", ")" ]
Extract subelement from obj, according to pointer. It assums that document is the object. :param obj: the object source :param bypass_ref: disable JSON Reference errors
[ "Extract", "subelement", "from", "obj", "according", "to", "pointer", ".", "It", "assums", "that", "document", "is", "the", "object", "." ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L40-L48
train
Extract subelement from obj according to pointer.
johnnoone/json-spec
src/jsonspec/pointer/bases.py
Pointer.parse
def parse(self, pointer): """parse pointer into tokens""" if isinstance(pointer, Pointer): return pointer.tokens[:] elif pointer == '': return [] tokens = [] staged, _, children = pointer.partition('/') if staged: try: ...
python
def parse(self, pointer): """parse pointer into tokens""" if isinstance(pointer, Pointer): return pointer.tokens[:] elif pointer == '': return [] tokens = [] staged, _, children = pointer.partition('/') if staged: try: ...
[ "def", "parse", "(", "self", ",", "pointer", ")", ":", "if", "isinstance", "(", "pointer", ",", "Pointer", ")", ":", "return", "pointer", ".", "tokens", "[", ":", "]", "elif", "pointer", "==", "''", ":", "return", "[", "]", "tokens", "=", "[", "]",...
parse pointer into tokens
[ "parse", "pointer", "into", "tokens" ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L96-L121
train
parse pointer into tokens
johnnoone/json-spec
src/jsonspec/pointer/bases.py
Pointer.extract
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to tokens. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ for token in self.tokens: obj = token.extract(obj, bypass_ref) return ob...
python
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to tokens. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ for token in self.tokens: obj = token.extract(obj, bypass_ref) return ob...
[ "def", "extract", "(", "self", ",", "obj", ",", "bypass_ref", "=", "False", ")", ":", "for", "token", "in", "self", ".", "tokens", ":", "obj", "=", "token", ".", "extract", "(", "obj", ",", "bypass_ref", ")", "return", "obj" ]
Extract subelement from obj, according to tokens. :param obj: the object source :param bypass_ref: disable JSON Reference errors
[ "Extract", "subelement", "from", "obj", "according", "to", "tokens", "." ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L123-L132
train
Extracts the subelement from obj according to the tokens.
johnnoone/json-spec
src/jsonspec/pointer/bases.py
StagesToken.extract
def extract(self, obj, bypass_ref=False): """ Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used """ for i in range(0, self.stages): try: obj = obj.parent_obj except Attribu...
python
def extract(self, obj, bypass_ref=False): """ Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used """ for i in range(0, self.stages): try: obj = obj.parent_obj except Attribu...
[ "def", "extract", "(", "self", ",", "obj", ",", "bypass_ref", "=", "False", ")", ":", "for", "i", "in", "range", "(", "0", ",", "self", ".", "stages", ")", ":", "try", ":", "obj", "=", "obj", ".", "parent_obj", "except", "AttributeError", ":", "rai...
Extract parent of obj, according to current token. :param obj: the object source :param bypass_ref: not used
[ "Extract", "parent", "of", "obj", "according", "to", "current", "token", "." ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L190-L205
train
Extract parent of the object according to current token.
johnnoone/json-spec
src/jsonspec/pointer/bases.py
ChildToken.extract
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to current token. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ try: if isinstance(obj, Mapping): if not bypass_ref and '...
python
def extract(self, obj, bypass_ref=False): """ Extract subelement from obj, according to current token. :param obj: the object source :param bypass_ref: disable JSON Reference errors """ try: if isinstance(obj, Mapping): if not bypass_ref and '...
[ "def", "extract", "(", "self", ",", "obj", ",", "bypass_ref", "=", "False", ")", ":", "try", ":", "if", "isinstance", "(", "obj", ",", "Mapping", ")", ":", "if", "not", "bypass_ref", "and", "'$ref'", "in", "obj", ":", "raise", "RefError", "(", "obj",...
Extract subelement from obj, according to current token. :param obj: the object source :param bypass_ref: disable JSON Reference errors
[ "Extract", "subelement", "from", "obj", "according", "to", "current", "token", "." ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/bases.py#L212-L240
train
Extracts the subelement of obj according to current token.
samstav/requests-chef
requests_chef/mixlib_auth.py
digester
def digester(data): """Create SHA-1 hash, get digest, b64 encode, split every 60 char.""" if not isinstance(data, six.binary_type): data = data.encode('utf_8') hashof = hashlib.sha1(data).digest() encoded_hash = base64.b64encode(hashof) if not isinstance(encoded_hash, six.string_types): ...
python
def digester(data): """Create SHA-1 hash, get digest, b64 encode, split every 60 char.""" if not isinstance(data, six.binary_type): data = data.encode('utf_8') hashof = hashlib.sha1(data).digest() encoded_hash = base64.b64encode(hashof) if not isinstance(encoded_hash, six.string_types): ...
[ "def", "digester", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "six", ".", "binary_type", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf_8'", ")", "hashof", "=", "hashlib", ".", "sha1", "(", "data", ")", ".", "dige...
Create SHA-1 hash, get digest, b64 encode, split every 60 char.
[ "Create", "SHA", "-", "1", "hash", "get", "digest", "b64", "encode", "split", "every", "60", "char", "." ]
a0bf013b925abd0cf76eeaf6300cf32659632773
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L38-L48
train
Create SHA - 1 hash get digest b64 encode split every 60 char.
samstav/requests-chef
requests_chef/mixlib_auth.py
normpath
def normpath(path): """Normalize a path. Expands ~'s, resolves relative paths, normalizes and returns an absolute path. """ return os.path.abspath(os.path.normpath(os.path.expanduser(path)))
python
def normpath(path): """Normalize a path. Expands ~'s, resolves relative paths, normalizes and returns an absolute path. """ return os.path.abspath(os.path.normpath(os.path.expanduser(path)))
[ "def", "normpath", "(", "path", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", ")" ]
Normalize a path. Expands ~'s, resolves relative paths, normalizes and returns an absolute path.
[ "Normalize", "a", "path", "." ]
a0bf013b925abd0cf76eeaf6300cf32659632773
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L51-L57
train
Normalizes a path. Expands ~ s resolves relative paths normalizes and returns an absolute path.
samstav/requests-chef
requests_chef/mixlib_auth.py
splitter
def splitter(iterable, chunksize=60): """Split an iterable that supports indexing into chunks of 'chunksize'.""" return (iterable[0+i:chunksize+i] for i in range(0, len(iterable), chunksize))
python
def splitter(iterable, chunksize=60): """Split an iterable that supports indexing into chunks of 'chunksize'.""" return (iterable[0+i:chunksize+i] for i in range(0, len(iterable), chunksize))
[ "def", "splitter", "(", "iterable", ",", "chunksize", "=", "60", ")", ":", "return", "(", "iterable", "[", "0", "+", "i", ":", "chunksize", "+", "i", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "iterable", ")", ",", "chunksize", ")...
Split an iterable that supports indexing into chunks of 'chunksize'.
[ "Split", "an", "iterable", "that", "supports", "indexing", "into", "chunks", "of", "chunksize", "." ]
a0bf013b925abd0cf76eeaf6300cf32659632773
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L60-L63
train
Split an iterable that supports indexing into chunks of chunksize.
samstav/requests-chef
requests_chef/mixlib_auth.py
ChefAuth.canonical_request
def canonical_request(self, method, path, content, timestamp): """Return the canonical request string.""" request = collections.OrderedDict([ ('Method', method.upper()), ('Hashed Path', path), ('X-Ops-Content-Hash', content), ('X-Ops-Timestamp', timestamp)...
python
def canonical_request(self, method, path, content, timestamp): """Return the canonical request string.""" request = collections.OrderedDict([ ('Method', method.upper()), ('Hashed Path', path), ('X-Ops-Content-Hash', content), ('X-Ops-Timestamp', timestamp)...
[ "def", "canonical_request", "(", "self", ",", "method", ",", "path", ",", "content", ",", "timestamp", ")", ":", "request", "=", "collections", ".", "OrderedDict", "(", "[", "(", "'Method'", ",", "method", ".", "upper", "(", ")", ")", ",", "(", "'Hashe...
Return the canonical request string.
[ "Return", "the", "canonical", "request", "string", "." ]
a0bf013b925abd0cf76eeaf6300cf32659632773
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L127-L137
train
Return the canonical request string.
samstav/requests-chef
requests_chef/mixlib_auth.py
RSAKey.load_pem
def load_pem(cls, private_key, password=None): """Return a PrivateKey instance. :param private_key: Private key string (PEM format) or the path to a local private key file. """ # TODO(sam): try to break this in tests maybe_path = normpath(private_key)...
python
def load_pem(cls, private_key, password=None): """Return a PrivateKey instance. :param private_key: Private key string (PEM format) or the path to a local private key file. """ # TODO(sam): try to break this in tests maybe_path = normpath(private_key)...
[ "def", "load_pem", "(", "cls", ",", "private_key", ",", "password", "=", "None", ")", ":", "# TODO(sam): try to break this in tests", "maybe_path", "=", "normpath", "(", "private_key", ")", "if", "os", ".", "path", ".", "isfile", "(", "maybe_path", ")", ":", ...
Return a PrivateKey instance. :param private_key: Private key string (PEM format) or the path to a local private key file.
[ "Return", "a", "PrivateKey", "instance", "." ]
a0bf013b925abd0cf76eeaf6300cf32659632773
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L159-L177
train
Load a PrivateKey instance from a PEM - formatted private key file.
samstav/requests-chef
requests_chef/mixlib_auth.py
RSAKey.sign
def sign(self, data, b64=True): """Sign data with the private key and return the signed data. The signed data will be Base64 encoded if b64 is True. """ padder = padding.PKCS1v15() signer = self.private_key.signer(padder, None) if not isinstance(data, six.binary_type): ...
python
def sign(self, data, b64=True): """Sign data with the private key and return the signed data. The signed data will be Base64 encoded if b64 is True. """ padder = padding.PKCS1v15() signer = self.private_key.signer(padder, None) if not isinstance(data, six.binary_type): ...
[ "def", "sign", "(", "self", ",", "data", ",", "b64", "=", "True", ")", ":", "padder", "=", "padding", ".", "PKCS1v15", "(", ")", "signer", "=", "self", ".", "private_key", ".", "signer", "(", "padder", ",", "None", ")", "if", "not", "isinstance", "...
Sign data with the private key and return the signed data. The signed data will be Base64 encoded if b64 is True.
[ "Sign", "data", "with", "the", "private", "key", "and", "return", "the", "signed", "data", "." ]
a0bf013b925abd0cf76eeaf6300cf32659632773
https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L179-L192
train
Sign data with the private key and return the signed data.