repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dshean/pygeotools | pygeotools/lib/warplib.py | parse_res | def parse_res(res, src_ds_list=None, t_srs=None):
"""Parse arbitrary input res
Parameters
----------
res : str or gdal.Dataset or filename or float
Arbitrary input res
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first' or 'last'
t_srs : osr.SpatialReference() object
Projection for res calculations, optional
Returns
-------
res : float
Output resolution
None if source resolution should be preserved
"""
#Default to using first t_srs for res calculations
#Assumes src_ds_list is not None
t_srs = parse_srs(t_srs, src_ds_list)
#Valid options for res
res_str_list = ['first', 'last', 'min', 'max', 'mean', 'med', 'common_scale_factor']
#Compute output resolution in t_srs
if res in res_str_list and src_ds_list is not None:
#Returns min, max, mean, med
res_stats = geolib.get_res_stats(src_ds_list, t_srs=t_srs)
if res == 'first':
res = geolib.get_res(src_ds_list[0], t_srs=t_srs, square=True)[0]
elif res == 'last':
res = geolib.get_res(src_ds_list[-1], t_srs=t_srs, square=True)[0]
elif res == 'min':
res = res_stats[0]
elif res == 'max':
res = res_stats[1]
elif res == 'mean':
res = res_stats[2]
elif res == 'med':
res = res_stats[3]
elif res == 'common_scale_factor':
#Determine res to upsample min and downsample max by constant factor
res = np.sqrt(res_stats[1]/res_stats[0]) * res_stats[0]
elif res == 'source':
res = None
elif isinstance(res, gdal.Dataset):
res = geolib.get_res(res, t_srs=t_srs, square=True)[0]
elif isinstance(res, str) and os.path.exists(res):
res = geolib.get_res(gdal.Open(res), t_srs=t_srs, square=True)[0]
else:
res = float(res)
return res | python | def parse_res(res, src_ds_list=None, t_srs=None):
"""Parse arbitrary input res
Parameters
----------
res : str or gdal.Dataset or filename or float
Arbitrary input res
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first' or 'last'
t_srs : osr.SpatialReference() object
Projection for res calculations, optional
Returns
-------
res : float
Output resolution
None if source resolution should be preserved
"""
#Default to using first t_srs for res calculations
#Assumes src_ds_list is not None
t_srs = parse_srs(t_srs, src_ds_list)
#Valid options for res
res_str_list = ['first', 'last', 'min', 'max', 'mean', 'med', 'common_scale_factor']
#Compute output resolution in t_srs
if res in res_str_list and src_ds_list is not None:
#Returns min, max, mean, med
res_stats = geolib.get_res_stats(src_ds_list, t_srs=t_srs)
if res == 'first':
res = geolib.get_res(src_ds_list[0], t_srs=t_srs, square=True)[0]
elif res == 'last':
res = geolib.get_res(src_ds_list[-1], t_srs=t_srs, square=True)[0]
elif res == 'min':
res = res_stats[0]
elif res == 'max':
res = res_stats[1]
elif res == 'mean':
res = res_stats[2]
elif res == 'med':
res = res_stats[3]
elif res == 'common_scale_factor':
#Determine res to upsample min and downsample max by constant factor
res = np.sqrt(res_stats[1]/res_stats[0]) * res_stats[0]
elif res == 'source':
res = None
elif isinstance(res, gdal.Dataset):
res = geolib.get_res(res, t_srs=t_srs, square=True)[0]
elif isinstance(res, str) and os.path.exists(res):
res = geolib.get_res(gdal.Open(res), t_srs=t_srs, square=True)[0]
else:
res = float(res)
return res | [
"def",
"parse_res",
"(",
"res",
",",
"src_ds_list",
"=",
"None",
",",
"t_srs",
"=",
"None",
")",
":",
"#Default to using first t_srs for res calculations",
"#Assumes src_ds_list is not None",
"t_srs",
"=",
"parse_srs",
"(",
"t_srs",
",",
"src_ds_list",
")",
"#Valid op... | Parse arbitrary input res
Parameters
----------
res : str or gdal.Dataset or filename or float
Arbitrary input res
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first' or 'last'
t_srs : osr.SpatialReference() object
Projection for res calculations, optional
Returns
-------
res : float
Output resolution
None if source resolution should be preserved | [
"Parse",
"arbitrary",
"input",
"res"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L307-L359 | train | 213,100 |
dshean/pygeotools | pygeotools/lib/warplib.py | parse_extent | def parse_extent(extent, src_ds_list=None, t_srs=None):
"""Parse arbitrary input extent
Parameters
----------
extent : str or gdal.Dataset or filename or list of float
Arbitrary input extent
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first', 'last', 'intersection', or 'union'
t_srs : osr.SpatialReference() object, optional
Projection for res calculations
Returns
-------
extent : list of float
Output extent [xmin, ymin, xmax, ymax]
None if source extent should be preserved
"""
#Default to using first t_srs for extent calculations
if t_srs is not None:
t_srs = parse_srs(t_srs, src_ds_list)
#Valid strings
extent_str_list = ['first', 'last', 'intersection', 'union']
if extent in extent_str_list and src_ds_list is not None:
if len(src_ds_list) == 1 and (extent == 'intersection' or extent == 'union'):
extent = None
elif extent == 'first':
extent = geolib.ds_geom_extent(src_ds_list[0], t_srs=t_srs)
#extent = geolib.ds_extent(src_ds_list[0], t_srs=t_srs)
elif extent == 'last':
extent = geolib.ds_geom_extent(src_ds_list[-1], t_srs=t_srs)
#extent = geolib.ds_extent(src_ds_list[-1], t_srs=t_srs)
elif extent == 'intersection':
#By default, compute_intersection takes ref_srs from ref_ds
extent = geolib.ds_geom_intersection_extent(src_ds_list, t_srs=t_srs)
if len(src_ds_list) > 1 and extent is None:
sys.exit("Input images do not intersect")
elif extent == 'union':
#Need to clean up union t_srs handling
extent = geolib.ds_geom_union_extent(src_ds_list, t_srs=t_srs)
elif extent == 'source':
extent = None
elif isinstance(extent, gdal.Dataset):
extent = geolib.ds_geom_extent(extent, t_srs=t_srs)
elif isinstance(extent, str) and os.path.exists(extent):
extent = geolib.ds_geom_extent(gdal.Open(extent), t_srs=t_srs)
elif isinstance(extent, (list, tuple, np.ndarray)):
extent = list(extent)
else:
extent = [float(i) for i in extent.split(' ')]
return extent | python | def parse_extent(extent, src_ds_list=None, t_srs=None):
"""Parse arbitrary input extent
Parameters
----------
extent : str or gdal.Dataset or filename or list of float
Arbitrary input extent
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first', 'last', 'intersection', or 'union'
t_srs : osr.SpatialReference() object, optional
Projection for res calculations
Returns
-------
extent : list of float
Output extent [xmin, ymin, xmax, ymax]
None if source extent should be preserved
"""
#Default to using first t_srs for extent calculations
if t_srs is not None:
t_srs = parse_srs(t_srs, src_ds_list)
#Valid strings
extent_str_list = ['first', 'last', 'intersection', 'union']
if extent in extent_str_list and src_ds_list is not None:
if len(src_ds_list) == 1 and (extent == 'intersection' or extent == 'union'):
extent = None
elif extent == 'first':
extent = geolib.ds_geom_extent(src_ds_list[0], t_srs=t_srs)
#extent = geolib.ds_extent(src_ds_list[0], t_srs=t_srs)
elif extent == 'last':
extent = geolib.ds_geom_extent(src_ds_list[-1], t_srs=t_srs)
#extent = geolib.ds_extent(src_ds_list[-1], t_srs=t_srs)
elif extent == 'intersection':
#By default, compute_intersection takes ref_srs from ref_ds
extent = geolib.ds_geom_intersection_extent(src_ds_list, t_srs=t_srs)
if len(src_ds_list) > 1 and extent is None:
sys.exit("Input images do not intersect")
elif extent == 'union':
#Need to clean up union t_srs handling
extent = geolib.ds_geom_union_extent(src_ds_list, t_srs=t_srs)
elif extent == 'source':
extent = None
elif isinstance(extent, gdal.Dataset):
extent = geolib.ds_geom_extent(extent, t_srs=t_srs)
elif isinstance(extent, str) and os.path.exists(extent):
extent = geolib.ds_geom_extent(gdal.Open(extent), t_srs=t_srs)
elif isinstance(extent, (list, tuple, np.ndarray)):
extent = list(extent)
else:
extent = [float(i) for i in extent.split(' ')]
return extent | [
"def",
"parse_extent",
"(",
"extent",
",",
"src_ds_list",
"=",
"None",
",",
"t_srs",
"=",
"None",
")",
":",
"#Default to using first t_srs for extent calculations",
"if",
"t_srs",
"is",
"not",
"None",
":",
"t_srs",
"=",
"parse_srs",
"(",
"t_srs",
",",
"src_ds_li... | Parse arbitrary input extent
Parameters
----------
extent : str or gdal.Dataset or filename or list of float
Arbitrary input extent
src_ds_list : list of gdal.Dataset objects, optional
Needed if specifying 'first', 'last', 'intersection', or 'union'
t_srs : osr.SpatialReference() object, optional
Projection for res calculations
Returns
-------
extent : list of float
Output extent [xmin, ymin, xmax, ymax]
None if source extent should be preserved | [
"Parse",
"arbitrary",
"input",
"extent"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L361-L414 | train | 213,101 |
dshean/pygeotools | pygeotools/lib/warplib.py | memwarp_multi | def memwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0):
"""Helper function for memwarp of multiple input GDAL Datasets
"""
return warp_multi(src_ds_list, res, extent, t_srs, r, warptype=memwarp, verbose=verbose, dst_ndv=dst_ndv) | python | def memwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0):
"""Helper function for memwarp of multiple input GDAL Datasets
"""
return warp_multi(src_ds_list, res, extent, t_srs, r, warptype=memwarp, verbose=verbose, dst_ndv=dst_ndv) | [
"def",
"memwarp_multi",
"(",
"src_ds_list",
",",
"res",
"=",
"'first'",
",",
"extent",
"=",
"'intersection'",
",",
"t_srs",
"=",
"'first'",
",",
"r",
"=",
"'cubic'",
",",
"verbose",
"=",
"True",
",",
"dst_ndv",
"=",
"0",
")",
":",
"return",
"warp_multi",... | Helper function for memwarp of multiple input GDAL Datasets | [
"Helper",
"function",
"for",
"memwarp",
"of",
"multiple",
"input",
"GDAL",
"Datasets"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L517-L520 | train | 213,102 |
dshean/pygeotools | pygeotools/lib/warplib.py | memwarp_multi_fn | def memwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0):
"""Helper function for memwarp of multiple input filenames
"""
#Should implement proper error handling here
if not iolib.fn_list_check(src_fn_list):
sys.exit('Missing input file(s)')
src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list]
return memwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, dst_ndv=dst_ndv) | python | def memwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, dst_ndv=0):
"""Helper function for memwarp of multiple input filenames
"""
#Should implement proper error handling here
if not iolib.fn_list_check(src_fn_list):
sys.exit('Missing input file(s)')
src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list]
return memwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, dst_ndv=dst_ndv) | [
"def",
"memwarp_multi_fn",
"(",
"src_fn_list",
",",
"res",
"=",
"'first'",
",",
"extent",
"=",
"'intersection'",
",",
"t_srs",
"=",
"'first'",
",",
"r",
"=",
"'cubic'",
",",
"verbose",
"=",
"True",
",",
"dst_ndv",
"=",
"0",
")",
":",
"#Should implement pro... | Helper function for memwarp of multiple input filenames | [
"Helper",
"function",
"for",
"memwarp",
"of",
"multiple",
"input",
"filenames"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L522-L529 | train | 213,103 |
dshean/pygeotools | pygeotools/lib/warplib.py | diskwarp_multi | def diskwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None):
"""Helper function for diskwarp of multiple input GDAL Datasets
"""
return warp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, warptype=diskwarp, outdir=outdir, dst_ndv=dst_ndv) | python | def diskwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None):
"""Helper function for diskwarp of multiple input GDAL Datasets
"""
return warp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, warptype=diskwarp, outdir=outdir, dst_ndv=dst_ndv) | [
"def",
"diskwarp_multi",
"(",
"src_ds_list",
",",
"res",
"=",
"'first'",
",",
"extent",
"=",
"'intersection'",
",",
"t_srs",
"=",
"'first'",
",",
"r",
"=",
"'cubic'",
",",
"verbose",
"=",
"True",
",",
"outdir",
"=",
"None",
",",
"dst_ndv",
"=",
"None",
... | Helper function for diskwarp of multiple input GDAL Datasets | [
"Helper",
"function",
"for",
"diskwarp",
"of",
"multiple",
"input",
"GDAL",
"Datasets"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L531-L534 | train | 213,104 |
dshean/pygeotools | pygeotools/lib/warplib.py | diskwarp_multi_fn | def diskwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None):
"""Helper function for diskwarp of multiple input filenames
"""
#Should implement proper error handling here
if not iolib.fn_list_check(src_fn_list):
sys.exit('Missing input file(s)')
src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list]
return diskwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, outdir=outdir, dst_ndv=dst_ndv) | python | def diskwarp_multi_fn(src_fn_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None):
"""Helper function for diskwarp of multiple input filenames
"""
#Should implement proper error handling here
if not iolib.fn_list_check(src_fn_list):
sys.exit('Missing input file(s)')
src_ds_list = [gdal.Open(fn, gdal.GA_ReadOnly) for fn in src_fn_list]
return diskwarp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, outdir=outdir, dst_ndv=dst_ndv) | [
"def",
"diskwarp_multi_fn",
"(",
"src_fn_list",
",",
"res",
"=",
"'first'",
",",
"extent",
"=",
"'intersection'",
",",
"t_srs",
"=",
"'first'",
",",
"r",
"=",
"'cubic'",
",",
"verbose",
"=",
"True",
",",
"outdir",
"=",
"None",
",",
"dst_ndv",
"=",
"None"... | Helper function for diskwarp of multiple input filenames | [
"Helper",
"function",
"for",
"diskwarp",
"of",
"multiple",
"input",
"filenames"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L536-L543 | train | 213,105 |
dshean/pygeotools | pygeotools/lib/warplib.py | writeout | def writeout(ds, outfn):
"""Write ds to disk
Note: Depreciated function - use diskwarp functions when writing to disk to avoid unnecessary CreateCopy
"""
print("Writing out %s" % outfn)
#Use outfn extension to get driver
#This may have issues if outfn already exists and the mem ds has different dimensions/res
out_ds = iolib.gtif_drv.CreateCopy(outfn, ds, 0, options=iolib.gdal_opt)
out_ds = None | python | def writeout(ds, outfn):
"""Write ds to disk
Note: Depreciated function - use diskwarp functions when writing to disk to avoid unnecessary CreateCopy
"""
print("Writing out %s" % outfn)
#Use outfn extension to get driver
#This may have issues if outfn already exists and the mem ds has different dimensions/res
out_ds = iolib.gtif_drv.CreateCopy(outfn, ds, 0, options=iolib.gdal_opt)
out_ds = None | [
"def",
"writeout",
"(",
"ds",
",",
"outfn",
")",
":",
"print",
"(",
"\"Writing out %s\"",
"%",
"outfn",
")",
"#Use outfn extension to get driver",
"#This may have issues if outfn already exists and the mem ds has different dimensions/res",
"out_ds",
"=",
"iolib",
".",
"gtif_d... | Write ds to disk
Note: Depreciated function - use diskwarp functions when writing to disk to avoid unnecessary CreateCopy | [
"Write",
"ds",
"to",
"disk"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/warplib.py#L545-L555 | train | 213,106 |
dshean/pygeotools | pygeotools/lib/timelib.py | getLocalTime | def getLocalTime(utc_dt, tz):
"""Return local timezone time
"""
import pytz
local_tz = pytz.timezone(tz)
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_dt | python | def getLocalTime(utc_dt, tz):
"""Return local timezone time
"""
import pytz
local_tz = pytz.timezone(tz)
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_dt | [
"def",
"getLocalTime",
"(",
"utc_dt",
",",
"tz",
")",
":",
"import",
"pytz",
"local_tz",
"=",
"pytz",
".",
"timezone",
"(",
"tz",
")",
"local_dt",
"=",
"utc_dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
".",
"astimezone",
"(",
"lo... | Return local timezone time | [
"Return",
"local",
"timezone",
"time"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L37-L43 | train | 213,107 |
dshean/pygeotools | pygeotools/lib/timelib.py | strptime_fuzzy | def strptime_fuzzy(s):
"""Fuzzy date string parsing
Note: this returns current date if not found. If only year is provided, will return current month, day
"""
import dateutil.parser
dt = dateutil.parser.parse(str(s), fuzzy=True)
return dt | python | def strptime_fuzzy(s):
"""Fuzzy date string parsing
Note: this returns current date if not found. If only year is provided, will return current month, day
"""
import dateutil.parser
dt = dateutil.parser.parse(str(s), fuzzy=True)
return dt | [
"def",
"strptime_fuzzy",
"(",
"s",
")",
":",
"import",
"dateutil",
".",
"parser",
"dt",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"str",
"(",
"s",
")",
",",
"fuzzy",
"=",
"True",
")",
"return",
"dt"
] | Fuzzy date string parsing
Note: this returns current date if not found. If only year is provided, will return current month, day | [
"Fuzzy",
"date",
"string",
"parsing"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L68-L75 | train | 213,108 |
dshean/pygeotools | pygeotools/lib/timelib.py | fn_getdatetime_list | def fn_getdatetime_list(fn):
"""Extract all datetime strings from input filename
"""
#Want to split last component
fn = os.path.split(os.path.splitext(fn)[0])[-1]
import re
#WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif
#Need to parse above with month name
#Note: made this more restrictive to avoid false matches:
#'20130304_1510_1030010020770600_1030010020CEAB00-DEM_4x'
#This is a problem, b/c 2015/17/00:
#WV02_20130315_10300100207D5600_1030010020151700
#This code should be obsolete before 2019
#Assume new filenames
#fn = fn[0:13]
#Use cascading re find to pull out timestamps
#Note: Want to be less restrictive here - could have a mix of YYYYMMDD_HHMM, YYYYMMDD and YYYY in filename
#Should probably search for all possibilities, then prune
#NOTE: these don't include seconds in the time
#NOTE: could have 20130304_1510__20130304__whatever in filename
#The current approach will only catch the first datetime
dstr = None
out = None
#20180101_1200 or 20180101T1200
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])[_T](?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]', fn)
#201801011200
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]', fn)
#20180101
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:$|_|-)', fn)
#This should pick up dates separated by a dash
#dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])', fn)
#2018.609990
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9]\.[0-9][0-9][0-9]*(?:$|_|-)', fn)
dstr = [d.lstrip('_').rstrip('_') for d in dstr]
dstr = [d.lstrip('-').rstrip('-') for d in dstr]
out = [decyear2dt(float(s)) for s in dstr]
dstr = None
#2018
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:$|_|-)', fn)
#This is for USGS archive filenames
if not dstr:
dstr = re.findall(r'[0-3][0-9][a-z][a-z][a-z][0-9][0-9]', fn)
#This is USGS archive format
if dstr:
out = [datetime.strptime(s, '%d%b%y') for s in dstr][0]
dstr = None
if dstr:
#This is a hack to remove peripheral underscores and dashes
dstr = [d.lstrip('_').rstrip('_') for d in dstr]
dstr = [d.lstrip('-').rstrip('-') for d in dstr]
#This returns an empty list of nothing is found
out = [strptime_fuzzy(s) for s in dstr]
return out | python | def fn_getdatetime_list(fn):
"""Extract all datetime strings from input filename
"""
#Want to split last component
fn = os.path.split(os.path.splitext(fn)[0])[-1]
import re
#WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif
#Need to parse above with month name
#Note: made this more restrictive to avoid false matches:
#'20130304_1510_1030010020770600_1030010020CEAB00-DEM_4x'
#This is a problem, b/c 2015/17/00:
#WV02_20130315_10300100207D5600_1030010020151700
#This code should be obsolete before 2019
#Assume new filenames
#fn = fn[0:13]
#Use cascading re find to pull out timestamps
#Note: Want to be less restrictive here - could have a mix of YYYYMMDD_HHMM, YYYYMMDD and YYYY in filename
#Should probably search for all possibilities, then prune
#NOTE: these don't include seconds in the time
#NOTE: could have 20130304_1510__20130304__whatever in filename
#The current approach will only catch the first datetime
dstr = None
out = None
#20180101_1200 or 20180101T1200
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])[_T](?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]', fn)
#201801011200
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]', fn)
#20180101
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:$|_|-)', fn)
#This should pick up dates separated by a dash
#dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])', fn)
#2018.609990
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9]\.[0-9][0-9][0-9]*(?:$|_|-)', fn)
dstr = [d.lstrip('_').rstrip('_') for d in dstr]
dstr = [d.lstrip('-').rstrip('-') for d in dstr]
out = [decyear2dt(float(s)) for s in dstr]
dstr = None
#2018
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:$|_|-)', fn)
#This is for USGS archive filenames
if not dstr:
dstr = re.findall(r'[0-3][0-9][a-z][a-z][a-z][0-9][0-9]', fn)
#This is USGS archive format
if dstr:
out = [datetime.strptime(s, '%d%b%y') for s in dstr][0]
dstr = None
if dstr:
#This is a hack to remove peripheral underscores and dashes
dstr = [d.lstrip('_').rstrip('_') for d in dstr]
dstr = [d.lstrip('-').rstrip('-') for d in dstr]
#This returns an empty list of nothing is found
out = [strptime_fuzzy(s) for s in dstr]
return out | [
"def",
"fn_getdatetime_list",
"(",
"fn",
")",
":",
"#Want to split last component",
"fn",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"fn",
")",
"[",
"0",
"]",
")",
"[",
"-",
"1",
"]",
"import",
"re",
"#WV01_12... | Extract all datetime strings from input filename | [
"Extract",
"all",
"datetime",
"strings",
"from",
"input",
"filename"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L87-L143 | train | 213,109 |
dshean/pygeotools | pygeotools/lib/timelib.py | get_t_factor | def get_t_factor(t1, t2):
"""Time difference between two datetimes, expressed as decimal year
"""
t_factor = None
if t1 is not None and t2 is not None and t1 != t2:
dt = t2 - t1
year = timedelta(days=365.25)
t_factor = abs(dt.total_seconds() / year.total_seconds())
return t_factor | python | def get_t_factor(t1, t2):
"""Time difference between two datetimes, expressed as decimal year
"""
t_factor = None
if t1 is not None and t2 is not None and t1 != t2:
dt = t2 - t1
year = timedelta(days=365.25)
t_factor = abs(dt.total_seconds() / year.total_seconds())
return t_factor | [
"def",
"get_t_factor",
"(",
"t1",
",",
"t2",
")",
":",
"t_factor",
"=",
"None",
"if",
"t1",
"is",
"not",
"None",
"and",
"t2",
"is",
"not",
"None",
"and",
"t1",
"!=",
"t2",
":",
"dt",
"=",
"t2",
"-",
"t1",
"year",
"=",
"timedelta",
"(",
"days",
... | Time difference between two datetimes, expressed as decimal year | [
"Time",
"difference",
"between",
"two",
"datetimes",
"expressed",
"as",
"decimal",
"year"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L145-L153 | train | 213,110 |
dshean/pygeotools | pygeotools/lib/timelib.py | sort_fn_list | def sort_fn_list(fn_list):
"""Sort input filename list by datetime
"""
dt_list = get_dt_list(fn_list)
fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]
return fn_list_sort | python | def sort_fn_list(fn_list):
"""Sort input filename list by datetime
"""
dt_list = get_dt_list(fn_list)
fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]
return fn_list_sort | [
"def",
"sort_fn_list",
"(",
"fn_list",
")",
":",
"dt_list",
"=",
"get_dt_list",
"(",
"fn_list",
")",
"fn_list_sort",
"=",
"[",
"fn",
"for",
"(",
"dt",
",",
"fn",
")",
"in",
"sorted",
"(",
"zip",
"(",
"dt_list",
",",
"fn_list",
")",
")",
"]",
"return"... | Sort input filename list by datetime | [
"Sort",
"input",
"filename",
"list",
"by",
"datetime"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L176-L181 | train | 213,111 |
dshean/pygeotools | pygeotools/lib/timelib.py | fix_repeat_dt | def fix_repeat_dt(dt_list, offset_s=0.001):
"""Add some small offset to remove duplicate times
Needed for xarray interp, which expects monotonically increasing times
"""
idx = (np.diff(dt_list) == timedelta(0))
while np.any(idx):
dt_list[idx.nonzero()[0] + 1] += timedelta(seconds=offset_s)
idx = (np.diff(dt_list) == timedelta(0))
return dt_list | python | def fix_repeat_dt(dt_list, offset_s=0.001):
"""Add some small offset to remove duplicate times
Needed for xarray interp, which expects monotonically increasing times
"""
idx = (np.diff(dt_list) == timedelta(0))
while np.any(idx):
dt_list[idx.nonzero()[0] + 1] += timedelta(seconds=offset_s)
idx = (np.diff(dt_list) == timedelta(0))
return dt_list | [
"def",
"fix_repeat_dt",
"(",
"dt_list",
",",
"offset_s",
"=",
"0.001",
")",
":",
"idx",
"=",
"(",
"np",
".",
"diff",
"(",
"dt_list",
")",
"==",
"timedelta",
"(",
"0",
")",
")",
"while",
"np",
".",
"any",
"(",
"idx",
")",
":",
"dt_list",
"[",
"idx... | Add some small offset to remove duplicate times
Needed for xarray interp, which expects monotonically increasing times | [
"Add",
"some",
"small",
"offset",
"to",
"remove",
"duplicate",
"times",
"Needed",
"for",
"xarray",
"interp",
"which",
"expects",
"monotonically",
"increasing",
"times"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L183-L191 | train | 213,112 |
dshean/pygeotools | pygeotools/lib/timelib.py | get_dt_list | def get_dt_list(fn_list):
"""Get list of datetime objects, extracted from a filename
"""
dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])
return dt_list | python | def get_dt_list(fn_list):
"""Get list of datetime objects, extracted from a filename
"""
dt_list = np.array([fn_getdatetime(fn) for fn in fn_list])
return dt_list | [
"def",
"get_dt_list",
"(",
"fn_list",
")",
":",
"dt_list",
"=",
"np",
".",
"array",
"(",
"[",
"fn_getdatetime",
"(",
"fn",
")",
"for",
"fn",
"in",
"fn_list",
"]",
")",
"return",
"dt_list"
] | Get list of datetime objects, extracted from a filename | [
"Get",
"list",
"of",
"datetime",
"objects",
"extracted",
"from",
"a",
"filename"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L193-L197 | train | 213,113 |
dshean/pygeotools | pygeotools/lib/timelib.py | get_closest_dt_idx | def get_closest_dt_idx(dt, dt_list):
"""Get indices of dt_list that is closest to input dt
"""
from pygeotools.lib import malib
dt_list = malib.checkma(dt_list, fix=False)
dt_diff = np.abs(dt - dt_list)
return dt_diff.argmin() | python | def get_closest_dt_idx(dt, dt_list):
"""Get indices of dt_list that is closest to input dt
"""
from pygeotools.lib import malib
dt_list = malib.checkma(dt_list, fix=False)
dt_diff = np.abs(dt - dt_list)
return dt_diff.argmin() | [
"def",
"get_closest_dt_idx",
"(",
"dt",
",",
"dt_list",
")",
":",
"from",
"pygeotools",
".",
"lib",
"import",
"malib",
"dt_list",
"=",
"malib",
".",
"checkma",
"(",
"dt_list",
",",
"fix",
"=",
"False",
")",
"dt_diff",
"=",
"np",
".",
"abs",
"(",
"dt",
... | Get indices of dt_list that is closest to input dt | [
"Get",
"indices",
"of",
"dt_list",
"that",
"is",
"closest",
"to",
"input",
"dt"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L218-L224 | train | 213,114 |
dshean/pygeotools | pygeotools/lib/timelib.py | mean_date | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | python | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | [
"def",
"mean_date",
"(",
"dt_list",
")",
":",
"dt_list_sort",
"=",
"sorted",
"(",
"dt_list",
")",
"dt_list_sort_rel",
"=",
"[",
"dt",
"-",
"dt_list_sort",
"[",
"0",
"]",
"for",
"dt",
"in",
"dt_list_sort",
"]",
"avg_timedelta",
"=",
"sum",
"(",
"dt_list_sor... | Calcuate mean datetime from datetime list | [
"Calcuate",
"mean",
"datetime",
"from",
"datetime",
"list"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L365-L371 | train | 213,115 |
dshean/pygeotools | pygeotools/lib/timelib.py | median_date | def median_date(dt_list):
"""Calcuate median datetime from datetime list
"""
#dt_list_sort = sorted(dt_list)
idx = len(dt_list)/2
if len(dt_list) % 2 == 0:
md = mean_date([dt_list[idx-1], dt_list[idx]])
else:
md = dt_list[idx]
return md | python | def median_date(dt_list):
"""Calcuate median datetime from datetime list
"""
#dt_list_sort = sorted(dt_list)
idx = len(dt_list)/2
if len(dt_list) % 2 == 0:
md = mean_date([dt_list[idx-1], dt_list[idx]])
else:
md = dt_list[idx]
return md | [
"def",
"median_date",
"(",
"dt_list",
")",
":",
"#dt_list_sort = sorted(dt_list)",
"idx",
"=",
"len",
"(",
"dt_list",
")",
"/",
"2",
"if",
"len",
"(",
"dt_list",
")",
"%",
"2",
"==",
"0",
":",
"md",
"=",
"mean_date",
"(",
"[",
"dt_list",
"[",
"idx",
... | Calcuate median datetime from datetime list | [
"Calcuate",
"median",
"datetime",
"from",
"datetime",
"list"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L373-L382 | train | 213,116 |
dshean/pygeotools | pygeotools/lib/timelib.py | dt_cluster | def dt_cluster(dt_list, dt_thresh=16.0):
"""Find clusters of similar datetimes within datetime list
"""
if not isinstance(dt_list[0], float):
o_list = dt2o(dt_list)
else:
o_list = dt_list
o_list_sort = np.sort(o_list)
o_list_sort_idx = np.argsort(o_list)
d = np.diff(o_list_sort)
#These are indices of breaks
#Add one so each b starts a cluster
b = np.nonzero(d > dt_thresh)[0] + 1
#Add one to shape so we include final index
b = np.hstack((0, b, d.shape[0] + 1))
f_list = []
for i in range(len(b)-1):
#Need to subtract 1 here to give cluster bounds
b_idx = [b[i], b[i+1]-1]
b_dt = o_list_sort[b_idx]
#These should be identical if input is already sorted
b_idx_orig = o_list_sort_idx[b_idx]
all_idx = np.arange(b_idx[0], b_idx[1])
all_sort = o_list_sort[all_idx]
#These should be identical if input is already sorted
all_idx_orig = o_list_sort_idx[all_idx]
dict = {}
dict['break_indices'] = b_idx_orig
dict['break_ts_o'] = b_dt
dict['break_ts_dt'] = o2dt(b_dt)
dict['all_indices'] = all_idx_orig
dict['all_ts_o'] = all_sort
dict['all_ts_dt'] = o2dt(all_sort)
f_list.append(dict)
return f_list | python | def dt_cluster(dt_list, dt_thresh=16.0):
"""Find clusters of similar datetimes within datetime list
"""
if not isinstance(dt_list[0], float):
o_list = dt2o(dt_list)
else:
o_list = dt_list
o_list_sort = np.sort(o_list)
o_list_sort_idx = np.argsort(o_list)
d = np.diff(o_list_sort)
#These are indices of breaks
#Add one so each b starts a cluster
b = np.nonzero(d > dt_thresh)[0] + 1
#Add one to shape so we include final index
b = np.hstack((0, b, d.shape[0] + 1))
f_list = []
for i in range(len(b)-1):
#Need to subtract 1 here to give cluster bounds
b_idx = [b[i], b[i+1]-1]
b_dt = o_list_sort[b_idx]
#These should be identical if input is already sorted
b_idx_orig = o_list_sort_idx[b_idx]
all_idx = np.arange(b_idx[0], b_idx[1])
all_sort = o_list_sort[all_idx]
#These should be identical if input is already sorted
all_idx_orig = o_list_sort_idx[all_idx]
dict = {}
dict['break_indices'] = b_idx_orig
dict['break_ts_o'] = b_dt
dict['break_ts_dt'] = o2dt(b_dt)
dict['all_indices'] = all_idx_orig
dict['all_ts_o'] = all_sort
dict['all_ts_dt'] = o2dt(all_sort)
f_list.append(dict)
return f_list | [
"def",
"dt_cluster",
"(",
"dt_list",
",",
"dt_thresh",
"=",
"16.0",
")",
":",
"if",
"not",
"isinstance",
"(",
"dt_list",
"[",
"0",
"]",
",",
"float",
")",
":",
"o_list",
"=",
"dt2o",
"(",
"dt_list",
")",
"else",
":",
"o_list",
"=",
"dt_list",
"o_list... | Find clusters of similar datetimes within datetime list | [
"Find",
"clusters",
"of",
"similar",
"datetimes",
"within",
"datetime",
"list"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L421-L455 | train | 213,117 |
dshean/pygeotools | pygeotools/lib/timelib.py | dt2decyear | def dt2decyear(dt):
"""Convert datetime to decimal year
"""
year = dt.year
startOfThisYear = datetime(year=year, month=1, day=1)
startOfNextYear = datetime(year=year+1, month=1, day=1)
yearElapsed = sinceEpoch(dt) - sinceEpoch(startOfThisYear)
yearDuration = sinceEpoch(startOfNextYear) - sinceEpoch(startOfThisYear)
fraction = yearElapsed/yearDuration
return year + fraction | python | def dt2decyear(dt):
"""Convert datetime to decimal year
"""
year = dt.year
startOfThisYear = datetime(year=year, month=1, day=1)
startOfNextYear = datetime(year=year+1, month=1, day=1)
yearElapsed = sinceEpoch(dt) - sinceEpoch(startOfThisYear)
yearDuration = sinceEpoch(startOfNextYear) - sinceEpoch(startOfThisYear)
fraction = yearElapsed/yearDuration
return year + fraction | [
"def",
"dt2decyear",
"(",
"dt",
")",
":",
"year",
"=",
"dt",
".",
"year",
"startOfThisYear",
"=",
"datetime",
"(",
"year",
"=",
"year",
",",
"month",
"=",
"1",
",",
"day",
"=",
"1",
")",
"startOfNextYear",
"=",
"datetime",
"(",
"year",
"=",
"year",
... | Convert datetime to decimal year | [
"Convert",
"datetime",
"to",
"decimal",
"year"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L462-L471 | train | 213,118 |
dshean/pygeotools | pygeotools/lib/timelib.py | decyear2dt | def decyear2dt(t):
"""Convert decimal year to datetime
"""
year = int(t)
rem = t - year
base = datetime(year, 1, 1)
dt = base + timedelta(seconds=(base.replace(year=base.year+1) - base).total_seconds() * rem)
#This works for np array input
#year = t.astype(int)
#rem = t - year
#base = np.array([datetime(y, 1, 1) for y in year])
return dt | python | def decyear2dt(t):
"""Convert decimal year to datetime
"""
year = int(t)
rem = t - year
base = datetime(year, 1, 1)
dt = base + timedelta(seconds=(base.replace(year=base.year+1) - base).total_seconds() * rem)
#This works for np array input
#year = t.astype(int)
#rem = t - year
#base = np.array([datetime(y, 1, 1) for y in year])
return dt | [
"def",
"decyear2dt",
"(",
"t",
")",
":",
"year",
"=",
"int",
"(",
"t",
")",
"rem",
"=",
"t",
"-",
"year",
"base",
"=",
"datetime",
"(",
"year",
",",
"1",
",",
"1",
")",
"dt",
"=",
"base",
"+",
"timedelta",
"(",
"seconds",
"=",
"(",
"base",
".... | Convert decimal year to datetime | [
"Convert",
"decimal",
"year",
"to",
"datetime"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L473-L484 | train | 213,119 |
dshean/pygeotools | pygeotools/lib/timelib.py | dt2jd | def dt2jd(dt):
"""Convert datetime to julian date
"""
a = (14 - dt.month)//12
y = dt.year + 4800 - a
m = dt.month + 12*a - 3
return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045 | python | def dt2jd(dt):
"""Convert datetime to julian date
"""
a = (14 - dt.month)//12
y = dt.year + 4800 - a
m = dt.month + 12*a - 3
return dt.day + ((153*m + 2)//5) + 365*y + y//4 - y//100 + y//400 - 32045 | [
"def",
"dt2jd",
"(",
"dt",
")",
":",
"a",
"=",
"(",
"14",
"-",
"dt",
".",
"month",
")",
"//",
"12",
"y",
"=",
"dt",
".",
"year",
"+",
"4800",
"-",
"a",
"m",
"=",
"dt",
".",
"month",
"+",
"12",
"*",
"a",
"-",
"3",
"return",
"dt",
".",
"d... | Convert datetime to julian date | [
"Convert",
"datetime",
"to",
"julian",
"date"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L488-L494 | train | 213,120 |
dshean/pygeotools | pygeotools/lib/timelib.py | jd2dt | def jd2dt(jd):
"""Convert julian date to datetime
"""
n = int(round(float(jd)))
a = n + 32044
b = (4*a + 3)//146097
c = a - (146097*b)//4
d = (4*c + 3)//1461
e = c - (1461*d)//4
m = (5*e + 2)//153
day = e + 1 - (153*m + 2)//5
month = m + 3 - 12*(m//10)
year = 100*b + d - 4800 + m/10
tfrac = 0.5 + float(jd) - n
tfrac_s = 86400.0 * tfrac
minfrac, hours = np.modf(tfrac_s / 3600.)
secfrac, minutes = np.modf(minfrac * 60.)
microsec, seconds = np.modf(secfrac * 60.)
return datetime(year, month, day, int(hours), int(minutes), int(seconds), int(microsec*1E6)) | python | def jd2dt(jd):
"""Convert julian date to datetime
"""
n = int(round(float(jd)))
a = n + 32044
b = (4*a + 3)//146097
c = a - (146097*b)//4
d = (4*c + 3)//1461
e = c - (1461*d)//4
m = (5*e + 2)//153
day = e + 1 - (153*m + 2)//5
month = m + 3 - 12*(m//10)
year = 100*b + d - 4800 + m/10
tfrac = 0.5 + float(jd) - n
tfrac_s = 86400.0 * tfrac
minfrac, hours = np.modf(tfrac_s / 3600.)
secfrac, minutes = np.modf(minfrac * 60.)
microsec, seconds = np.modf(secfrac * 60.)
return datetime(year, month, day, int(hours), int(minutes), int(seconds), int(microsec*1E6)) | [
"def",
"jd2dt",
"(",
"jd",
")",
":",
"n",
"=",
"int",
"(",
"round",
"(",
"float",
"(",
"jd",
")",
")",
")",
"a",
"=",
"n",
"+",
"32044",
"b",
"=",
"(",
"4",
"*",
"a",
"+",
"3",
")",
"//",
"146097",
"c",
"=",
"a",
"-",
"(",
"146097",
"*"... | Convert julian date to datetime | [
"Convert",
"julian",
"date",
"to",
"datetime"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L496-L516 | train | 213,121 |
dshean/pygeotools | pygeotools/lib/timelib.py | gps2dt | def gps2dt(gps_week, gps_ms):
"""Convert GPS week and ms to a datetime
"""
gps_epoch = datetime(1980,1,6,0,0,0)
gps_week_s = timedelta(seconds=gps_week*7*24*60*60)
gps_ms_s = timedelta(milliseconds=gps_ms)
return gps_epoch + gps_week_s + gps_ms_s | python | def gps2dt(gps_week, gps_ms):
"""Convert GPS week and ms to a datetime
"""
gps_epoch = datetime(1980,1,6,0,0,0)
gps_week_s = timedelta(seconds=gps_week*7*24*60*60)
gps_ms_s = timedelta(milliseconds=gps_ms)
return gps_epoch + gps_week_s + gps_ms_s | [
"def",
"gps2dt",
"(",
"gps_week",
",",
"gps_ms",
")",
":",
"gps_epoch",
"=",
"datetime",
"(",
"1980",
",",
"1",
",",
"6",
",",
"0",
",",
"0",
",",
"0",
")",
"gps_week_s",
"=",
"timedelta",
"(",
"seconds",
"=",
"gps_week",
"*",
"7",
"*",
"24",
"*"... | Convert GPS week and ms to a datetime | [
"Convert",
"GPS",
"week",
"and",
"ms",
"to",
"a",
"datetime"
] | 5ac745717c0098d01eb293ff1fe32fd7358c76ab | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L519-L525 | train | 213,122 |
rocky/python-xdis | xdis/main.py | disco_loop | def disco_loop(opc, version, queue, real_out, dup_lines=False,
show_bytes=False):
"""Disassembles a queue of code objects. If we discover
another code object which will be found in co_consts, we add
the new code to the list. Note that the order of code discovery
is in the order of first encountered which is not amenable for
the format used by a disassembler where code objects should
be defined before using them in other functions.
However this is not recursive and will overall lead to less
memory consumption at run time.
"""
while len(queue) > 0:
co = queue.popleft()
if co.co_name not in ('<module>', '?'):
real_out.write("\n" + format_code_info(co, version) + "\n")
bytecode = Bytecode(co, opc, dup_lines=dup_lines)
real_out.write(bytecode.dis(show_bytes=show_bytes) + "\n")
for c in co.co_consts:
if iscode(c):
queue.append(c)
pass
pass | python | def disco_loop(opc, version, queue, real_out, dup_lines=False,
show_bytes=False):
"""Disassembles a queue of code objects. If we discover
another code object which will be found in co_consts, we add
the new code to the list. Note that the order of code discovery
is in the order of first encountered which is not amenable for
the format used by a disassembler where code objects should
be defined before using them in other functions.
However this is not recursive and will overall lead to less
memory consumption at run time.
"""
while len(queue) > 0:
co = queue.popleft()
if co.co_name not in ('<module>', '?'):
real_out.write("\n" + format_code_info(co, version) + "\n")
bytecode = Bytecode(co, opc, dup_lines=dup_lines)
real_out.write(bytecode.dis(show_bytes=show_bytes) + "\n")
for c in co.co_consts:
if iscode(c):
queue.append(c)
pass
pass | [
"def",
"disco_loop",
"(",
"opc",
",",
"version",
",",
"queue",
",",
"real_out",
",",
"dup_lines",
"=",
"False",
",",
"show_bytes",
"=",
"False",
")",
":",
"while",
"len",
"(",
"queue",
")",
">",
"0",
":",
"co",
"=",
"queue",
".",
"popleft",
"(",
")... | Disassembles a queue of code objects. If we discover
another code object which will be found in co_consts, we add
the new code to the list. Note that the order of code discovery
is in the order of first encountered which is not amenable for
the format used by a disassembler where code objects should
be defined before using them in other functions.
However this is not recursive and will overall lead to less
memory consumption at run time. | [
"Disassembles",
"a",
"queue",
"of",
"code",
"objects",
".",
"If",
"we",
"discover",
"another",
"code",
"object",
"which",
"will",
"be",
"found",
"in",
"co_consts",
"we",
"add",
"the",
"new",
"code",
"to",
"the",
"list",
".",
"Note",
"that",
"the",
"order... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/main.py#L127-L151 | train | 213,123 |
rocky/python-xdis | xdis/main.py | disco_loop_asm_format | def disco_loop_asm_format(opc, version, co, real_out,
fn_name_map, all_fns):
"""Produces disassembly in a format more conducive to
automatic assembly by producing inner modules before they are
used by outer ones. Since this is recusive, we'll
use more stack space at runtime.
"""
if version < 3.0:
co = code2compat(co)
else:
co = code3compat(co)
co_name = co.co_name
mapped_name = fn_name_map.get(co_name, co_name)
new_consts = []
for c in co.co_consts:
if iscode(c):
if version < 3.0:
c_compat = code2compat(c)
else:
c_compat = code3compat(c)
disco_loop_asm_format(opc, version, c_compat, real_out,
fn_name_map, all_fns)
m = re.match(".* object <(.+)> at", str(c))
if m:
basename = m.group(1)
if basename != 'module':
mapped_name = code_uniquify(basename, c.co_code)
c_compat.co_name = mapped_name
c_compat.freeze()
new_consts.append(c_compat)
else:
new_consts.append(c)
pass
co.co_consts = new_consts
m = re.match("^<(.+)>$", co.co_name)
if m or co_name in all_fns:
if co_name in all_fns:
basename = co_name
else:
basename = m.group(1)
if basename != 'module':
mapped_name = code_uniquify(basename, co.co_code)
co_name = mapped_name
assert mapped_name not in fn_name_map
fn_name_map[mapped_name] = basename
co.co_name = mapped_name
pass
elif co_name in fn_name_map:
# FIXME: better would be a hash of the co_code
mapped_name = code_uniquify(co_name, co.co_code)
fn_name_map[mapped_name] = co_name
co.co_name = mapped_name
pass
co = co.freeze()
all_fns.add(co_name)
if co.co_name != '<module>' or co.co_filename:
real_out.write("\n" + format_code_info(co, version, mapped_name) + "\n")
bytecode = Bytecode(co, opc, dup_lines=True)
real_out.write(bytecode.dis(asm_format=True) + "\n") | python | def disco_loop_asm_format(opc, version, co, real_out,
fn_name_map, all_fns):
"""Produces disassembly in a format more conducive to
automatic assembly by producing inner modules before they are
used by outer ones. Since this is recusive, we'll
use more stack space at runtime.
"""
if version < 3.0:
co = code2compat(co)
else:
co = code3compat(co)
co_name = co.co_name
mapped_name = fn_name_map.get(co_name, co_name)
new_consts = []
for c in co.co_consts:
if iscode(c):
if version < 3.0:
c_compat = code2compat(c)
else:
c_compat = code3compat(c)
disco_loop_asm_format(opc, version, c_compat, real_out,
fn_name_map, all_fns)
m = re.match(".* object <(.+)> at", str(c))
if m:
basename = m.group(1)
if basename != 'module':
mapped_name = code_uniquify(basename, c.co_code)
c_compat.co_name = mapped_name
c_compat.freeze()
new_consts.append(c_compat)
else:
new_consts.append(c)
pass
co.co_consts = new_consts
m = re.match("^<(.+)>$", co.co_name)
if m or co_name in all_fns:
if co_name in all_fns:
basename = co_name
else:
basename = m.group(1)
if basename != 'module':
mapped_name = code_uniquify(basename, co.co_code)
co_name = mapped_name
assert mapped_name not in fn_name_map
fn_name_map[mapped_name] = basename
co.co_name = mapped_name
pass
elif co_name in fn_name_map:
# FIXME: better would be a hash of the co_code
mapped_name = code_uniquify(co_name, co.co_code)
fn_name_map[mapped_name] = co_name
co.co_name = mapped_name
pass
co = co.freeze()
all_fns.add(co_name)
if co.co_name != '<module>' or co.co_filename:
real_out.write("\n" + format_code_info(co, version, mapped_name) + "\n")
bytecode = Bytecode(co, opc, dup_lines=True)
real_out.write(bytecode.dis(asm_format=True) + "\n") | [
"def",
"disco_loop_asm_format",
"(",
"opc",
",",
"version",
",",
"co",
",",
"real_out",
",",
"fn_name_map",
",",
"all_fns",
")",
":",
"if",
"version",
"<",
"3.0",
":",
"co",
"=",
"code2compat",
"(",
"co",
")",
"else",
":",
"co",
"=",
"code3compat",
"("... | Produces disassembly in a format more conducive to
automatic assembly by producing inner modules before they are
used by outer ones. Since this is recusive, we'll
use more stack space at runtime. | [
"Produces",
"disassembly",
"in",
"a",
"format",
"more",
"conducive",
"to",
"automatic",
"assembly",
"by",
"producing",
"inner",
"modules",
"before",
"they",
"are",
"used",
"by",
"outer",
"ones",
".",
"Since",
"this",
"is",
"recusive",
"we",
"ll",
"use",
"mor... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/main.py#L157-L222 | train | 213,124 |
rocky/python-xdis | xdis/verify.py | wr_long | def wr_long(f, x):
"""Internal; write a 32-bit int to a file in little-endian order."""
if PYTHON3:
f.write(bytes([x & 0xff]))
f.write(bytes([(x >> 8) & 0xff]))
f.write(bytes([(x >> 16) & 0xff]))
f.write(bytes([(x >> 24) & 0xff]))
else:
f.write(chr( x & 0xff))
f.write(chr((x >> 8) & 0xff))
f.write(chr((x >> 16) & 0xff))
f.write(chr((x >> 24) & 0xff)) | python | def wr_long(f, x):
"""Internal; write a 32-bit int to a file in little-endian order."""
if PYTHON3:
f.write(bytes([x & 0xff]))
f.write(bytes([(x >> 8) & 0xff]))
f.write(bytes([(x >> 16) & 0xff]))
f.write(bytes([(x >> 24) & 0xff]))
else:
f.write(chr( x & 0xff))
f.write(chr((x >> 8) & 0xff))
f.write(chr((x >> 16) & 0xff))
f.write(chr((x >> 24) & 0xff)) | [
"def",
"wr_long",
"(",
"f",
",",
"x",
")",
":",
"if",
"PYTHON3",
":",
"f",
".",
"write",
"(",
"bytes",
"(",
"[",
"x",
"&",
"0xff",
"]",
")",
")",
"f",
".",
"write",
"(",
"bytes",
"(",
"[",
"(",
"x",
">>",
"8",
")",
"&",
"0xff",
"]",
")",
... | Internal; write a 32-bit int to a file in little-endian order. | [
"Internal",
";",
"write",
"a",
"32",
"-",
"bit",
"int",
"to",
"a",
"file",
"in",
"little",
"-",
"endian",
"order",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/verify.py#L23-L34 | train | 213,125 |
rocky/python-xdis | xdis/verify.py | dump_compile | def dump_compile(codeobject, filename, timestamp, magic):
"""Write code object as a byte-compiled file
Arguments:
codeobject: code object
filefile: bytecode file to write
timestamp: timestamp to put in file
magic: Pyton bytecode magic
"""
# Atomically write the pyc/pyo file. Issue #13146.
# id() is used to generate a pseudo-random filename.
path_tmp = '%s.%s' % (filename, id(filename))
fc = None
try:
fc = open(path_tmp, 'wb')
if PYTHON3:
fc.write(bytes([0, 0, 0, 0]))
else:
fc.write('\0\0\0\0')
wr_long(fc, timestamp)
marshal.dump(codeobject, fc)
fc.flush()
fc.seek(0, 0)
fc.write(magic)
fc.close()
os.rename(path_tmp, filename)
except OSError:
try:
os.unlink(path_tmp)
except OSError:
pass
raise
finally:
if fc: fc.close() | python | def dump_compile(codeobject, filename, timestamp, magic):
"""Write code object as a byte-compiled file
Arguments:
codeobject: code object
filefile: bytecode file to write
timestamp: timestamp to put in file
magic: Pyton bytecode magic
"""
# Atomically write the pyc/pyo file. Issue #13146.
# id() is used to generate a pseudo-random filename.
path_tmp = '%s.%s' % (filename, id(filename))
fc = None
try:
fc = open(path_tmp, 'wb')
if PYTHON3:
fc.write(bytes([0, 0, 0, 0]))
else:
fc.write('\0\0\0\0')
wr_long(fc, timestamp)
marshal.dump(codeobject, fc)
fc.flush()
fc.seek(0, 0)
fc.write(magic)
fc.close()
os.rename(path_tmp, filename)
except OSError:
try:
os.unlink(path_tmp)
except OSError:
pass
raise
finally:
if fc: fc.close() | [
"def",
"dump_compile",
"(",
"codeobject",
",",
"filename",
",",
"timestamp",
",",
"magic",
")",
":",
"# Atomically write the pyc/pyo file. Issue #13146.",
"# id() is used to generate a pseudo-random filename.",
"path_tmp",
"=",
"'%s.%s'",
"%",
"(",
"filename",
",",
"id",
... | Write code object as a byte-compiled file
Arguments:
codeobject: code object
filefile: bytecode file to write
timestamp: timestamp to put in file
magic: Pyton bytecode magic | [
"Write",
"code",
"object",
"as",
"a",
"byte",
"-",
"compiled",
"file"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/verify.py#L36-L69 | train | 213,126 |
rocky/python-xdis | xdis/magics.py | int2magic | def int2magic(magic_int):
"""Given a magic int like 62211, compute the corresponding magic byte string
b'\x03\xf3\r\n' using the conversion method that does this.
See also dictionary magic2nt2version which has precomputed these values
for knonwn magic_int's.
"""
if (sys.version_info >= (3, 0)):
return struct.pack('<Hcc', magic_int, bytes('\r', 'utf-8'), bytes('\n', 'utf-8'))
else:
return struct.pack('<Hcc', magic_int, '\r', '\n') | python | def int2magic(magic_int):
"""Given a magic int like 62211, compute the corresponding magic byte string
b'\x03\xf3\r\n' using the conversion method that does this.
See also dictionary magic2nt2version which has precomputed these values
for knonwn magic_int's.
"""
if (sys.version_info >= (3, 0)):
return struct.pack('<Hcc', magic_int, bytes('\r', 'utf-8'), bytes('\n', 'utf-8'))
else:
return struct.pack('<Hcc', magic_int, '\r', '\n') | [
"def",
"int2magic",
"(",
"magic_int",
")",
":",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"'<Hcc'",
",",
"magic_int",
",",
"bytes",
"(",
"'\\r'",
",",
"'utf-8'",
")",
",",
... | Given a magic int like 62211, compute the corresponding magic byte string
b'\x03\xf3\r\n' using the conversion method that does this.
See also dictionary magic2nt2version which has precomputed these values
for knonwn magic_int's. | [
"Given",
"a",
"magic",
"int",
"like",
"62211",
"compute",
"the",
"corresponding",
"magic",
"byte",
"string",
"b",
"\\",
"x03",
"\\",
"xf3",
"\\",
"r",
"\\",
"n",
"using",
"the",
"conversion",
"method",
"that",
"does",
"this",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/magics.py#L42-L53 | train | 213,127 |
rocky/python-xdis | xdis/magics.py | sysinfo2float | def sysinfo2float(version_info=sys.version_info):
"""Convert a sys.versions_info-compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can only be used for released version
of C Python, not interim development versions, since we can't
represent that as a floating-point number.
For handling Pypy, pyston, jython, etc. and interim versions of
C Python, use sysinfo2magic.
"""
vers_str = '.'.join([str(v) for v in version_info[0:3]])
if version_info[3] != 'final':
vers_str += '.' + ''.join([str(i) for i in version_info[3:]])
if IS_PYPY:
vers_str += 'pypy'
else:
try:
import platform
platform = platform.python_implementation()
if platform in ('Jython', 'Pyston'):
vers_str += platform
pass
except ImportError:
# Python may be too old, e.g. < 2.6 or implementation may
# just not have platform
pass
except AttributeError:
pass
return py_str2float(vers_str) | python | def sysinfo2float(version_info=sys.version_info):
"""Convert a sys.versions_info-compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can only be used for released version
of C Python, not interim development versions, since we can't
represent that as a floating-point number.
For handling Pypy, pyston, jython, etc. and interim versions of
C Python, use sysinfo2magic.
"""
vers_str = '.'.join([str(v) for v in version_info[0:3]])
if version_info[3] != 'final':
vers_str += '.' + ''.join([str(i) for i in version_info[3:]])
if IS_PYPY:
vers_str += 'pypy'
else:
try:
import platform
platform = platform.python_implementation()
if platform in ('Jython', 'Pyston'):
vers_str += platform
pass
except ImportError:
# Python may be too old, e.g. < 2.6 or implementation may
# just not have platform
pass
except AttributeError:
pass
return py_str2float(vers_str) | [
"def",
"sysinfo2float",
"(",
"version_info",
"=",
"sys",
".",
"version_info",
")",
":",
"vers_str",
"=",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"version_info",
"[",
"0",
":",
"3",
"]",
"]",
")",
"if",
"version_info",
... | Convert a sys.versions_info-compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can only be used for released version
of C Python, not interim development versions, since we can't
represent that as a floating-point number.
For handling Pypy, pyston, jython, etc. and interim versions of
C Python, use sysinfo2magic. | [
"Convert",
"a",
"sys",
".",
"versions_info",
"-",
"compatible",
"list",
"into",
"a",
"canonic",
"floating",
"-",
"point",
"number",
"which",
"that",
"can",
"then",
"be",
"used",
"to",
"look",
"up",
"a",
"magic",
"number",
".",
"Note",
"that",
"this",
"ca... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/magics.py#L357-L386 | train | 213,128 |
rocky/python-xdis | xdis/magics.py | sysinfo2magic | def sysinfo2magic(version_info=sys.version_info):
"""Convert a list sys.versions_info compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can raise an exception.
"""
# FIXME: DRY with sysinfo2float()
vers_str = '.'.join([str(v) for v in version_info[0:3]])
if version_info[3] != 'final':
vers_str += ''.join([str(v) for v in version_info[3:]])
if IS_PYPY:
vers_str += 'pypy'
else:
try:
import platform
platform = platform.python_implementation()
if platform in ('Jython', 'Pyston'):
vers_str += platform
pass
except ImportError:
# Python may be too old, e.g. < 2.6 or implementation may
# just not have platform
pass
return magics[vers_str] | python | def sysinfo2magic(version_info=sys.version_info):
"""Convert a list sys.versions_info compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can raise an exception.
"""
# FIXME: DRY with sysinfo2float()
vers_str = '.'.join([str(v) for v in version_info[0:3]])
if version_info[3] != 'final':
vers_str += ''.join([str(v) for v in version_info[3:]])
if IS_PYPY:
vers_str += 'pypy'
else:
try:
import platform
platform = platform.python_implementation()
if platform in ('Jython', 'Pyston'):
vers_str += platform
pass
except ImportError:
# Python may be too old, e.g. < 2.6 or implementation may
# just not have platform
pass
return magics[vers_str] | [
"def",
"sysinfo2magic",
"(",
"version_info",
"=",
"sys",
".",
"version_info",
")",
":",
"# FIXME: DRY with sysinfo2float()",
"vers_str",
"=",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"version_info",
"[",
"0",
":",
"3",
"]",
"... | Convert a list sys.versions_info compatible list into a 'canonic'
floating-point number which that can then be used to look up a
magic number. Note that this can raise an exception. | [
"Convert",
"a",
"list",
"sys",
".",
"versions_info",
"compatible",
"list",
"into",
"a",
"canonic",
"floating",
"-",
"point",
"number",
"which",
"that",
"can",
"then",
"be",
"used",
"to",
"look",
"up",
"a",
"magic",
"number",
".",
"Note",
"that",
"this",
... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/magics.py#L389-L414 | train | 213,129 |
rocky/python-xdis | xdis/opcodes/base.py | init_opdata | def init_opdata(l, from_mod, version=None, is_pypy=False):
"""Sets up a number of the structures found in Python's
opcode.py. Python opcode.py routines assign attributes to modules.
In order to do this in a modular way here, the local dictionary
for the module is passed.
"""
if version:
l['python_version'] = version
l['is_pypy'] = is_pypy
l['cmp_op'] = cmp_op
l['HAVE_ARGUMENT'] = HAVE_ARGUMENT
if version <= 3.5:
l['findlinestarts'] = findlinestarts
l['findlabels'] = findlabels
l['get_jump_targets'] = get_jump_targets
l['get_jump_target_maps'] = get_jump_target_maps
else:
l['findlinestarts'] = wordcode.findlinestarts
l['findlabels'] = wordcode.findlabels
l['get_jump_targets'] = wordcode.get_jump_targets
l['get_jump_target_maps'] = wordcode.get_jump_target_maps
l['opmap'] = deepcopy(from_mod.opmap)
l['opname'] = deepcopy(from_mod.opname)
for field in fields2copy:
l[field] = list(getattr(from_mod, field)) | python | def init_opdata(l, from_mod, version=None, is_pypy=False):
"""Sets up a number of the structures found in Python's
opcode.py. Python opcode.py routines assign attributes to modules.
In order to do this in a modular way here, the local dictionary
for the module is passed.
"""
if version:
l['python_version'] = version
l['is_pypy'] = is_pypy
l['cmp_op'] = cmp_op
l['HAVE_ARGUMENT'] = HAVE_ARGUMENT
if version <= 3.5:
l['findlinestarts'] = findlinestarts
l['findlabels'] = findlabels
l['get_jump_targets'] = get_jump_targets
l['get_jump_target_maps'] = get_jump_target_maps
else:
l['findlinestarts'] = wordcode.findlinestarts
l['findlabels'] = wordcode.findlabels
l['get_jump_targets'] = wordcode.get_jump_targets
l['get_jump_target_maps'] = wordcode.get_jump_target_maps
l['opmap'] = deepcopy(from_mod.opmap)
l['opname'] = deepcopy(from_mod.opname)
for field in fields2copy:
l[field] = list(getattr(from_mod, field)) | [
"def",
"init_opdata",
"(",
"l",
",",
"from_mod",
",",
"version",
"=",
"None",
",",
"is_pypy",
"=",
"False",
")",
":",
"if",
"version",
":",
"l",
"[",
"'python_version'",
"]",
"=",
"version",
"l",
"[",
"'is_pypy'",
"]",
"=",
"is_pypy",
"l",
"[",
"'cmp... | Sets up a number of the structures found in Python's
opcode.py. Python opcode.py routines assign attributes to modules.
In order to do this in a modular way here, the local dictionary
for the module is passed. | [
"Sets",
"up",
"a",
"number",
"of",
"the",
"structures",
"found",
"in",
"Python",
"s",
"opcode",
".",
"py",
".",
"Python",
"opcode",
".",
"py",
"routines",
"assign",
"attributes",
"to",
"modules",
".",
"In",
"order",
"to",
"do",
"this",
"in",
"a",
"modu... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/opcodes/base.py#L43-L70 | train | 213,130 |
rocky/python-xdis | xdis/opcodes/base.py | rm_op | def rm_op(l, name, op):
"""Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op.
"""
# opname is an array, so we need to keep the position in there.
l['opname'][op] = '<%s>' % op
if op in l['hasconst']:
l['hasconst'].remove(op)
if op in l['hascompare']:
l['hascompare'].remove(op)
if op in l['hascondition']:
l['hascondition'].remove(op)
if op in l['hasfree']:
l['hasfree'].remove(op)
if op in l['hasjabs']:
l['hasjabs'].remove(op)
if op in l['hasname']:
l['hasname'].remove(op)
if op in l['hasjrel']:
l['hasjrel'].remove(op)
if op in l['haslocal']:
l['haslocal'].remove(op)
if op in l['hasname']:
l['hasname'].remove(op)
if op in l['hasnargs']:
l['hasnargs'].remove(op)
if op in l['hasvargs']:
l['hasvargs'].remove(op)
if op in l['nofollow']:
l['nofollow'].remove(op)
assert l['opmap'][name] == op
del l['opmap'][name] | python | def rm_op(l, name, op):
"""Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op.
"""
# opname is an array, so we need to keep the position in there.
l['opname'][op] = '<%s>' % op
if op in l['hasconst']:
l['hasconst'].remove(op)
if op in l['hascompare']:
l['hascompare'].remove(op)
if op in l['hascondition']:
l['hascondition'].remove(op)
if op in l['hasfree']:
l['hasfree'].remove(op)
if op in l['hasjabs']:
l['hasjabs'].remove(op)
if op in l['hasname']:
l['hasname'].remove(op)
if op in l['hasjrel']:
l['hasjrel'].remove(op)
if op in l['haslocal']:
l['haslocal'].remove(op)
if op in l['hasname']:
l['hasname'].remove(op)
if op in l['hasnargs']:
l['hasnargs'].remove(op)
if op in l['hasvargs']:
l['hasvargs'].remove(op)
if op in l['nofollow']:
l['nofollow'].remove(op)
assert l['opmap'][name] == op
del l['opmap'][name] | [
"def",
"rm_op",
"(",
"l",
",",
"name",
",",
"op",
")",
":",
"# opname is an array, so we need to keep the position in there.",
"l",
"[",
"'opname'",
"]",
"[",
"op",
"]",
"=",
"'<%s>'",
"%",
"op",
"if",
"op",
"in",
"l",
"[",
"'hasconst'",
"]",
":",
"l",
"... | Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op. | [
"Remove",
"an",
"opcode",
".",
"This",
"is",
"used",
"when",
"basing",
"a",
"new",
"Python",
"release",
"off",
"of",
"another",
"one",
"and",
"there",
"is",
"an",
"opcode",
"that",
"is",
"in",
"the",
"old",
"release",
"that",
"was",
"removed",
"in",
"t... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/opcodes/base.py#L120-L156 | train | 213,131 |
rocky/python-xdis | xdis/opcodes/base.py | opcode_check | def opcode_check(l):
"""When the version of Python we are running happens
to have the same opcode set as the opcode we are
importing, we perform checks to make sure our opcode
set matches exactly.
"""
# Python 2.6 reports 2.6000000000000001
if (abs(PYTHON_VERSION - l['python_version']) <= 0.01
and IS_PYPY == l['is_pypy']):
try:
import dis
opmap = fix_opcode_names(dis.opmap)
# print(set(opmap.items()) - set(l['opmap'].items()))
# print(set(l['opmap'].items()) - set(opmap.items()))
assert all(item in opmap.items() for item in l['opmap'].items())
assert all(item in l['opmap'].items() for item in opmap.items())
except:
import sys | python | def opcode_check(l):
"""When the version of Python we are running happens
to have the same opcode set as the opcode we are
importing, we perform checks to make sure our opcode
set matches exactly.
"""
# Python 2.6 reports 2.6000000000000001
if (abs(PYTHON_VERSION - l['python_version']) <= 0.01
and IS_PYPY == l['is_pypy']):
try:
import dis
opmap = fix_opcode_names(dis.opmap)
# print(set(opmap.items()) - set(l['opmap'].items()))
# print(set(l['opmap'].items()) - set(opmap.items()))
assert all(item in opmap.items() for item in l['opmap'].items())
assert all(item in l['opmap'].items() for item in opmap.items())
except:
import sys | [
"def",
"opcode_check",
"(",
"l",
")",
":",
"# Python 2.6 reports 2.6000000000000001",
"if",
"(",
"abs",
"(",
"PYTHON_VERSION",
"-",
"l",
"[",
"'python_version'",
"]",
")",
"<=",
"0.01",
"and",
"IS_PYPY",
"==",
"l",
"[",
"'is_pypy'",
"]",
")",
":",
"try",
"... | When the version of Python we are running happens
to have the same opcode set as the opcode we are
importing, we perform checks to make sure our opcode
set matches exactly. | [
"When",
"the",
"version",
"of",
"Python",
"we",
"are",
"running",
"happens",
"to",
"have",
"the",
"same",
"opcode",
"set",
"as",
"the",
"opcode",
"we",
"are",
"importing",
"we",
"perform",
"checks",
"to",
"make",
"sure",
"our",
"opcode",
"set",
"matches",
... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/opcodes/base.py#L238-L256 | train | 213,132 |
rocky/python-xdis | xdis/opcodes/base.py | dump_opcodes | def dump_opcodes(opmap):
"""Utility for dumping opcodes"""
op2name = {}
for k in opmap.keys():
op2name[opmap[k]] = k
for i in sorted(op2name.keys()):
print("%-3s %s" % (str(i), op2name[i])) | python | def dump_opcodes(opmap):
"""Utility for dumping opcodes"""
op2name = {}
for k in opmap.keys():
op2name[opmap[k]] = k
for i in sorted(op2name.keys()):
print("%-3s %s" % (str(i), op2name[i])) | [
"def",
"dump_opcodes",
"(",
"opmap",
")",
":",
"op2name",
"=",
"{",
"}",
"for",
"k",
"in",
"opmap",
".",
"keys",
"(",
")",
":",
"op2name",
"[",
"opmap",
"[",
"k",
"]",
"]",
"=",
"k",
"for",
"i",
"in",
"sorted",
"(",
"op2name",
".",
"keys",
"(",... | Utility for dumping opcodes | [
"Utility",
"for",
"dumping",
"opcodes"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/opcodes/base.py#L258-L264 | train | 213,133 |
rocky/python-xdis | xdis/util.py | pretty_flags | def pretty_flags(flags):
"""Return pretty representation of code flags."""
names = []
result = "0x%08x" % flags
for i in range(32):
flag = 1 << i
if flags & flag:
names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
flags ^= flag
if not flags:
break
else:
names.append(hex(flags))
names.reverse()
return "%s (%s)" % (result, " | ".join(names)) | python | def pretty_flags(flags):
"""Return pretty representation of code flags."""
names = []
result = "0x%08x" % flags
for i in range(32):
flag = 1 << i
if flags & flag:
names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
flags ^= flag
if not flags:
break
else:
names.append(hex(flags))
names.reverse()
return "%s (%s)" % (result, " | ".join(names)) | [
"def",
"pretty_flags",
"(",
"flags",
")",
":",
"names",
"=",
"[",
"]",
"result",
"=",
"\"0x%08x\"",
"%",
"flags",
"for",
"i",
"in",
"range",
"(",
"32",
")",
":",
"flag",
"=",
"1",
"<<",
"i",
"if",
"flags",
"&",
"flag",
":",
"names",
".",
"append"... | Return pretty representation of code flags. | [
"Return",
"pretty",
"representation",
"of",
"code",
"flags",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/util.py#L69-L83 | train | 213,134 |
rocky/python-xdis | xdis/util.py | _try_compile | def _try_compile(source, name):
"""Attempts to compile the given source, first as an expression and
then as a statement if the first approach fails.
Utility function to accept strings in functions that otherwise
expect code objects
"""
try:
c = compile(source, name, 'eval')
except SyntaxError:
c = compile(source, name, 'exec')
return c | python | def _try_compile(source, name):
"""Attempts to compile the given source, first as an expression and
then as a statement if the first approach fails.
Utility function to accept strings in functions that otherwise
expect code objects
"""
try:
c = compile(source, name, 'eval')
except SyntaxError:
c = compile(source, name, 'exec')
return c | [
"def",
"_try_compile",
"(",
"source",
",",
"name",
")",
":",
"try",
":",
"c",
"=",
"compile",
"(",
"source",
",",
"name",
",",
"'eval'",
")",
"except",
"SyntaxError",
":",
"c",
"=",
"compile",
"(",
"source",
",",
"name",
",",
"'exec'",
")",
"return",... | Attempts to compile the given source, first as an expression and
then as a statement if the first approach fails.
Utility function to accept strings in functions that otherwise
expect code objects | [
"Attempts",
"to",
"compile",
"the",
"given",
"source",
"first",
"as",
"an",
"expression",
"and",
"then",
"as",
"a",
"statement",
"if",
"the",
"first",
"approach",
"fails",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/util.py#L145-L156 | train | 213,135 |
rocky/python-xdis | xdis/util.py | get_code_object | def get_code_object(x):
"""Helper to handle methods, functions, generators, strings and raw code objects"""
if hasattr(x, '__func__'): # Method
x = x.__func__
if hasattr(x, '__code__'): # Function
x = x.__code__
if hasattr(x, 'gi_code'): # Generator
x = x.gi_code
if isinstance(x, str): # Source code
x = _try_compile(x, "<disassembly>")
if hasattr(x, 'co_code'): # Code object
return x
raise TypeError("don't know how to disassemble %s objects" %
type(x).__name__) | python | def get_code_object(x):
"""Helper to handle methods, functions, generators, strings and raw code objects"""
if hasattr(x, '__func__'): # Method
x = x.__func__
if hasattr(x, '__code__'): # Function
x = x.__code__
if hasattr(x, 'gi_code'): # Generator
x = x.gi_code
if isinstance(x, str): # Source code
x = _try_compile(x, "<disassembly>")
if hasattr(x, 'co_code'): # Code object
return x
raise TypeError("don't know how to disassemble %s objects" %
type(x).__name__) | [
"def",
"get_code_object",
"(",
"x",
")",
":",
"if",
"hasattr",
"(",
"x",
",",
"'__func__'",
")",
":",
"# Method",
"x",
"=",
"x",
".",
"__func__",
"if",
"hasattr",
"(",
"x",
",",
"'__code__'",
")",
":",
"# Function",
"x",
"=",
"x",
".",
"__code__",
... | Helper to handle methods, functions, generators, strings and raw code objects | [
"Helper",
"to",
"handle",
"methods",
"functions",
"generators",
"strings",
"and",
"raw",
"code",
"objects"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/util.py#L158-L171 | train | 213,136 |
rocky/python-xdis | xdis/bytecode.py | get_jump_target_maps | def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachable
instructions. The values of the dictionary may be useful in control-flow
analysis.
"""
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_bytecode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
if op in opc.NOFOLLOW:
prev_offset = -1
else:
prev_offset = offset
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
op_len = op_size(op, opc)
jump_offset = offset + op_len + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev | python | def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachable
instructions. The values of the dictionary may be useful in control-flow
analysis.
"""
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_bytecode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
if op in opc.NOFOLLOW:
prev_offset = -1
else:
prev_offset = offset
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
op_len = op_size(op, opc)
jump_offset = offset + op_len + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev | [
"def",
"get_jump_target_maps",
"(",
"code",
",",
"opc",
")",
":",
"offset2prev",
"=",
"{",
"}",
"prev_offset",
"=",
"-",
"1",
"for",
"offset",
",",
"op",
",",
"arg",
"in",
"unpack_opargs_bytecode",
"(",
"code",
",",
"opc",
")",
":",
"if",
"prev_offset",
... | Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachable
instructions. The values of the dictionary may be useful in control-flow
analysis. | [
"Returns",
"a",
"dictionary",
"where",
"the",
"key",
"is",
"an",
"offset",
"and",
"the",
"values",
"are",
"a",
"list",
"of",
"instruction",
"offsets",
"which",
"can",
"get",
"run",
"before",
"that",
"instruction",
".",
"This",
"includes",
"jump",
"instructio... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L137-L167 | train | 213,137 |
rocky/python-xdis | xdis/bytecode.py | _get_const_info | def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not None:
argval = const_list[const_index]
# float values nan and inf are not directly representable in Python at least
# before 3.5 and even there it is via a library constant.
# So we will canonicalize their representation as float('nan') and float('inf')
if isinstance(argval, float) and str(argval) in frozenset(['nan', '-nan', 'inf', '-inf']):
return argval, "float('%s')" % argval
return argval, repr(argval) | python | def _get_const_info(const_index, const_list):
"""Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not None:
argval = const_list[const_index]
# float values nan and inf are not directly representable in Python at least
# before 3.5 and even there it is via a library constant.
# So we will canonicalize their representation as float('nan') and float('inf')
if isinstance(argval, float) and str(argval) in frozenset(['nan', '-nan', 'inf', '-inf']):
return argval, "float('%s')" % argval
return argval, repr(argval) | [
"def",
"_get_const_info",
"(",
"const_index",
",",
"const_list",
")",
":",
"argval",
"=",
"const_index",
"if",
"const_list",
"is",
"not",
"None",
":",
"argval",
"=",
"const_list",
"[",
"const_index",
"]",
"# float values nan and inf are not directly representable in Pyt... | Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr(). | [
"Helper",
"to",
"get",
"optional",
"details",
"about",
"const",
"references"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L172-L188 | train | 213,138 |
rocky/python-xdis | xdis/bytecode.py | _get_name_info | def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr().
"""
argval = name_index
if (name_list is not None
# PyPY seems to "optimize" out constant names,
# so we need for that:
and name_index < len(name_list)):
argval = name_list[name_index]
argrepr = argval
else:
argrepr = repr(argval)
return argval, argrepr | python | def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr().
"""
argval = name_index
if (name_list is not None
# PyPY seems to "optimize" out constant names,
# so we need for that:
and name_index < len(name_list)):
argval = name_list[name_index]
argrepr = argval
else:
argrepr = repr(argval)
return argval, argrepr | [
"def",
"_get_name_info",
"(",
"name_index",
",",
"name_list",
")",
":",
"argval",
"=",
"name_index",
"if",
"(",
"name_list",
"is",
"not",
"None",
"# PyPY seems to \"optimize\" out constant names,",
"# so we need for that:",
"and",
"name_index",
"<",
"len",
"(",
"name_... | Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr(). | [
"Helper",
"to",
"get",
"optional",
"details",
"about",
"named",
"references"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L190-L206 | train | 213,139 |
rocky/python-xdis | xdis/bytecode.py | instruction_size | def instruction_size(op, opc):
"""For a given opcode, `op`, in opcode module `opc`,
return the size, in bytes, of an `op` instruction.
This is the size of the opcode (1 byte) and any operand it has. In
Python before version 3.6 this will be either 1 or 3 bytes. In
Python 3.6 or later, it is 2 bytes or a "word"."""
if op < opc.HAVE_ARGUMENT:
return 2 if opc.version >= 3.6 else 1
else:
return 2 if opc.version >= 3.6 else 3 | python | def instruction_size(op, opc):
"""For a given opcode, `op`, in opcode module `opc`,
return the size, in bytes, of an `op` instruction.
This is the size of the opcode (1 byte) and any operand it has. In
Python before version 3.6 this will be either 1 or 3 bytes. In
Python 3.6 or later, it is 2 bytes or a "word"."""
if op < opc.HAVE_ARGUMENT:
return 2 if opc.version >= 3.6 else 1
else:
return 2 if opc.version >= 3.6 else 3 | [
"def",
"instruction_size",
"(",
"op",
",",
"opc",
")",
":",
"if",
"op",
"<",
"opc",
".",
"HAVE_ARGUMENT",
":",
"return",
"2",
"if",
"opc",
".",
"version",
">=",
"3.6",
"else",
"1",
"else",
":",
"return",
"2",
"if",
"opc",
".",
"version",
">=",
"3.6... | For a given opcode, `op`, in opcode module `opc`,
return the size, in bytes, of an `op` instruction.
This is the size of the opcode (1 byte) and any operand it has. In
Python before version 3.6 this will be either 1 or 3 bytes. In
Python 3.6 or later, it is 2 bytes or a "word". | [
"For",
"a",
"given",
"opcode",
"op",
"in",
"opcode",
"module",
"opc",
"return",
"the",
"size",
"in",
"bytes",
"of",
"an",
"op",
"instruction",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L325-L335 | train | 213,140 |
rocky/python-xdis | xdis/bytecode.py | Instruction.disassemble | def disassemble(self, lineno_width=3,
mark_as_current=False,
asm_format=False,
show_bytes=False):
"""Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*mark_as_current* inserts a '-->' marker arrow as part of the line
"""
fields = []
if asm_format:
indexed_operand = set(['name', 'local', 'compare', 'free'])
# Column: Source code line number
if lineno_width:
if self.starts_line is not None:
if asm_format:
lineno_fmt = "%%%dd:\n" % lineno_width
fields.append(lineno_fmt % self.starts_line)
fields.append(' ' * (lineno_width))
if self.is_jump_target:
fields.append(' ' * (lineno_width-1))
else:
lineno_fmt = "%%%dd:" % lineno_width
fields.append(lineno_fmt % self.starts_line)
else:
fields.append(' ' * (lineno_width+1))
# Column: Current instruction indicator
if mark_as_current and not asm_format:
fields.append('-->')
else:
fields.append(' ')
# Column: Jump target marker
if self.is_jump_target:
if not asm_format:
fields.append('>>')
else:
fields = ["L%d:\n" % self.offset] + fields
if not self.starts_line:
fields.append(' ')
else:
fields.append(' ')
# Column: Instruction offset from start of code sequence
if not asm_format:
fields.append(repr(self.offset).rjust(4))
if show_bytes:
hex_bytecode = "|%02x" % self.opcode
if self.inst_size == 1:
# Not 3.6 or later
hex_bytecode += ' ' * (2*3)
if self.inst_size == 2:
# Must by Python 3.6 or later
if self.has_arg:
hex_bytecode += " %02x" % (self.arg % 256)
else :
hex_bytecode += ' 00'
elif self.inst_size == 3:
# Not 3.6 or later
hex_bytecode += " %02x %02x" % (
(self.arg >> 8, self.arg % 256))
fields.append(hex_bytecode + '|')
# Column: Opcode name
fields.append(self.opname.ljust(20))
# Column: Opcode argument
if self.arg is not None:
argrepr = self.argrepr
if asm_format:
if self.optype == 'jabs':
fields.append('L' + str(self.arg))
elif self.optype == 'jrel':
argval = self.offset + self.arg + self.inst_size
fields.append('L' + str(argval))
elif self.optype in indexed_operand:
fields.append('(%s)' % argrepr)
argrepr = None
elif (self.optype == 'const'
and not re.search('\s', argrepr)):
fields.append('(%s)' % argrepr)
argrepr = None
else:
fields.append(repr(self.arg))
elif not (show_bytes and argrepr):
fields.append(repr(self.arg).rjust(6))
# Column: Opcode argument details
if argrepr:
fields.append('(%s)' % argrepr)
pass
pass
return ' '.join(fields).rstrip() | python | def disassemble(self, lineno_width=3,
mark_as_current=False,
asm_format=False,
show_bytes=False):
"""Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*mark_as_current* inserts a '-->' marker arrow as part of the line
"""
fields = []
if asm_format:
indexed_operand = set(['name', 'local', 'compare', 'free'])
# Column: Source code line number
if lineno_width:
if self.starts_line is not None:
if asm_format:
lineno_fmt = "%%%dd:\n" % lineno_width
fields.append(lineno_fmt % self.starts_line)
fields.append(' ' * (lineno_width))
if self.is_jump_target:
fields.append(' ' * (lineno_width-1))
else:
lineno_fmt = "%%%dd:" % lineno_width
fields.append(lineno_fmt % self.starts_line)
else:
fields.append(' ' * (lineno_width+1))
# Column: Current instruction indicator
if mark_as_current and not asm_format:
fields.append('-->')
else:
fields.append(' ')
# Column: Jump target marker
if self.is_jump_target:
if not asm_format:
fields.append('>>')
else:
fields = ["L%d:\n" % self.offset] + fields
if not self.starts_line:
fields.append(' ')
else:
fields.append(' ')
# Column: Instruction offset from start of code sequence
if not asm_format:
fields.append(repr(self.offset).rjust(4))
if show_bytes:
hex_bytecode = "|%02x" % self.opcode
if self.inst_size == 1:
# Not 3.6 or later
hex_bytecode += ' ' * (2*3)
if self.inst_size == 2:
# Must by Python 3.6 or later
if self.has_arg:
hex_bytecode += " %02x" % (self.arg % 256)
else :
hex_bytecode += ' 00'
elif self.inst_size == 3:
# Not 3.6 or later
hex_bytecode += " %02x %02x" % (
(self.arg >> 8, self.arg % 256))
fields.append(hex_bytecode + '|')
# Column: Opcode name
fields.append(self.opname.ljust(20))
# Column: Opcode argument
if self.arg is not None:
argrepr = self.argrepr
if asm_format:
if self.optype == 'jabs':
fields.append('L' + str(self.arg))
elif self.optype == 'jrel':
argval = self.offset + self.arg + self.inst_size
fields.append('L' + str(argval))
elif self.optype in indexed_operand:
fields.append('(%s)' % argrepr)
argrepr = None
elif (self.optype == 'const'
and not re.search('\s', argrepr)):
fields.append('(%s)' % argrepr)
argrepr = None
else:
fields.append(repr(self.arg))
elif not (show_bytes and argrepr):
fields.append(repr(self.arg).rjust(6))
# Column: Opcode argument details
if argrepr:
fields.append('(%s)' % argrepr)
pass
pass
return ' '.join(fields).rstrip() | [
"def",
"disassemble",
"(",
"self",
",",
"lineno_width",
"=",
"3",
",",
"mark_as_current",
"=",
"False",
",",
"asm_format",
"=",
"False",
",",
"show_bytes",
"=",
"False",
")",
":",
"fields",
"=",
"[",
"]",
"if",
"asm_format",
":",
"indexed_operand",
"=",
... | Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*mark_as_current* inserts a '-->' marker arrow as part of the line | [
"Format",
"instruction",
"details",
"for",
"inclusion",
"in",
"disassembly",
"output"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L371-L462 | train | 213,141 |
rocky/python-xdis | xdis/bytecode.py | Bytecode.from_traceback | def from_traceback(cls, tb):
""" Construct a Bytecode from the given traceback """
while tb.tb_next:
tb = tb.tb_next
return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) | python | def from_traceback(cls, tb):
""" Construct a Bytecode from the given traceback """
while tb.tb_next:
tb = tb.tb_next
return cls(tb.tb_frame.f_code, current_offset=tb.tb_lasti) | [
"def",
"from_traceback",
"(",
"cls",
",",
"tb",
")",
":",
"while",
"tb",
".",
"tb_next",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"return",
"cls",
"(",
"tb",
".",
"tb_frame",
".",
"f_code",
",",
"current_offset",
"=",
"tb",
".",
"tb_lasti",
")"
] | Construct a Bytecode from the given traceback | [
"Construct",
"a",
"Bytecode",
"from",
"the",
"given",
"traceback"
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L502-L506 | train | 213,142 |
rocky/python-xdis | xdis/bytecode.py | Bytecode.dis | def dis(self, asm_format=False, show_bytes=False):
"""Return a formatted view of the bytecode operations."""
co = self.codeobj
if self.current_offset is not None:
offset = self.current_offset
else:
offset = -1
output = StringIO()
self.disassemble_bytes(co.co_code, varnames=co.co_varnames,
names=co.co_names, constants=co.co_consts,
cells=self._cell_names,
linestarts=self._linestarts,
line_offset=self._line_offset,
file=output,
lasti=offset,
asm_format=asm_format,
show_bytes=show_bytes)
return output.getvalue() | python | def dis(self, asm_format=False, show_bytes=False):
"""Return a formatted view of the bytecode operations."""
co = self.codeobj
if self.current_offset is not None:
offset = self.current_offset
else:
offset = -1
output = StringIO()
self.disassemble_bytes(co.co_code, varnames=co.co_varnames,
names=co.co_names, constants=co.co_consts,
cells=self._cell_names,
linestarts=self._linestarts,
line_offset=self._line_offset,
file=output,
lasti=offset,
asm_format=asm_format,
show_bytes=show_bytes)
return output.getvalue() | [
"def",
"dis",
"(",
"self",
",",
"asm_format",
"=",
"False",
",",
"show_bytes",
"=",
"False",
")",
":",
"co",
"=",
"self",
".",
"codeobj",
"if",
"self",
".",
"current_offset",
"is",
"not",
"None",
":",
"offset",
"=",
"self",
".",
"current_offset",
"else... | Return a formatted view of the bytecode operations. | [
"Return",
"a",
"formatted",
"view",
"of",
"the",
"bytecode",
"operations",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/bytecode.py#L512-L529 | train | 213,143 |
rocky/python-xdis | xdis/wordcode.py | get_jump_target_maps | def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachible
instructions. The values of the dictionary may be useful in control-flow
analysis.
"""
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
prev_offset = offset
if op in opc.NOFOLLOW:
prev_offset = -1
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev | python | def get_jump_target_maps(code, opc):
"""Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachible
instructions. The values of the dictionary may be useful in control-flow
analysis.
"""
offset2prev = {}
prev_offset = -1
for offset, op, arg in unpack_opargs_wordcode(code, opc):
if prev_offset >= 0:
prev_list = offset2prev.get(offset, [])
prev_list.append(prev_offset)
offset2prev[offset] = prev_list
prev_offset = offset
if op in opc.NOFOLLOW:
prev_offset = -1
if arg is not None:
jump_offset = -1
if op in opc.JREL_OPS:
jump_offset = offset + 2 + arg
elif op in opc.JABS_OPS:
jump_offset = arg
if jump_offset >= 0:
prev_list = offset2prev.get(jump_offset, [])
prev_list.append(offset)
offset2prev[jump_offset] = prev_list
return offset2prev | [
"def",
"get_jump_target_maps",
"(",
"code",
",",
"opc",
")",
":",
"offset2prev",
"=",
"{",
"}",
"prev_offset",
"=",
"-",
"1",
"for",
"offset",
",",
"op",
",",
"arg",
"in",
"unpack_opargs_wordcode",
"(",
"code",
",",
"opc",
")",
":",
"if",
"prev_offset",
... | Returns a dictionary where the key is an offset and the values are
a list of instruction offsets which can get run before that
instruction. This includes jump instructions as well as non-jump
instructions. Therefore, the keys of the dictionary are reachible
instructions. The values of the dictionary may be useful in control-flow
analysis. | [
"Returns",
"a",
"dictionary",
"where",
"the",
"key",
"is",
"an",
"offset",
"and",
"the",
"values",
"are",
"a",
"list",
"of",
"instruction",
"offsets",
"which",
"can",
"get",
"run",
"before",
"that",
"instruction",
".",
"This",
"includes",
"jump",
"instructio... | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/wordcode.py#L100-L128 | train | 213,144 |
rocky/python-xdis | xdis/std.py | _StdApi.dis | def dis(self, x=None, file=None):
"""Disassemble classes, methods, functions, generators, or code.
With no argument, disassemble the last traceback.
"""
self._print(self.Bytecode(x).dis(), file) | python | def dis(self, x=None, file=None):
"""Disassemble classes, methods, functions, generators, or code.
With no argument, disassemble the last traceback.
"""
self._print(self.Bytecode(x).dis(), file) | [
"def",
"dis",
"(",
"self",
",",
"x",
"=",
"None",
",",
"file",
"=",
"None",
")",
":",
"self",
".",
"_print",
"(",
"self",
".",
"Bytecode",
"(",
"x",
")",
".",
"dis",
"(",
")",
",",
"file",
")"
] | Disassemble classes, methods, functions, generators, or code.
With no argument, disassemble the last traceback. | [
"Disassemble",
"classes",
"methods",
"functions",
"generators",
"or",
"code",
"."
] | 46a2902ae8f5d8eee495eed67ac0690fd545453d | https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/std.py#L135-L141 | train | 213,145 |
knipknap/exscript | Exscript/protocols/__init__.py | get_protocol_from_name | def get_protocol_from_name(name):
"""
Returns the protocol class for the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: The protocol class.
"""
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls | python | def get_protocol_from_name(name):
"""
Returns the protocol class for the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: The protocol class.
"""
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls | [
"def",
"get_protocol_from_name",
"(",
"name",
")",
":",
"cls",
"=",
"protocol_map",
".",
"get",
"(",
"name",
")",
"if",
"not",
"cls",
":",
"raise",
"ValueError",
"(",
"'Unsupported protocol \"%s\".'",
"%",
"name",
")",
"return",
"cls"
] | Returns the protocol class for the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: The protocol class. | [
"Returns",
"the",
"protocol",
"class",
"for",
"the",
"protocol",
"with",
"the",
"given",
"name",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/__init__.py#L39-L51 | train | 213,146 |
knipknap/exscript | Exscript/protocols/__init__.py | create_protocol | def create_protocol(name, **kwargs):
"""
Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol.
"""
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls(**kwargs) | python | def create_protocol(name, **kwargs):
"""
Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol.
"""
cls = protocol_map.get(name)
if not cls:
raise ValueError('Unsupported protocol "%s".' % name)
return cls(**kwargs) | [
"def",
"create_protocol",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
"=",
"protocol_map",
".",
"get",
"(",
"name",
")",
"if",
"not",
"cls",
":",
"raise",
"ValueError",
"(",
"'Unsupported protocol \"%s\".'",
"%",
"name",
")",
"return",
"cls",
... | Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol. | [
"Returns",
"an",
"instance",
"of",
"the",
"protocol",
"with",
"the",
"given",
"name",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/__init__.py#L54-L66 | train | 213,147 |
knipknap/exscript | Exscript/util/crypt.py | _long_from_raw | def _long_from_raw(thehash):
"""Fold to a long, a digest supplied as a string."""
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h]))
return hashnum | python | def _long_from_raw(thehash):
"""Fold to a long, a digest supplied as a string."""
hashnum = 0
for h in thehash:
hashnum <<= 8
hashnum |= ord(bytes([h]))
return hashnum | [
"def",
"_long_from_raw",
"(",
"thehash",
")",
":",
"hashnum",
"=",
"0",
"for",
"h",
"in",
"thehash",
":",
"hashnum",
"<<=",
"8",
"hashnum",
"|=",
"ord",
"(",
"bytes",
"(",
"[",
"h",
"]",
")",
")",
"return",
"hashnum"
] | Fold to a long, a digest supplied as a string. | [
"Fold",
"to",
"a",
"long",
"a",
"digest",
"supplied",
"as",
"a",
"string",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/crypt.py#L315-L321 | train | 213,148 |
knipknap/exscript | Exscript/logger.py | Log.aborted | def aborted(self, exc_info):
"""
Called by a logger to log an exception.
"""
self.exc_info = exc_info
self.did_end = True
self.write(format_exception(*self.exc_info)) | python | def aborted(self, exc_info):
"""
Called by a logger to log an exception.
"""
self.exc_info = exc_info
self.did_end = True
self.write(format_exception(*self.exc_info)) | [
"def",
"aborted",
"(",
"self",
",",
"exc_info",
")",
":",
"self",
".",
"exc_info",
"=",
"exc_info",
"self",
".",
"did_end",
"=",
"True",
"self",
".",
"write",
"(",
"format_exception",
"(",
"*",
"self",
".",
"exc_info",
")",
")"
] | Called by a logger to log an exception. | [
"Called",
"by",
"a",
"logger",
"to",
"log",
"an",
"exception",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/logger.py#L78-L84 | train | 213,149 |
knipknap/exscript | Exscript/key.py | PrivateKey.from_file | def from_file(filename, password='', keytype=None):
"""
Returns a new PrivateKey instance with the given attributes.
If keytype is None, we attempt to automatically detect the type.
:type filename: string
:param filename: The key file name.
:type password: string
:param password: The key password.
:type keytype: string
:param keytype: The key type.
:rtype: PrivateKey
:return: The new key.
"""
if keytype is None:
try:
key = RSAKey.from_private_key_file(filename)
keytype = 'rsa'
except SSHException as e:
try:
key = DSSKey.from_private_key_file(filename)
keytype = 'dss'
except SSHException as e:
msg = 'not a recognized private key: ' + repr(filename)
raise ValueError(msg)
key = PrivateKey(keytype)
key.filename = filename
key.password = password
return key | python | def from_file(filename, password='', keytype=None):
"""
Returns a new PrivateKey instance with the given attributes.
If keytype is None, we attempt to automatically detect the type.
:type filename: string
:param filename: The key file name.
:type password: string
:param password: The key password.
:type keytype: string
:param keytype: The key type.
:rtype: PrivateKey
:return: The new key.
"""
if keytype is None:
try:
key = RSAKey.from_private_key_file(filename)
keytype = 'rsa'
except SSHException as e:
try:
key = DSSKey.from_private_key_file(filename)
keytype = 'dss'
except SSHException as e:
msg = 'not a recognized private key: ' + repr(filename)
raise ValueError(msg)
key = PrivateKey(keytype)
key.filename = filename
key.password = password
return key | [
"def",
"from_file",
"(",
"filename",
",",
"password",
"=",
"''",
",",
"keytype",
"=",
"None",
")",
":",
"if",
"keytype",
"is",
"None",
":",
"try",
":",
"key",
"=",
"RSAKey",
".",
"from_private_key_file",
"(",
"filename",
")",
"keytype",
"=",
"'rsa'",
"... | Returns a new PrivateKey instance with the given attributes.
If keytype is None, we attempt to automatically detect the type.
:type filename: string
:param filename: The key file name.
:type password: string
:param password: The key password.
:type keytype: string
:param keytype: The key type.
:rtype: PrivateKey
:return: The new key. | [
"Returns",
"a",
"new",
"PrivateKey",
"instance",
"with",
"the",
"given",
"attributes",
".",
"If",
"keytype",
"is",
"None",
"we",
"attempt",
"to",
"automatically",
"detect",
"the",
"type",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/key.py#L55-L83 | train | 213,150 |
knipknap/exscript | Exscript/host.py | Host.get_uri | def get_uri(self):
"""
Returns a URI formatted representation of the host, including all
of it's attributes except for the name. Uses the
address, not the name of the host to build the URI.
:rtype: str
:return: A URI.
"""
url = Url()
url.protocol = self.get_protocol()
url.hostname = self.get_address()
url.port = self.get_tcp_port()
url.vars = dict((k, to_list(v))
for (k, v) in list(self.get_all().items())
if isinstance(v, str) or isinstance(v, list))
if self.account:
url.username = self.account.get_name()
url.password1 = self.account.get_password()
url.password2 = self.account.authorization_password
return str(url) | python | def get_uri(self):
"""
Returns a URI formatted representation of the host, including all
of it's attributes except for the name. Uses the
address, not the name of the host to build the URI.
:rtype: str
:return: A URI.
"""
url = Url()
url.protocol = self.get_protocol()
url.hostname = self.get_address()
url.port = self.get_tcp_port()
url.vars = dict((k, to_list(v))
for (k, v) in list(self.get_all().items())
if isinstance(v, str) or isinstance(v, list))
if self.account:
url.username = self.account.get_name()
url.password1 = self.account.get_password()
url.password2 = self.account.authorization_password
return str(url) | [
"def",
"get_uri",
"(",
"self",
")",
":",
"url",
"=",
"Url",
"(",
")",
"url",
".",
"protocol",
"=",
"self",
".",
"get_protocol",
"(",
")",
"url",
".",
"hostname",
"=",
"self",
".",
"get_address",
"(",
")",
"url",
".",
"port",
"=",
"self",
".",
"ge... | Returns a URI formatted representation of the host, including all
of it's attributes except for the name. Uses the
address, not the name of the host to build the URI.
:rtype: str
:return: A URI. | [
"Returns",
"a",
"URI",
"formatted",
"representation",
"of",
"the",
"host",
"including",
"all",
"of",
"it",
"s",
"attributes",
"except",
"for",
"the",
"name",
".",
"Uses",
"the",
"address",
"not",
"the",
"name",
"of",
"the",
"host",
"to",
"build",
"the",
... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L118-L140 | train | 213,151 |
knipknap/exscript | Exscript/host.py | Host.set_address | def set_address(self, address):
"""
Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param address: A hostname or IP name.
"""
if is_ip(address):
self.address = clean_ip(address)
else:
self.address = address | python | def set_address(self, address):
"""
Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param address: A hostname or IP name.
"""
if is_ip(address):
self.address = clean_ip(address)
else:
self.address = address | [
"def",
"set_address",
"(",
"self",
",",
"address",
")",
":",
"if",
"is_ip",
"(",
"address",
")",
":",
"self",
".",
"address",
"=",
"clean_ip",
"(",
"address",
")",
"else",
":",
"self",
".",
"address",
"=",
"address"
] | Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param address: A hostname or IP name. | [
"Set",
"the",
"address",
"of",
"the",
"remote",
"host",
"the",
"is",
"contacted",
"without",
"changing",
"hostname",
"username",
"password",
"protocol",
"and",
"TCP",
"port",
"number",
".",
"This",
"is",
"the",
"actual",
"address",
"that",
"is",
"used",
"to"... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L179-L192 | train | 213,152 |
knipknap/exscript | Exscript/host.py | Host.get_option | def get_option(self, name, default=None):
"""
Returns the value of the given option if it is defined, returns
the given default value otherwise.
:type name: str
:param name: The option name.
:type default: object
:param default: A default value.
"""
if self.options is None:
return default
return self.options.get(name, default) | python | def get_option(self, name, default=None):
"""
Returns the value of the given option if it is defined, returns
the given default value otherwise.
:type name: str
:param name: The option name.
:type default: object
:param default: A default value.
"""
if self.options is None:
return default
return self.options.get(name, default) | [
"def",
"get_option",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"self",
".",
"options",
"is",
"None",
":",
"return",
"default",
"return",
"self",
".",
"options",
".",
"get",
"(",
"name",
",",
"default",
")"
] | Returns the value of the given option if it is defined, returns
the given default value otherwise.
:type name: str
:param name: The option name.
:type default: object
:param default: A default value. | [
"Returns",
"the",
"value",
"of",
"the",
"given",
"option",
"if",
"it",
"is",
"defined",
"returns",
"the",
"given",
"default",
"value",
"otherwise",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L253-L265 | train | 213,153 |
knipknap/exscript | Exscript/host.py | Host.set_tcp_port | def set_tcp_port(self, tcp_port):
"""
Defines the TCP port number.
:type tcp_port: int
:param tcp_port: The TCP port number.
"""
if tcp_port is None:
self.tcp_port = None
return
self.tcp_port = int(tcp_port) | python | def set_tcp_port(self, tcp_port):
"""
Defines the TCP port number.
:type tcp_port: int
:param tcp_port: The TCP port number.
"""
if tcp_port is None:
self.tcp_port = None
return
self.tcp_port = int(tcp_port) | [
"def",
"set_tcp_port",
"(",
"self",
",",
"tcp_port",
")",
":",
"if",
"tcp_port",
"is",
"None",
":",
"self",
".",
"tcp_port",
"=",
"None",
"return",
"self",
".",
"tcp_port",
"=",
"int",
"(",
"tcp_port",
")"
] | Defines the TCP port number.
:type tcp_port: int
:param tcp_port: The TCP port number. | [
"Defines",
"the",
"TCP",
"port",
"number",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L278-L288 | train | 213,154 |
knipknap/exscript | Exscript/host.py | Host.append | def append(self, name, value):
"""
Appends the given value to the list variable with the given name.
:type name: string
:param name: The name of the variable.
:type value: object
:param value: The appended value.
"""
if self.vars is None:
self.vars = {}
if name in self.vars:
self.vars[name].append(value)
else:
self.vars[name] = [value] | python | def append(self, name, value):
"""
Appends the given value to the list variable with the given name.
:type name: string
:param name: The name of the variable.
:type value: object
:param value: The appended value.
"""
if self.vars is None:
self.vars = {}
if name in self.vars:
self.vars[name].append(value)
else:
self.vars[name] = [value] | [
"def",
"append",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"self",
".",
"vars",
"is",
"None",
":",
"self",
".",
"vars",
"=",
"{",
"}",
"if",
"name",
"in",
"self",
".",
"vars",
":",
"self",
".",
"vars",
"[",
"name",
"]",
".",
"ap... | Appends the given value to the list variable with the given name.
:type name: string
:param name: The name of the variable.
:type value: object
:param value: The appended value. | [
"Appends",
"the",
"given",
"value",
"to",
"the",
"list",
"variable",
"with",
"the",
"given",
"name",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L341-L355 | train | 213,155 |
knipknap/exscript | Exscript/host.py | Host.get | def get(self, name, default=None):
"""
Returns the value of the given variable, or the given default
value if the variable is not defined.
:type name: string
:param name: The name of the variable.
:type default: object
:param default: The default value.
:rtype: object
:return: The value of the variable.
"""
if self.vars is None:
return default
return self.vars.get(name, default) | python | def get(self, name, default=None):
"""
Returns the value of the given variable, or the given default
value if the variable is not defined.
:type name: string
:param name: The name of the variable.
:type default: object
:param default: The default value.
:rtype: object
:return: The value of the variable.
"""
if self.vars is None:
return default
return self.vars.get(name, default) | [
"def",
"get",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"self",
".",
"vars",
"is",
"None",
":",
"return",
"default",
"return",
"self",
".",
"vars",
".",
"get",
"(",
"name",
",",
"default",
")"
] | Returns the value of the given variable, or the given default
value if the variable is not defined.
:type name: string
:param name: The name of the variable.
:type default: object
:param default: The default value.
:rtype: object
:return: The value of the variable. | [
"Returns",
"the",
"value",
"of",
"the",
"given",
"variable",
"or",
"the",
"given",
"default",
"value",
"if",
"the",
"variable",
"is",
"not",
"defined",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/host.py#L386-L400 | train | 213,156 |
knipknap/exscript | Exscript/util/impl.py | copy_labels | def copy_labels(src, dst):
"""
Copies all labels of one object to another object.
:type src: object
:param src: The object to check read the labels from.
:type dst: object
:param dst: The object into which the labels are copied.
"""
labels = src.__dict__.get('_labels')
if labels is None:
return
dst.__dict__['_labels'] = labels.copy() | python | def copy_labels(src, dst):
"""
Copies all labels of one object to another object.
:type src: object
:param src: The object to check read the labels from.
:type dst: object
:param dst: The object into which the labels are copied.
"""
labels = src.__dict__.get('_labels')
if labels is None:
return
dst.__dict__['_labels'] = labels.copy() | [
"def",
"copy_labels",
"(",
"src",
",",
"dst",
")",
":",
"labels",
"=",
"src",
".",
"__dict__",
".",
"get",
"(",
"'_labels'",
")",
"if",
"labels",
"is",
"None",
":",
"return",
"dst",
".",
"__dict__",
"[",
"'_labels'",
"]",
"=",
"labels",
".",
"copy",
... | Copies all labels of one object to another object.
:type src: object
:param src: The object to check read the labels from.
:type dst: object
:param dst: The object into which the labels are copied. | [
"Copies",
"all",
"labels",
"of",
"one",
"object",
"to",
"another",
"object",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/impl.py#L70-L82 | train | 213,157 |
knipknap/exscript | Exscript/util/impl.py | serializeable_exc_info | def serializeable_exc_info(thetype, ex, tb):
"""
Since traceback objects can not be pickled, this function manipulates
exception info tuples before they are passed accross process
boundaries.
"""
return thetype, ex, ''.join(traceback.format_exception(thetype, ex, tb)) | python | def serializeable_exc_info(thetype, ex, tb):
"""
Since traceback objects can not be pickled, this function manipulates
exception info tuples before they are passed accross process
boundaries.
"""
return thetype, ex, ''.join(traceback.format_exception(thetype, ex, tb)) | [
"def",
"serializeable_exc_info",
"(",
"thetype",
",",
"ex",
",",
"tb",
")",
":",
"return",
"thetype",
",",
"ex",
",",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"thetype",
",",
"ex",
",",
"tb",
")",
")"
] | Since traceback objects can not be pickled, this function manipulates
exception info tuples before they are passed accross process
boundaries. | [
"Since",
"traceback",
"objects",
"can",
"not",
"be",
"pickled",
"this",
"function",
"manipulates",
"exception",
"info",
"tuples",
"before",
"they",
"are",
"passed",
"accross",
"process",
"boundaries",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/impl.py#L85-L91 | train | 213,158 |
knipknap/exscript | Exscript/util/impl.py | deprecated | def deprecated(func):
"""
A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used.
"""
def decorated(*args, **kwargs):
warnings.warn('Call to deprecated function %s.' % func.__name__,
category=DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
decorated.__name__ = func.__name__
decorated.__doc__ = func.__doc__
decorated.__dict__.update(func.__dict__)
return decorated | python | def deprecated(func):
"""
A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used.
"""
def decorated(*args, **kwargs):
warnings.warn('Call to deprecated function %s.' % func.__name__,
category=DeprecationWarning,
stacklevel=2)
return func(*args, **kwargs)
decorated.__name__ = func.__name__
decorated.__doc__ = func.__doc__
decorated.__dict__.update(func.__dict__)
return decorated | [
"def",
"deprecated",
"(",
"func",
")",
":",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'Call to deprecated function %s.'",
"%",
"func",
".",
"__name__",
",",
"category",
"=",
"DeprecationWarning",
... | A decorator for marking functions as deprecated. Results in
a printed warning message when the function is used. | [
"A",
"decorator",
"for",
"marking",
"functions",
"as",
"deprecated",
".",
"Results",
"in",
"a",
"printed",
"warning",
"message",
"when",
"the",
"function",
"is",
"used",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/impl.py#L129-L142 | train | 213,159 |
knipknap/exscript | Exscript/util/impl.py | synchronized | def synchronized(func):
"""
Decorator for synchronizing method access.
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
except AttributeError:
from multiprocessing import RLock
rlock = self.__dict__.setdefault('_sync_lock', RLock())
with rlock:
return func(self, *args, **kwargs)
return wrapped | python | def synchronized(func):
"""
Decorator for synchronizing method access.
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
except AttributeError:
from multiprocessing import RLock
rlock = self.__dict__.setdefault('_sync_lock', RLock())
with rlock:
return func(self, *args, **kwargs)
return wrapped | [
"def",
"synchronized",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"rlock",
"=",
"self",
".",
"_sync_lock",
"except",
"AttributeError",
":",
... | Decorator for synchronizing method access. | [
"Decorator",
"for",
"synchronizing",
"method",
"access",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/impl.py#L145-L158 | train | 213,160 |
knipknap/exscript | Exscript/util/impl.py | debug | def debug(func):
"""
Decorator that prints a message whenever a function is entered or left.
"""
@wraps(func)
def wrapped(*args, **kwargs):
arg = repr(args) + ' ' + repr(kwargs)
sys.stdout.write('Entering ' + func.__name__ + arg + '\n')
try:
result = func(*args, **kwargs)
except:
sys.stdout.write('Traceback caught:\n')
sys.stdout.write(format_exception(*sys.exc_info()))
raise
arg = repr(result)
sys.stdout.write('Leaving ' + func.__name__ + '(): ' + arg + '\n')
return result
return wrapped | python | def debug(func):
"""
Decorator that prints a message whenever a function is entered or left.
"""
@wraps(func)
def wrapped(*args, **kwargs):
arg = repr(args) + ' ' + repr(kwargs)
sys.stdout.write('Entering ' + func.__name__ + arg + '\n')
try:
result = func(*args, **kwargs)
except:
sys.stdout.write('Traceback caught:\n')
sys.stdout.write(format_exception(*sys.exc_info()))
raise
arg = repr(result)
sys.stdout.write('Leaving ' + func.__name__ + '(): ' + arg + '\n')
return result
return wrapped | [
"def",
"debug",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"arg",
"=",
"repr",
"(",
"args",
")",
"+",
"' '",
"+",
"repr",
"(",
"kwargs",
")",
"sys",
".",
"stdo... | Decorator that prints a message whenever a function is entered or left. | [
"Decorator",
"that",
"prints",
"a",
"message",
"whenever",
"a",
"function",
"is",
"entered",
"or",
"left",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/impl.py#L161-L178 | train | 213,161 |
knipknap/exscript | Exscript/util/template.py | eval | def eval(conn, string, strip_command=True, **kwargs):
"""
Compiles the given template and executes it on the given
connection.
Raises an exception if the compilation fails.
if strip_command is True, the first line of each response that is
received after any command sent by the template is stripped. For
example, consider the following template::
ls -1{extract /(\S+)/ as filenames}
{loop filenames as filename}
touch $filename
{end}
If strip_command is False, the response, (and hence, the `filenames'
variable) contains the following::
ls -1
myfile
myfile2
[...]
By setting strip_command to True, the first line is ommitted.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type string: string
:param string: The template to compile.
:type strip_command: bool
:param strip_command: Whether to strip the command echo from the response.
:type kwargs: dict
:param kwargs: Variables to define in the template.
:rtype: dict
:return: The variables that are defined after execution of the script.
"""
parser_args = {'strip_command': strip_command}
return _run(conn, None, string, parser_args, **kwargs) | python | def eval(conn, string, strip_command=True, **kwargs):
"""
Compiles the given template and executes it on the given
connection.
Raises an exception if the compilation fails.
if strip_command is True, the first line of each response that is
received after any command sent by the template is stripped. For
example, consider the following template::
ls -1{extract /(\S+)/ as filenames}
{loop filenames as filename}
touch $filename
{end}
If strip_command is False, the response, (and hence, the `filenames'
variable) contains the following::
ls -1
myfile
myfile2
[...]
By setting strip_command to True, the first line is ommitted.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type string: string
:param string: The template to compile.
:type strip_command: bool
:param strip_command: Whether to strip the command echo from the response.
:type kwargs: dict
:param kwargs: Variables to define in the template.
:rtype: dict
:return: The variables that are defined after execution of the script.
"""
parser_args = {'strip_command': strip_command}
return _run(conn, None, string, parser_args, **kwargs) | [
"def",
"eval",
"(",
"conn",
",",
"string",
",",
"strip_command",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"parser_args",
"=",
"{",
"'strip_command'",
":",
"strip_command",
"}",
"return",
"_run",
"(",
"conn",
",",
"None",
",",
"string",
",",
"par... | Compiles the given template and executes it on the given
connection.
Raises an exception if the compilation fails.
if strip_command is True, the first line of each response that is
received after any command sent by the template is stripped. For
example, consider the following template::
ls -1{extract /(\S+)/ as filenames}
{loop filenames as filename}
touch $filename
{end}
If strip_command is False, the response, (and hence, the `filenames'
variable) contains the following::
ls -1
myfile
myfile2
[...]
By setting strip_command to True, the first line is ommitted.
:type conn: Exscript.protocols.Protocol
:param conn: The connection on which to run the template.
:type string: string
:param string: The template to compile.
:type strip_command: bool
:param strip_command: Whether to strip the command echo from the response.
:type kwargs: dict
:param kwargs: Variables to define in the template.
:rtype: dict
:return: The variables that are defined after execution of the script. | [
"Compiles",
"the",
"given",
"template",
"and",
"executes",
"it",
"on",
"the",
"given",
"connection",
".",
"Raises",
"an",
"exception",
"if",
"the",
"compilation",
"fails",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/template.py#L104-L141 | train | 213,162 |
knipknap/exscript | Exscript/util/url.py | _urlparse_qs | def _urlparse_qs(url):
"""
Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param url: URL with query string to be parsed
"""
# Extract the query part from the URL.
querystring = urlparse(url)[4]
# Split the query into name/value pairs.
pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')]
# Split the name/value pairs.
result = OrderedDefaultDict(list)
for name_value in pairs:
pair = name_value.split('=', 1)
if len(pair) != 2:
continue
if len(pair[1]) > 0:
name = _unquote(pair[0].replace('+', ' '))
value = _unquote(pair[1].replace('+', ' '))
result[name].append(value)
return result | python | def _urlparse_qs(url):
"""
Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param url: URL with query string to be parsed
"""
# Extract the query part from the URL.
querystring = urlparse(url)[4]
# Split the query into name/value pairs.
pairs = [s2 for s1 in querystring.split('&') for s2 in s1.split(';')]
# Split the name/value pairs.
result = OrderedDefaultDict(list)
for name_value in pairs:
pair = name_value.split('=', 1)
if len(pair) != 2:
continue
if len(pair[1]) > 0:
name = _unquote(pair[0].replace('+', ' '))
value = _unquote(pair[1].replace('+', ' '))
result[name].append(value)
return result | [
"def",
"_urlparse_qs",
"(",
"url",
")",
":",
"# Extract the query part from the URL.",
"querystring",
"=",
"urlparse",
"(",
"url",
")",
"[",
"4",
"]",
"# Split the query into name/value pairs.",
"pairs",
"=",
"[",
"s2",
"for",
"s1",
"in",
"querystring",
".",
"spli... | Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param url: URL with query string to be parsed | [
"Parse",
"a",
"URL",
"query",
"string",
"and",
"return",
"the",
"components",
"as",
"a",
"dictionary",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/url.py#L72-L103 | train | 213,163 |
knipknap/exscript | Exscript/workqueue/workqueue.py | WorkQueue.set_debug | def set_debug(self, debug=1):
"""
Set the debug level.
:type debug: int
:param debug: The debug level.
"""
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug | python | def set_debug(self, debug=1):
"""
Set the debug level.
:type debug: int
:param debug: The debug level.
"""
self._check_if_ready()
self.debug = debug
self.main_loop.debug = debug | [
"def",
"set_debug",
"(",
"self",
",",
"debug",
"=",
"1",
")",
":",
"self",
".",
"_check_if_ready",
"(",
")",
"self",
".",
"debug",
"=",
"debug",
"self",
".",
"main_loop",
".",
"debug",
"=",
"debug"
] | Set the debug level.
:type debug: int
:param debug: The debug level. | [
"Set",
"the",
"debug",
"level",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/workqueue/workqueue.py#L87-L96 | train | 213,164 |
knipknap/exscript | Exscript/workqueue/workqueue.py | WorkQueue.set_max_threads | def set_max_threads(self, max_threads):
"""
Set the maximum number of concurrent threads.
:type max_threads: int
:param max_threads: The number of threads.
"""
if max_threads is None:
raise TypeError('max_threads must not be None.')
self._check_if_ready()
self.collection.set_max_working(max_threads) | python | def set_max_threads(self, max_threads):
"""
Set the maximum number of concurrent threads.
:type max_threads: int
:param max_threads: The number of threads.
"""
if max_threads is None:
raise TypeError('max_threads must not be None.')
self._check_if_ready()
self.collection.set_max_working(max_threads) | [
"def",
"set_max_threads",
"(",
"self",
",",
"max_threads",
")",
":",
"if",
"max_threads",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'max_threads must not be None.'",
")",
"self",
".",
"_check_if_ready",
"(",
")",
"self",
".",
"collection",
".",
"set_max_wor... | Set the maximum number of concurrent threads.
:type max_threads: int
:param max_threads: The number of threads. | [
"Set",
"the",
"maximum",
"number",
"of",
"concurrent",
"threads",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/workqueue/workqueue.py#L108-L118 | train | 213,165 |
knipknap/exscript | Exscript/stdlib/connection.py | authorize | def authorize(scope, password=[None]):
"""
Looks for a password prompt on the current connection
and enters the given password.
If a password is not given, the function uses the same
password that was used at the last login attempt; it is
an error if no such attempt was made before.
:type password: string
:param password: A password.
"""
conn = scope.get('__connection__')
password = password[0]
if password is None:
conn.app_authorize()
else:
account = Account('', password)
conn.app_authorize(account)
return True | python | def authorize(scope, password=[None]):
"""
Looks for a password prompt on the current connection
and enters the given password.
If a password is not given, the function uses the same
password that was used at the last login attempt; it is
an error if no such attempt was made before.
:type password: string
:param password: A password.
"""
conn = scope.get('__connection__')
password = password[0]
if password is None:
conn.app_authorize()
else:
account = Account('', password)
conn.app_authorize(account)
return True | [
"def",
"authorize",
"(",
"scope",
",",
"password",
"=",
"[",
"None",
"]",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"password",
"=",
"password",
"[",
"0",
"]",
"if",
"password",
"is",
"None",
":",
"conn",
".",
"app_aut... | Looks for a password prompt on the current connection
and enters the given password.
If a password is not given, the function uses the same
password that was used at the last login attempt; it is
an error if no such attempt was made before.
:type password: string
:param password: A password. | [
"Looks",
"for",
"a",
"password",
"prompt",
"on",
"the",
"current",
"connection",
"and",
"enters",
"the",
"given",
"password",
".",
"If",
"a",
"password",
"is",
"not",
"given",
"the",
"function",
"uses",
"the",
"same",
"password",
"that",
"was",
"used",
"at... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L61-L79 | train | 213,166 |
knipknap/exscript | Exscript/stdlib/connection.py | close | def close(scope):
"""
Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed.
"""
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
return True | python | def close(scope):
"""
Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed.
"""
conn = scope.get('__connection__')
conn.close(1)
scope.define(__response__=conn.response)
return True | [
"def",
"close",
"(",
"scope",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"conn",
".",
"close",
"(",
"1",
")",
"scope",
".",
"define",
"(",
"__response__",
"=",
"conn",
".",
"response",
")",
"return",
"True"
] | Closes the existing connection with the remote host. This function is
rarely used, as normally Exscript closes the connection automatically
when the script has completed. | [
"Closes",
"the",
"existing",
"connection",
"with",
"the",
"remote",
"host",
".",
"This",
"function",
"is",
"rarely",
"used",
"as",
"normally",
"Exscript",
"closes",
"the",
"connection",
"automatically",
"when",
"the",
"script",
"has",
"completed",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L124-L133 | train | 213,167 |
knipknap/exscript | Exscript/stdlib/connection.py | exec_ | def exec_(scope, data):
"""
Sends the given data to the remote host and waits until the host
has responded with a prompt.
If the given data is a list of strings, each item is sent, and
after each item a prompt is expected.
This function also causes the response of the command to be stored
in the built-in __response__ variable.
:type data: string
:param data: The data that is sent.
"""
conn = scope.get('__connection__')
response = []
for line in data:
conn.send(line)
conn.expect_prompt()
response += conn.response.split('\n')[1:]
scope.define(__response__=response)
return True | python | def exec_(scope, data):
"""
Sends the given data to the remote host and waits until the host
has responded with a prompt.
If the given data is a list of strings, each item is sent, and
after each item a prompt is expected.
This function also causes the response of the command to be stored
in the built-in __response__ variable.
:type data: string
:param data: The data that is sent.
"""
conn = scope.get('__connection__')
response = []
for line in data:
conn.send(line)
conn.expect_prompt()
response += conn.response.split('\n')[1:]
scope.define(__response__=response)
return True | [
"def",
"exec_",
"(",
"scope",
",",
"data",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"response",
"=",
"[",
"]",
"for",
"line",
"in",
"data",
":",
"conn",
".",
"send",
"(",
"line",
")",
"conn",
".",
"expect_prompt",
"... | Sends the given data to the remote host and waits until the host
has responded with a prompt.
If the given data is a list of strings, each item is sent, and
after each item a prompt is expected.
This function also causes the response of the command to be stored
in the built-in __response__ variable.
:type data: string
:param data: The data that is sent. | [
"Sends",
"the",
"given",
"data",
"to",
"the",
"remote",
"host",
"and",
"waits",
"until",
"the",
"host",
"has",
"responded",
"with",
"a",
"prompt",
".",
"If",
"the",
"given",
"data",
"is",
"a",
"list",
"of",
"strings",
"each",
"item",
"is",
"sent",
"and... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L137-L157 | train | 213,168 |
knipknap/exscript | Exscript/stdlib/connection.py | wait_for | def wait_for(scope, prompt):
"""
Waits until the response of the remote host contains the given pattern.
:type prompt: regex
:param prompt: The prompt pattern.
"""
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True | python | def wait_for(scope, prompt):
"""
Waits until the response of the remote host contains the given pattern.
:type prompt: regex
:param prompt: The prompt pattern.
"""
conn = scope.get('__connection__')
conn.expect(prompt)
scope.define(__response__=conn.response)
return True | [
"def",
"wait_for",
"(",
"scope",
",",
"prompt",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"conn",
".",
"expect",
"(",
"prompt",
")",
"scope",
".",
"define",
"(",
"__response__",
"=",
"conn",
".",
"response",
")",
"return... | Waits until the response of the remote host contains the given pattern.
:type prompt: regex
:param prompt: The prompt pattern. | [
"Waits",
"until",
"the",
"response",
"of",
"the",
"remote",
"host",
"contains",
"the",
"given",
"pattern",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L225-L235 | train | 213,169 |
knipknap/exscript | Exscript/stdlib/connection.py | set_prompt | def set_prompt(scope, prompt=None):
"""
Defines the pattern that is recognized at any future time when Exscript
needs to wait for a prompt.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and continues as soon as the
pattern is found.
Exscript waits for a prompt whenever it sends a command (unless the send()
method was used). set_prompt() redefines as to what is recognized as a
prompt.
:type prompt: regex
:param prompt: The prompt pattern.
"""
conn = scope.get('__connection__')
conn.set_prompt(prompt)
return True | python | def set_prompt(scope, prompt=None):
"""
Defines the pattern that is recognized at any future time when Exscript
needs to wait for a prompt.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and continues as soon as the
pattern is found.
Exscript waits for a prompt whenever it sends a command (unless the send()
method was used). set_prompt() redefines as to what is recognized as a
prompt.
:type prompt: regex
:param prompt: The prompt pattern.
"""
conn = scope.get('__connection__')
conn.set_prompt(prompt)
return True | [
"def",
"set_prompt",
"(",
"scope",
",",
"prompt",
"=",
"None",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"conn",
".",
"set_prompt",
"(",
"prompt",
")",
"return",
"True"
] | Defines the pattern that is recognized at any future time when Exscript
needs to wait for a prompt.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and continues as soon as the
pattern is found.
Exscript waits for a prompt whenever it sends a command (unless the send()
method was used). set_prompt() redefines as to what is recognized as a
prompt.
:type prompt: regex
:param prompt: The prompt pattern. | [
"Defines",
"the",
"pattern",
"that",
"is",
"recognized",
"at",
"any",
"future",
"time",
"when",
"Exscript",
"needs",
"to",
"wait",
"for",
"a",
"prompt",
".",
"In",
"other",
"words",
"whenever",
"Exscript",
"waits",
"for",
"a",
"prompt",
"it",
"searches",
"... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L239-L256 | train | 213,170 |
knipknap/exscript | Exscript/stdlib/connection.py | set_error | def set_error(scope, error_re=None):
"""
Defines a pattern that, whenever detected in the response of the remote
host, causes an error to be raised.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and raises an error if the
pattern is found.
:type error_re: regex
:param error_re: The error pattern.
"""
conn = scope.get('__connection__')
conn.set_error_prompt(error_re)
return True | python | def set_error(scope, error_re=None):
"""
Defines a pattern that, whenever detected in the response of the remote
host, causes an error to be raised.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and raises an error if the
pattern is found.
:type error_re: regex
:param error_re: The error pattern.
"""
conn = scope.get('__connection__')
conn.set_error_prompt(error_re)
return True | [
"def",
"set_error",
"(",
"scope",
",",
"error_re",
"=",
"None",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"conn",
".",
"set_error_prompt",
"(",
"error_re",
")",
"return",
"True"
] | Defines a pattern that, whenever detected in the response of the remote
host, causes an error to be raised.
In other words, whenever Exscript waits for a prompt, it searches the
response of the host for the given pattern and raises an error if the
pattern is found.
:type error_re: regex
:param error_re: The error pattern. | [
"Defines",
"a",
"pattern",
"that",
"whenever",
"detected",
"in",
"the",
"response",
"of",
"the",
"remote",
"host",
"causes",
"an",
"error",
"to",
"be",
"raised",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L260-L274 | train | 213,171 |
knipknap/exscript | Exscript/stdlib/connection.py | set_timeout | def set_timeout(scope, timeout):
"""
Defines the time after which Exscript fails if it does not receive a
prompt from the remote host.
:type timeout: int
:param timeout: The timeout in seconds.
"""
conn = scope.get('__connection__')
conn.set_timeout(int(timeout[0]))
return True | python | def set_timeout(scope, timeout):
"""
Defines the time after which Exscript fails if it does not receive a
prompt from the remote host.
:type timeout: int
:param timeout: The timeout in seconds.
"""
conn = scope.get('__connection__')
conn.set_timeout(int(timeout[0]))
return True | [
"def",
"set_timeout",
"(",
"scope",
",",
"timeout",
")",
":",
"conn",
"=",
"scope",
".",
"get",
"(",
"'__connection__'",
")",
"conn",
".",
"set_timeout",
"(",
"int",
"(",
"timeout",
"[",
"0",
"]",
")",
")",
"return",
"True"
] | Defines the time after which Exscript fails if it does not receive a
prompt from the remote host.
:type timeout: int
:param timeout: The timeout in seconds. | [
"Defines",
"the",
"time",
"after",
"which",
"Exscript",
"fails",
"if",
"it",
"does",
"not",
"receive",
"a",
"prompt",
"from",
"the",
"remote",
"host",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/stdlib/connection.py#L278-L288 | train | 213,172 |
knipknap/exscript | Exscript/emulators/vdevice.py | VirtualDevice.add_command | def add_command(self, command, handler, prompt=True):
"""
Registers a command.
The command may be either a string (which is then automatically
compiled into a regular expression), or a pre-compiled regular
expression object.
If the given response handler is a string, it is sent as the
response to any command that matches the given regular expression.
If the given response handler is a function, it is called
with the command passed as an argument.
:type command: str|regex
:param command: A string or a compiled regular expression.
:type handler: function|str
:param handler: A string, or a response handler.
:type prompt: bool
:param prompt: Whether to show a prompt after completing the command.
"""
if prompt:
thehandler = self._create_autoprompt_handler(handler)
else:
thehandler = handler
self.commands.add(command, thehandler) | python | def add_command(self, command, handler, prompt=True):
"""
Registers a command.
The command may be either a string (which is then automatically
compiled into a regular expression), or a pre-compiled regular
expression object.
If the given response handler is a string, it is sent as the
response to any command that matches the given regular expression.
If the given response handler is a function, it is called
with the command passed as an argument.
:type command: str|regex
:param command: A string or a compiled regular expression.
:type handler: function|str
:param handler: A string, or a response handler.
:type prompt: bool
:param prompt: Whether to show a prompt after completing the command.
"""
if prompt:
thehandler = self._create_autoprompt_handler(handler)
else:
thehandler = handler
self.commands.add(command, thehandler) | [
"def",
"add_command",
"(",
"self",
",",
"command",
",",
"handler",
",",
"prompt",
"=",
"True",
")",
":",
"if",
"prompt",
":",
"thehandler",
"=",
"self",
".",
"_create_autoprompt_handler",
"(",
"handler",
")",
"else",
":",
"thehandler",
"=",
"handler",
"sel... | Registers a command.
The command may be either a string (which is then automatically
compiled into a regular expression), or a pre-compiled regular
expression object.
If the given response handler is a string, it is sent as the
response to any command that matches the given regular expression.
If the given response handler is a function, it is called
with the command passed as an argument.
:type command: str|regex
:param command: A string or a compiled regular expression.
:type handler: function|str
:param handler: A string, or a response handler.
:type prompt: bool
:param prompt: Whether to show a prompt after completing the command. | [
"Registers",
"a",
"command",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/emulators/vdevice.py#L118-L142 | train | 213,173 |
knipknap/exscript | Exscript/emulators/vdevice.py | VirtualDevice.add_commands_from_file | def add_commands_from_file(self, filename, autoprompt=True):
"""
Wrapper around add_command_handler that reads the handlers from the
file with the given name. The file is a Python script containing
a list named 'commands' of tuples that map command names to
handlers.
:type filename: str
:param filename: The name of the file containing the tuples.
:type autoprompt: bool
:param autoprompt: Whether to append a prompt to each response.
"""
if autoprompt:
deco = self._create_autoprompt_handler
else:
deco = None
self.commands.add_from_file(filename, deco) | python | def add_commands_from_file(self, filename, autoprompt=True):
"""
Wrapper around add_command_handler that reads the handlers from the
file with the given name. The file is a Python script containing
a list named 'commands' of tuples that map command names to
handlers.
:type filename: str
:param filename: The name of the file containing the tuples.
:type autoprompt: bool
:param autoprompt: Whether to append a prompt to each response.
"""
if autoprompt:
deco = self._create_autoprompt_handler
else:
deco = None
self.commands.add_from_file(filename, deco) | [
"def",
"add_commands_from_file",
"(",
"self",
",",
"filename",
",",
"autoprompt",
"=",
"True",
")",
":",
"if",
"autoprompt",
":",
"deco",
"=",
"self",
".",
"_create_autoprompt_handler",
"else",
":",
"deco",
"=",
"None",
"self",
".",
"commands",
".",
"add_fro... | Wrapper around add_command_handler that reads the handlers from the
file with the given name. The file is a Python script containing
a list named 'commands' of tuples that map command names to
handlers.
:type filename: str
:param filename: The name of the file containing the tuples.
:type autoprompt: bool
:param autoprompt: Whether to append a prompt to each response. | [
"Wrapper",
"around",
"add_command_handler",
"that",
"reads",
"the",
"handlers",
"from",
"the",
"file",
"with",
"the",
"given",
"name",
".",
"The",
"file",
"is",
"a",
"Python",
"script",
"containing",
"a",
"list",
"named",
"commands",
"of",
"tuples",
"that",
... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/emulators/vdevice.py#L144-L160 | train | 213,174 |
knipknap/exscript | Exscript/emulators/vdevice.py | VirtualDevice.init | def init(self):
"""
Init or reset the virtual device.
:rtype: str
:return: The initial response of the virtual device.
"""
self.logged_in = False
if self.login_type == self.LOGIN_TYPE_PASSWORDONLY:
self.prompt_stage = self.PROMPT_STAGE_PASSWORD
elif self.login_type == self.LOGIN_TYPE_NONE:
self.prompt_stage = self.PROMPT_STAGE_CUSTOM
else:
self.prompt_stage = self.PROMPT_STAGE_USERNAME
return self.banner + self._get_prompt() | python | def init(self):
"""
Init or reset the virtual device.
:rtype: str
:return: The initial response of the virtual device.
"""
self.logged_in = False
if self.login_type == self.LOGIN_TYPE_PASSWORDONLY:
self.prompt_stage = self.PROMPT_STAGE_PASSWORD
elif self.login_type == self.LOGIN_TYPE_NONE:
self.prompt_stage = self.PROMPT_STAGE_CUSTOM
else:
self.prompt_stage = self.PROMPT_STAGE_USERNAME
return self.banner + self._get_prompt() | [
"def",
"init",
"(",
"self",
")",
":",
"self",
".",
"logged_in",
"=",
"False",
"if",
"self",
".",
"login_type",
"==",
"self",
".",
"LOGIN_TYPE_PASSWORDONLY",
":",
"self",
".",
"prompt_stage",
"=",
"self",
".",
"PROMPT_STAGE_PASSWORD",
"elif",
"self",
".",
"... | Init or reset the virtual device.
:rtype: str
:return: The initial response of the virtual device. | [
"Init",
"or",
"reset",
"the",
"virtual",
"device",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/emulators/vdevice.py#L162-L178 | train | 213,175 |
knipknap/exscript | Exscript/emulators/vdevice.py | VirtualDevice.do | def do(self, command):
"""
"Executes" the given command on the virtual device, and returns
the response.
:type command: str
:param command: The command to be executed.
:rtype: str
:return: The response of the virtual device.
"""
echo = self.echo and command or ''
if not self.logged_in:
return echo + '\n' + self._get_prompt()
response = self.commands.eval(command)
if response is None:
return echo + '\n' + self._get_prompt()
return echo + response | python | def do(self, command):
"""
"Executes" the given command on the virtual device, and returns
the response.
:type command: str
:param command: The command to be executed.
:rtype: str
:return: The response of the virtual device.
"""
echo = self.echo and command or ''
if not self.logged_in:
return echo + '\n' + self._get_prompt()
response = self.commands.eval(command)
if response is None:
return echo + '\n' + self._get_prompt()
return echo + response | [
"def",
"do",
"(",
"self",
",",
"command",
")",
":",
"echo",
"=",
"self",
".",
"echo",
"and",
"command",
"or",
"''",
"if",
"not",
"self",
".",
"logged_in",
":",
"return",
"echo",
"+",
"'\\n'",
"+",
"self",
".",
"_get_prompt",
"(",
")",
"response",
"... | "Executes" the given command on the virtual device, and returns
the response.
:type command: str
:param command: The command to be executed.
:rtype: str
:return: The response of the virtual device. | [
"Executes",
"the",
"given",
"command",
"on",
"the",
"virtual",
"device",
"and",
"returns",
"the",
"response",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/emulators/vdevice.py#L180-L197 | train | 213,176 |
knipknap/exscript | Exscript/util/interact.py | get_user | def get_user(prompt=None):
"""
Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default one if None.
:rtype: string
:return: A username.
"""
# Read username and password.
try:
env_user = getpass.getuser()
except KeyError:
env_user = ''
if prompt is None:
prompt = "Please enter your user name"
if env_user is None or env_user == '':
user = input('%s: ' % prompt)
else:
user = input('%s [%s]: ' % (prompt, env_user))
if user == '':
user = env_user
return user | python | def get_user(prompt=None):
"""
Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default one if None.
:rtype: string
:return: A username.
"""
# Read username and password.
try:
env_user = getpass.getuser()
except KeyError:
env_user = ''
if prompt is None:
prompt = "Please enter your user name"
if env_user is None or env_user == '':
user = input('%s: ' % prompt)
else:
user = input('%s [%s]: ' % (prompt, env_user))
if user == '':
user = env_user
return user | [
"def",
"get_user",
"(",
"prompt",
"=",
"None",
")",
":",
"# Read username and password.",
"try",
":",
"env_user",
"=",
"getpass",
".",
"getuser",
"(",
")",
"except",
"KeyError",
":",
"env_user",
"=",
"''",
"if",
"prompt",
"is",
"None",
":",
"prompt",
"=",
... | Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default one if None.
:rtype: string
:return: A username. | [
"Prompts",
"the",
"user",
"for",
"his",
"login",
"name",
"defaulting",
"to",
"the",
"USER",
"environment",
"variable",
".",
"Returns",
"a",
"string",
"containing",
"the",
"username",
".",
"May",
"throw",
"an",
"exception",
"if",
"EOF",
"is",
"given",
"by",
... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/interact.py#L250-L274 | train | 213,177 |
knipknap/exscript | Exscript/util/interact.py | InputHistory.get | def get(self, key, default=None):
"""
Returns the input with the given key from the section that was
passed to the constructor. If either the section or the key
are not found, the default value is returned.
:type key: str
:param key: The key for which to return a value.
:type default: str|object
:param default: The default value that is returned.
:rtype: str|object
:return: The value from the config file, or the default.
"""
if not self.parser:
return default
try:
return self.parser.get(self.section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default | python | def get(self, key, default=None):
"""
Returns the input with the given key from the section that was
passed to the constructor. If either the section or the key
are not found, the default value is returned.
:type key: str
:param key: The key for which to return a value.
:type default: str|object
:param default: The default value that is returned.
:rtype: str|object
:return: The value from the config file, or the default.
"""
if not self.parser:
return default
try:
return self.parser.get(self.section, key)
except (configparser.NoSectionError, configparser.NoOptionError):
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"parser",
":",
"return",
"default",
"try",
":",
"return",
"self",
".",
"parser",
".",
"get",
"(",
"self",
".",
"section",
",",
"key",
")",
"ex... | Returns the input with the given key from the section that was
passed to the constructor. If either the section or the key
are not found, the default value is returned.
:type key: str
:param key: The key for which to return a value.
:type default: str|object
:param default: The default value that is returned.
:rtype: str|object
:return: The value from the config file, or the default. | [
"Returns",
"the",
"input",
"with",
"the",
"given",
"key",
"from",
"the",
"section",
"that",
"was",
"passed",
"to",
"the",
"constructor",
".",
"If",
"either",
"the",
"section",
"or",
"the",
"key",
"are",
"not",
"found",
"the",
"default",
"value",
"is",
"r... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/interact.py#L88-L106 | train | 213,178 |
knipknap/exscript | Exscript/util/interact.py | InputHistory.set | def set(self, key, value):
"""
Saves the input with the given key in the section that was
passed to the constructor. If either the section or the key
are not found, they are created.
Does nothing if the given value is None.
:type key: str
:param key: The key for which to define a value.
:type value: str|None
:param value: The value that is defined, or None.
:rtype: str|None
:return: The given value.
"""
if value is None:
return None
self.parser.set(self.section, key, value)
# Unfortunately ConfigParser attempts to write a string to the file
# object, and NamedTemporaryFile uses binary mode. So we nee to create
# the tempfile, and then re-open it.
with NamedTemporaryFile(delete=False) as tmpfile:
pass
with codecs.open(tmpfile.name, 'w', encoding='utf8') as fp:
self.parser.write(fp)
self.file.close()
shutil.move(tmpfile.name, self.file.name)
self.file = open(self.file.name)
return value | python | def set(self, key, value):
"""
Saves the input with the given key in the section that was
passed to the constructor. If either the section or the key
are not found, they are created.
Does nothing if the given value is None.
:type key: str
:param key: The key for which to define a value.
:type value: str|None
:param value: The value that is defined, or None.
:rtype: str|None
:return: The given value.
"""
if value is None:
return None
self.parser.set(self.section, key, value)
# Unfortunately ConfigParser attempts to write a string to the file
# object, and NamedTemporaryFile uses binary mode. So we nee to create
# the tempfile, and then re-open it.
with NamedTemporaryFile(delete=False) as tmpfile:
pass
with codecs.open(tmpfile.name, 'w', encoding='utf8') as fp:
self.parser.write(fp)
self.file.close()
shutil.move(tmpfile.name, self.file.name)
self.file = open(self.file.name)
return value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"self",
".",
"parser",
".",
"set",
"(",
"self",
".",
"section",
",",
"key",
",",
"value",
")",
"# Unfortunately ConfigParser attempts to wr... | Saves the input with the given key in the section that was
passed to the constructor. If either the section or the key
are not found, they are created.
Does nothing if the given value is None.
:type key: str
:param key: The key for which to define a value.
:type value: str|None
:param value: The value that is defined, or None.
:rtype: str|None
:return: The given value. | [
"Saves",
"the",
"input",
"with",
"the",
"given",
"key",
"in",
"the",
"section",
"that",
"was",
"passed",
"to",
"the",
"constructor",
".",
"If",
"either",
"the",
"section",
"or",
"the",
"key",
"are",
"not",
"found",
"they",
"are",
"created",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/interact.py#L108-L139 | train | 213,179 |
knipknap/exscript | Exscript/account.py | Account.acquire | def acquire(self, signal=True):
"""
Locks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the acquired_event signal.
"""
if not self.needs_lock:
return
with self.synclock:
while not self.lock.acquire(False):
self.synclock.wait()
if signal:
self.acquired_event(self)
self.synclock.notify_all() | python | def acquire(self, signal=True):
"""
Locks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the acquired_event signal.
"""
if not self.needs_lock:
return
with self.synclock:
while not self.lock.acquire(False):
self.synclock.wait()
if signal:
self.acquired_event(self)
self.synclock.notify_all() | [
"def",
"acquire",
"(",
"self",
",",
"signal",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"needs_lock",
":",
"return",
"with",
"self",
".",
"synclock",
":",
"while",
"not",
"self",
".",
"lock",
".",
"acquire",
"(",
"False",
")",
":",
"self",
"... | Locks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the acquired_event signal. | [
"Locks",
"the",
"account",
".",
"Method",
"has",
"no",
"effect",
"if",
"the",
"constructor",
"argument",
"needs_lock",
"wsa",
"set",
"to",
"False",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L105-L121 | train | 213,180 |
knipknap/exscript | Exscript/account.py | Account.release | def release(self, signal=True):
"""
Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal.
"""
if not self.needs_lock:
return
with self.synclock:
self.lock.release()
if signal:
self.released_event(self)
self.synclock.notify_all() | python | def release(self, signal=True):
"""
Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal.
"""
if not self.needs_lock:
return
with self.synclock:
self.lock.release()
if signal:
self.released_event(self)
self.synclock.notify_all() | [
"def",
"release",
"(",
"self",
",",
"signal",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"needs_lock",
":",
"return",
"with",
"self",
".",
"synclock",
":",
"self",
".",
"lock",
".",
"release",
"(",
")",
"if",
"signal",
":",
"self",
".",
"rele... | Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal. | [
"Unlocks",
"the",
"account",
".",
"Method",
"has",
"no",
"effect",
"if",
"the",
"constructor",
"argument",
"needs_lock",
"wsa",
"set",
"to",
"False",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L123-L138 | train | 213,181 |
knipknap/exscript | Exscript/account.py | Account.set_name | def set_name(self, name):
"""
Changes the name of the account.
:type name: string
:param name: The account name.
"""
self.name = name
self.changed_event.emit(self) | python | def set_name(self, name):
"""
Changes the name of the account.
:type name: string
:param name: The account name.
"""
self.name = name
self.changed_event.emit(self) | [
"def",
"set_name",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"changed_event",
".",
"emit",
"(",
"self",
")"
] | Changes the name of the account.
:type name: string
:param name: The account name. | [
"Changes",
"the",
"name",
"of",
"the",
"account",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L140-L148 | train | 213,182 |
knipknap/exscript | Exscript/account.py | Account.set_password | def set_password(self, password):
"""
Changes the password of the account.
:type password: string
:param password: The account password.
"""
self.password = password
self.changed_event.emit(self) | python | def set_password(self, password):
"""
Changes the password of the account.
:type password: string
:param password: The account password.
"""
self.password = password
self.changed_event.emit(self) | [
"def",
"set_password",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"password",
"=",
"password",
"self",
".",
"changed_event",
".",
"emit",
"(",
"self",
")"
] | Changes the password of the account.
:type password: string
:param password: The account password. | [
"Changes",
"the",
"password",
"of",
"the",
"account",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L159-L167 | train | 213,183 |
knipknap/exscript | Exscript/account.py | Account.set_authorization_password | def set_authorization_password(self, password):
"""
Changes the authorization password of the account.
:type password: string
:param password: The new authorization password.
"""
self.authorization_password = password
self.changed_event.emit(self) | python | def set_authorization_password(self, password):
"""
Changes the authorization password of the account.
:type password: string
:param password: The new authorization password.
"""
self.authorization_password = password
self.changed_event.emit(self) | [
"def",
"set_authorization_password",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"authorization_password",
"=",
"password",
"self",
".",
"changed_event",
".",
"emit",
"(",
"self",
")"
] | Changes the authorization password of the account.
:type password: string
:param password: The new authorization password. | [
"Changes",
"the",
"authorization",
"password",
"of",
"the",
"account",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L178-L186 | train | 213,184 |
knipknap/exscript | Exscript/account.py | AccountProxy.for_host | def for_host(parent, host):
"""
Returns a new AccountProxy that has an account acquired. The
account is chosen based on what the connected AccountManager
selects for the given host.
"""
account = AccountProxy(parent)
account.host = host
if account.acquire():
return account
return None | python | def for_host(parent, host):
"""
Returns a new AccountProxy that has an account acquired. The
account is chosen based on what the connected AccountManager
selects for the given host.
"""
account = AccountProxy(parent)
account.host = host
if account.acquire():
return account
return None | [
"def",
"for_host",
"(",
"parent",
",",
"host",
")",
":",
"account",
"=",
"AccountProxy",
"(",
"parent",
")",
"account",
".",
"host",
"=",
"host",
"if",
"account",
".",
"acquire",
"(",
")",
":",
"return",
"account",
"return",
"None"
] | Returns a new AccountProxy that has an account acquired. The
account is chosen based on what the connected AccountManager
selects for the given host. | [
"Returns",
"a",
"new",
"AccountProxy",
"that",
"has",
"an",
"account",
"acquired",
".",
"The",
"account",
"is",
"chosen",
"based",
"on",
"what",
"the",
"connected",
"AccountManager",
"selects",
"for",
"the",
"given",
"host",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L230-L240 | train | 213,185 |
knipknap/exscript | Exscript/account.py | AccountProxy.for_account_hash | def for_account_hash(parent, account_hash):
"""
Returns a new AccountProxy that acquires the account with the
given hash, if such an account is known to the account manager.
It is an error if the account manager does not have such an
account.
"""
account = AccountProxy(parent)
account.account_hash = account_hash
if account.acquire():
return account
return None | python | def for_account_hash(parent, account_hash):
"""
Returns a new AccountProxy that acquires the account with the
given hash, if such an account is known to the account manager.
It is an error if the account manager does not have such an
account.
"""
account = AccountProxy(parent)
account.account_hash = account_hash
if account.acquire():
return account
return None | [
"def",
"for_account_hash",
"(",
"parent",
",",
"account_hash",
")",
":",
"account",
"=",
"AccountProxy",
"(",
"parent",
")",
"account",
".",
"account_hash",
"=",
"account_hash",
"if",
"account",
".",
"acquire",
"(",
")",
":",
"return",
"account",
"return",
"... | Returns a new AccountProxy that acquires the account with the
given hash, if such an account is known to the account manager.
It is an error if the account manager does not have such an
account. | [
"Returns",
"a",
"new",
"AccountProxy",
"that",
"acquires",
"the",
"account",
"with",
"the",
"given",
"hash",
"if",
"such",
"an",
"account",
"is",
"known",
"to",
"the",
"account",
"manager",
".",
"It",
"is",
"an",
"error",
"if",
"the",
"account",
"manager",... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L243-L254 | train | 213,186 |
knipknap/exscript | Exscript/account.py | AccountProxy.acquire | def acquire(self):
"""
Locks the account. Returns True on success, False if the account
is thread-local and must not be locked.
"""
if self.host:
self.parent.send(('acquire-account-for-host', self.host))
elif self.account_hash:
self.parent.send(('acquire-account-from-hash', self.account_hash))
else:
self.parent.send(('acquire-account'))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response is None:
return False
self.account_hash, \
self.user, \
self.password, \
self.authorization_password, \
self.key = response
return True | python | def acquire(self):
"""
Locks the account. Returns True on success, False if the account
is thread-local and must not be locked.
"""
if self.host:
self.parent.send(('acquire-account-for-host', self.host))
elif self.account_hash:
self.parent.send(('acquire-account-from-hash', self.account_hash))
else:
self.parent.send(('acquire-account'))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response is None:
return False
self.account_hash, \
self.user, \
self.password, \
self.authorization_password, \
self.key = response
return True | [
"def",
"acquire",
"(",
"self",
")",
":",
"if",
"self",
".",
"host",
":",
"self",
".",
"parent",
".",
"send",
"(",
"(",
"'acquire-account-for-host'",
",",
"self",
".",
"host",
")",
")",
"elif",
"self",
".",
"account_hash",
":",
"self",
".",
"parent",
... | Locks the account. Returns True on success, False if the account
is thread-local and must not be locked. | [
"Locks",
"the",
"account",
".",
"Returns",
"True",
"on",
"success",
"False",
"if",
"the",
"account",
"is",
"thread",
"-",
"local",
"and",
"must",
"not",
"be",
"locked",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L291-L314 | train | 213,187 |
knipknap/exscript | Exscript/account.py | AccountProxy.release | def release(self):
"""
Unlocks the account.
"""
self.parent.send(('release-account', self.account_hash))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response != 'ok':
raise ValueError('unexpected response: ' + repr(response)) | python | def release(self):
"""
Unlocks the account.
"""
self.parent.send(('release-account', self.account_hash))
response = self.parent.recv()
if isinstance(response, Exception):
raise response
if response != 'ok':
raise ValueError('unexpected response: ' + repr(response)) | [
"def",
"release",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"send",
"(",
"(",
"'release-account'",
",",
"self",
".",
"account_hash",
")",
")",
"response",
"=",
"self",
".",
"parent",
".",
"recv",
"(",
")",
"if",
"isinstance",
"(",
"response",
... | Unlocks the account. | [
"Unlocks",
"the",
"account",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L316-L327 | train | 213,188 |
knipknap/exscript | Exscript/account.py | AccountPool.get_account_from_hash | def get_account_from_hash(self, account_hash):
"""
Returns the account with the given hash, or None if no such
account is included in the account pool.
"""
for account in self.accounts:
if account.__hash__() == account_hash:
return account
return None | python | def get_account_from_hash(self, account_hash):
"""
Returns the account with the given hash, or None if no such
account is included in the account pool.
"""
for account in self.accounts:
if account.__hash__() == account_hash:
return account
return None | [
"def",
"get_account_from_hash",
"(",
"self",
",",
"account_hash",
")",
":",
"for",
"account",
"in",
"self",
".",
"accounts",
":",
"if",
"account",
".",
"__hash__",
"(",
")",
"==",
"account_hash",
":",
"return",
"account",
"return",
"None"
] | Returns the account with the given hash, or None if no such
account is included in the account pool. | [
"Returns",
"the",
"account",
"with",
"the",
"given",
"hash",
"or",
"None",
"if",
"no",
"such",
"account",
"is",
"included",
"in",
"the",
"account",
"pool",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L447-L455 | train | 213,189 |
knipknap/exscript | Exscript/account.py | AccountPool.add_account | def add_account(self, accounts):
"""
Adds one or more account instances to the pool.
:type accounts: Account|list[Account]
:param accounts: The account to be added.
"""
with self.unlock_cond:
for account in to_list(accounts):
account.acquired_event.listen(self._on_account_acquired)
account.released_event.listen(self._on_account_released)
self.accounts.add(account)
self.unlocked_accounts.append(account)
self.unlock_cond.notify_all() | python | def add_account(self, accounts):
"""
Adds one or more account instances to the pool.
:type accounts: Account|list[Account]
:param accounts: The account to be added.
"""
with self.unlock_cond:
for account in to_list(accounts):
account.acquired_event.listen(self._on_account_acquired)
account.released_event.listen(self._on_account_released)
self.accounts.add(account)
self.unlocked_accounts.append(account)
self.unlock_cond.notify_all() | [
"def",
"add_account",
"(",
"self",
",",
"accounts",
")",
":",
"with",
"self",
".",
"unlock_cond",
":",
"for",
"account",
"in",
"to_list",
"(",
"accounts",
")",
":",
"account",
".",
"acquired_event",
".",
"listen",
"(",
"self",
".",
"_on_account_acquired",
... | Adds one or more account instances to the pool.
:type accounts: Account|list[Account]
:param accounts: The account to be added. | [
"Adds",
"one",
"or",
"more",
"account",
"instances",
"to",
"the",
"pool",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L467-L480 | train | 213,190 |
knipknap/exscript | Exscript/account.py | AccountPool.reset | def reset(self):
"""
Removes all accounts.
"""
with self.unlock_cond:
for owner in self.owner2account:
self.release_accounts(owner)
self._remove_account(self.accounts.copy())
self.unlock_cond.notify_all() | python | def reset(self):
"""
Removes all accounts.
"""
with self.unlock_cond:
for owner in self.owner2account:
self.release_accounts(owner)
self._remove_account(self.accounts.copy())
self.unlock_cond.notify_all() | [
"def",
"reset",
"(",
"self",
")",
":",
"with",
"self",
".",
"unlock_cond",
":",
"for",
"owner",
"in",
"self",
".",
"owner2account",
":",
"self",
".",
"release_accounts",
"(",
"owner",
")",
"self",
".",
"_remove_account",
"(",
"self",
".",
"accounts",
"."... | Removes all accounts. | [
"Removes",
"all",
"accounts",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L498-L506 | train | 213,191 |
knipknap/exscript | Exscript/account.py | AccountPool.get_account_from_name | def get_account_from_name(self, name):
"""
Returns the account with the given name.
:type name: string
:param name: The name of the account.
"""
for account in self.accounts:
if account.get_name() == name:
return account
return None | python | def get_account_from_name(self, name):
"""
Returns the account with the given name.
:type name: string
:param name: The name of the account.
"""
for account in self.accounts:
if account.get_name() == name:
return account
return None | [
"def",
"get_account_from_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"account",
"in",
"self",
".",
"accounts",
":",
"if",
"account",
".",
"get_name",
"(",
")",
"==",
"name",
":",
"return",
"account",
"return",
"None"
] | Returns the account with the given name.
:type name: string
:param name: The name of the account. | [
"Returns",
"the",
"account",
"with",
"the",
"given",
"name",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L508-L518 | train | 213,192 |
knipknap/exscript | Exscript/account.py | AccountPool.acquire_account | def acquire_account(self, account=None, owner=None):
"""
Waits until an account becomes available, then locks and returns it.
If an account is not passed, the next available account is returned.
:type account: Account
:param account: The account to be acquired, or None.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired.
"""
with self.unlock_cond:
if len(self.accounts) == 0:
raise ValueError('account pool is empty')
if account:
# Specific account requested.
while account not in self.unlocked_accounts:
self.unlock_cond.wait()
self.unlocked_accounts.remove(account)
else:
# Else take the next available one.
while len(self.unlocked_accounts) == 0:
self.unlock_cond.wait()
account = self.unlocked_accounts.popleft()
if owner is not None:
self.owner2account[owner].append(account)
self.account2owner[account] = owner
account.acquire(False)
self.unlock_cond.notify_all()
return account | python | def acquire_account(self, account=None, owner=None):
"""
Waits until an account becomes available, then locks and returns it.
If an account is not passed, the next available account is returned.
:type account: Account
:param account: The account to be acquired, or None.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired.
"""
with self.unlock_cond:
if len(self.accounts) == 0:
raise ValueError('account pool is empty')
if account:
# Specific account requested.
while account not in self.unlocked_accounts:
self.unlock_cond.wait()
self.unlocked_accounts.remove(account)
else:
# Else take the next available one.
while len(self.unlocked_accounts) == 0:
self.unlock_cond.wait()
account = self.unlocked_accounts.popleft()
if owner is not None:
self.owner2account[owner].append(account)
self.account2owner[account] = owner
account.acquire(False)
self.unlock_cond.notify_all()
return account | [
"def",
"acquire_account",
"(",
"self",
",",
"account",
"=",
"None",
",",
"owner",
"=",
"None",
")",
":",
"with",
"self",
".",
"unlock_cond",
":",
"if",
"len",
"(",
"self",
".",
"accounts",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'account pool... | Waits until an account becomes available, then locks and returns it.
If an account is not passed, the next available account is returned.
:type account: Account
:param account: The account to be acquired, or None.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired. | [
"Waits",
"until",
"an",
"account",
"becomes",
"available",
"then",
"locks",
"and",
"returns",
"it",
".",
"If",
"an",
"account",
"is",
"not",
"passed",
"the",
"next",
"available",
"account",
"is",
"returned",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L526-L558 | train | 213,193 |
knipknap/exscript | Exscript/account.py | AccountManager.add_pool | def add_pool(self, pool, match=None):
"""
Adds a new account pool. If the given match argument is
None, the pool the default pool. Otherwise, the match argument is
a callback function that is invoked to decide whether or not the
given pool should be used for a host.
When Exscript logs into a host, the account is chosen in the following
order:
# Exscript checks whether an account was attached to the
:class:`Host` object using :class:`Host.set_account()`), and uses that.
# If the :class:`Host` has no account attached, Exscript walks
through all pools that were passed to :class:`Queue.add_account_pool()`.
For each pool, it passes the :class:`Host` to the function in the
given match argument. If the return value is True, the account
pool is used to acquire an account.
(Accounts within each pool are taken in a round-robin
fashion.)
# If no matching account pool is found, an account is taken
from the default account pool.
# Finally, if all that fails and the default account pool
contains no accounts, an error is raised.
Example usage::
def do_nothing(conn):
conn.autoinit()
def use_this_pool(host):
return host.get_name().startswith('foo')
default_pool = AccountPool()
default_pool.add_account(Account('default-user', 'password'))
other_pool = AccountPool()
other_pool.add_account(Account('user', 'password'))
queue = Queue()
queue.account_manager.add_pool(default_pool)
queue.account_manager.add_pool(other_pool, use_this_pool)
host = Host('localhost')
queue.run(host, do_nothing)
In the example code, the host has no account attached. As a result,
the queue checks whether use_this_pool() returns True. Because the
hostname does not start with 'foo', the function returns False, and
Exscript takes the 'default-user' account from the default pool.
:type pool: AccountPool
:param pool: The account pool that is added.
:type match: callable
:param match: A callback to check if the pool should be used.
"""
if match is None:
self.default_pool = pool
else:
self.pools.append((match, pool)) | python | def add_pool(self, pool, match=None):
"""
Adds a new account pool. If the given match argument is
None, the pool the default pool. Otherwise, the match argument is
a callback function that is invoked to decide whether or not the
given pool should be used for a host.
When Exscript logs into a host, the account is chosen in the following
order:
# Exscript checks whether an account was attached to the
:class:`Host` object using :class:`Host.set_account()`), and uses that.
# If the :class:`Host` has no account attached, Exscript walks
through all pools that were passed to :class:`Queue.add_account_pool()`.
For each pool, it passes the :class:`Host` to the function in the
given match argument. If the return value is True, the account
pool is used to acquire an account.
(Accounts within each pool are taken in a round-robin
fashion.)
# If no matching account pool is found, an account is taken
from the default account pool.
# Finally, if all that fails and the default account pool
contains no accounts, an error is raised.
Example usage::
def do_nothing(conn):
conn.autoinit()
def use_this_pool(host):
return host.get_name().startswith('foo')
default_pool = AccountPool()
default_pool.add_account(Account('default-user', 'password'))
other_pool = AccountPool()
other_pool.add_account(Account('user', 'password'))
queue = Queue()
queue.account_manager.add_pool(default_pool)
queue.account_manager.add_pool(other_pool, use_this_pool)
host = Host('localhost')
queue.run(host, do_nothing)
In the example code, the host has no account attached. As a result,
the queue checks whether use_this_pool() returns True. Because the
hostname does not start with 'foo', the function returns False, and
Exscript takes the 'default-user' account from the default pool.
:type pool: AccountPool
:param pool: The account pool that is added.
:type match: callable
:param match: A callback to check if the pool should be used.
"""
if match is None:
self.default_pool = pool
else:
self.pools.append((match, pool)) | [
"def",
"add_pool",
"(",
"self",
",",
"pool",
",",
"match",
"=",
"None",
")",
":",
"if",
"match",
"is",
"None",
":",
"self",
".",
"default_pool",
"=",
"pool",
"else",
":",
"self",
".",
"pools",
".",
"append",
"(",
"(",
"match",
",",
"pool",
")",
"... | Adds a new account pool. If the given match argument is
None, the pool the default pool. Otherwise, the match argument is
a callback function that is invoked to decide whether or not the
given pool should be used for a host.
When Exscript logs into a host, the account is chosen in the following
order:
# Exscript checks whether an account was attached to the
:class:`Host` object using :class:`Host.set_account()`), and uses that.
# If the :class:`Host` has no account attached, Exscript walks
through all pools that were passed to :class:`Queue.add_account_pool()`.
For each pool, it passes the :class:`Host` to the function in the
given match argument. If the return value is True, the account
pool is used to acquire an account.
(Accounts within each pool are taken in a round-robin
fashion.)
# If no matching account pool is found, an account is taken
from the default account pool.
# Finally, if all that fails and the default account pool
contains no accounts, an error is raised.
Example usage::
def do_nothing(conn):
conn.autoinit()
def use_this_pool(host):
return host.get_name().startswith('foo')
default_pool = AccountPool()
default_pool.add_account(Account('default-user', 'password'))
other_pool = AccountPool()
other_pool.add_account(Account('user', 'password'))
queue = Queue()
queue.account_manager.add_pool(default_pool)
queue.account_manager.add_pool(other_pool, use_this_pool)
host = Host('localhost')
queue.run(host, do_nothing)
In the example code, the host has no account attached. As a result,
the queue checks whether use_this_pool() returns True. Because the
hostname does not start with 'foo', the function returns False, and
Exscript takes the 'default-user' account from the default pool.
:type pool: AccountPool
:param pool: The account pool that is added.
:type match: callable
:param match: A callback to check if the pool should be used. | [
"Adds",
"a",
"new",
"account",
"pool",
".",
"If",
"the",
"given",
"match",
"argument",
"is",
"None",
"the",
"pool",
"the",
"default",
"pool",
".",
"Otherwise",
"the",
"match",
"argument",
"is",
"a",
"callback",
"function",
"that",
"is",
"invoked",
"to",
... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L598-L659 | train | 213,194 |
knipknap/exscript | Exscript/account.py | AccountManager.get_account_from_hash | def get_account_from_hash(self, account_hash):
"""
Returns the account with the given hash, if it is contained in any
of the pools. Returns None otherwise.
:type account_hash: str
:param account_hash: The hash of an account object.
"""
for _, pool in self.pools:
account = pool.get_account_from_hash(account_hash)
if account is not None:
return account
return self.default_pool.get_account_from_hash(account_hash) | python | def get_account_from_hash(self, account_hash):
"""
Returns the account with the given hash, if it is contained in any
of the pools. Returns None otherwise.
:type account_hash: str
:param account_hash: The hash of an account object.
"""
for _, pool in self.pools:
account = pool.get_account_from_hash(account_hash)
if account is not None:
return account
return self.default_pool.get_account_from_hash(account_hash) | [
"def",
"get_account_from_hash",
"(",
"self",
",",
"account_hash",
")",
":",
"for",
"_",
",",
"pool",
"in",
"self",
".",
"pools",
":",
"account",
"=",
"pool",
".",
"get_account_from_hash",
"(",
"account_hash",
")",
"if",
"account",
"is",
"not",
"None",
":",... | Returns the account with the given hash, if it is contained in any
of the pools. Returns None otherwise.
:type account_hash: str
:param account_hash: The hash of an account object. | [
"Returns",
"the",
"account",
"with",
"the",
"given",
"hash",
"if",
"it",
"is",
"contained",
"in",
"any",
"of",
"the",
"pools",
".",
"Returns",
"None",
"otherwise",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L671-L683 | train | 213,195 |
knipknap/exscript | Exscript/account.py | AccountManager.acquire_account | def acquire_account(self, account=None, owner=None):
"""
Acquires the given account. If no account is given, one is chosen
from the default pool.
:type account: Account
:param account: The account that is added.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired.
"""
if account is not None:
for _, pool in self.pools:
if pool.has_account(account):
return pool.acquire_account(account, owner)
if not self.default_pool.has_account(account):
# The account is not in any pool.
account.acquire()
return account
return self.default_pool.acquire_account(account, owner) | python | def acquire_account(self, account=None, owner=None):
"""
Acquires the given account. If no account is given, one is chosen
from the default pool.
:type account: Account
:param account: The account that is added.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired.
"""
if account is not None:
for _, pool in self.pools:
if pool.has_account(account):
return pool.acquire_account(account, owner)
if not self.default_pool.has_account(account):
# The account is not in any pool.
account.acquire()
return account
return self.default_pool.acquire_account(account, owner) | [
"def",
"acquire_account",
"(",
"self",
",",
"account",
"=",
"None",
",",
"owner",
"=",
"None",
")",
":",
"if",
"account",
"is",
"not",
"None",
":",
"for",
"_",
",",
"pool",
"in",
"self",
".",
"pools",
":",
"if",
"pool",
".",
"has_account",
"(",
"ac... | Acquires the given account. If no account is given, one is chosen
from the default pool.
:type account: Account
:param account: The account that is added.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired. | [
"Acquires",
"the",
"given",
"account",
".",
"If",
"no",
"account",
"is",
"given",
"one",
"is",
"chosen",
"from",
"the",
"default",
"pool",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L685-L707 | train | 213,196 |
knipknap/exscript | Exscript/account.py | AccountManager.acquire_account_for | def acquire_account_for(self, host, owner=None):
"""
Acquires an account for the given host and returns it.
The host is passed to each of the match functions that were
passed in when adding the pool. The first pool for which the
match function returns True is chosen to assign an account.
:type host: :class:`Host`
:param host: The host for which an account is acquired.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired.
"""
# Check whether a matching account pool exists.
for match, pool in self.pools:
if match(host) is True:
return pool.acquire_account(owner=owner)
# Else, choose an account from the default account pool.
return self.default_pool.acquire_account(owner=owner) | python | def acquire_account_for(self, host, owner=None):
"""
Acquires an account for the given host and returns it.
The host is passed to each of the match functions that were
passed in when adding the pool. The first pool for which the
match function returns True is chosen to assign an account.
:type host: :class:`Host`
:param host: The host for which an account is acquired.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired.
"""
# Check whether a matching account pool exists.
for match, pool in self.pools:
if match(host) is True:
return pool.acquire_account(owner=owner)
# Else, choose an account from the default account pool.
return self.default_pool.acquire_account(owner=owner) | [
"def",
"acquire_account_for",
"(",
"self",
",",
"host",
",",
"owner",
"=",
"None",
")",
":",
"# Check whether a matching account pool exists.",
"for",
"match",
",",
"pool",
"in",
"self",
".",
"pools",
":",
"if",
"match",
"(",
"host",
")",
"is",
"True",
":",
... | Acquires an account for the given host and returns it.
The host is passed to each of the match functions that were
passed in when adding the pool. The first pool for which the
match function returns True is chosen to assign an account.
:type host: :class:`Host`
:param host: The host for which an account is acquired.
:type owner: object
:param owner: An optional descriptor for the owner.
:rtype: :class:`Account`
:return: The account that was acquired. | [
"Acquires",
"an",
"account",
"for",
"the",
"given",
"host",
"and",
"returns",
"it",
".",
"The",
"host",
"is",
"passed",
"to",
"each",
"of",
"the",
"match",
"functions",
"that",
"were",
"passed",
"in",
"when",
"adding",
"the",
"pool",
".",
"The",
"first",... | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L709-L729 | train | 213,197 |
knipknap/exscript | Exscript/emulators/command.py | CommandSet.eval | def eval(self, command):
"""
Evaluate the given string against all registered commands and
return the defined response.
:type command: str
:param command: The command that is evaluated.
:rtype: str or None
:return: The response, if one was defined.
"""
for cmd, response in self.response_list:
if not cmd.match(command):
continue
if response is None:
return None
elif hasattr(response, '__call__'):
return response(command)
else:
return response
if self.strict:
raise Exception('Undefined command: ' + repr(command))
return None | python | def eval(self, command):
"""
Evaluate the given string against all registered commands and
return the defined response.
:type command: str
:param command: The command that is evaluated.
:rtype: str or None
:return: The response, if one was defined.
"""
for cmd, response in self.response_list:
if not cmd.match(command):
continue
if response is None:
return None
elif hasattr(response, '__call__'):
return response(command)
else:
return response
if self.strict:
raise Exception('Undefined command: ' + repr(command))
return None | [
"def",
"eval",
"(",
"self",
",",
"command",
")",
":",
"for",
"cmd",
",",
"response",
"in",
"self",
".",
"response_list",
":",
"if",
"not",
"cmd",
".",
"match",
"(",
"command",
")",
":",
"continue",
"if",
"response",
"is",
"None",
":",
"return",
"None... | Evaluate the given string against all registered commands and
return the defined response.
:type command: str
:param command: The command that is evaluated.
:rtype: str or None
:return: The response, if one was defined. | [
"Evaluate",
"the",
"given",
"string",
"against",
"all",
"registered",
"commands",
"and",
"return",
"the",
"defined",
"response",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/emulators/command.py#L98-L119 | train | 213,198 |
knipknap/exscript | Exscript/util/cast.py | to_host | def to_host(host, default_protocol='telnet', default_domain=''):
"""
Given a string or a Host object, this function returns a Host object.
:type host: string|Host
:param host: A hostname (may be URL formatted) or a Host object.
:type default_protocol: str
:param default_protocol: Passed to the Host constructor.
:type default_domain: str
:param default_domain: Appended to each hostname that has no domain.
:rtype: Host
:return: The Host object.
"""
if host is None:
raise TypeError('None can not be cast to Host')
if hasattr(host, 'get_address'):
return host
if default_domain and not '.' in host:
host += '.' + default_domain
return Exscript.Host(host, default_protocol=default_protocol) | python | def to_host(host, default_protocol='telnet', default_domain=''):
"""
Given a string or a Host object, this function returns a Host object.
:type host: string|Host
:param host: A hostname (may be URL formatted) or a Host object.
:type default_protocol: str
:param default_protocol: Passed to the Host constructor.
:type default_domain: str
:param default_domain: Appended to each hostname that has no domain.
:rtype: Host
:return: The Host object.
"""
if host is None:
raise TypeError('None can not be cast to Host')
if hasattr(host, 'get_address'):
return host
if default_domain and not '.' in host:
host += '.' + default_domain
return Exscript.Host(host, default_protocol=default_protocol) | [
"def",
"to_host",
"(",
"host",
",",
"default_protocol",
"=",
"'telnet'",
",",
"default_domain",
"=",
"''",
")",
":",
"if",
"host",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'None can not be cast to Host'",
")",
"if",
"hasattr",
"(",
"host",
",",
"'get_a... | Given a string or a Host object, this function returns a Host object.
:type host: string|Host
:param host: A hostname (may be URL formatted) or a Host object.
:type default_protocol: str
:param default_protocol: Passed to the Host constructor.
:type default_domain: str
:param default_domain: Appended to each hostname that has no domain.
:rtype: Host
:return: The Host object. | [
"Given",
"a",
"string",
"or",
"a",
"Host",
"object",
"this",
"function",
"returns",
"a",
"Host",
"object",
"."
] | 72718eee3e87b345d5a5255be9824e867e42927b | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/cast.py#L47-L66 | train | 213,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.