id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4,600 | rytilahti/python-songpal | songpal/service.py | Service.asdict | def asdict(self):
"""Return dict presentation of this service.
Useful for dumping the device information into JSON.
"""
return {
"methods": {m.name: m.asdict() for m in self.methods},
"protocols": self.protocols,
"notifications": {n.name: n.asdict() for n in self.notifications},
} | python | def asdict(self):
return {
"methods": {m.name: m.asdict() for m in self.methods},
"protocols": self.protocols,
"notifications": {n.name: n.asdict() for n in self.notifications},
} | [
"def",
"asdict",
"(",
"self",
")",
":",
"return",
"{",
"\"methods\"",
":",
"{",
"m",
".",
"name",
":",
"m",
".",
"asdict",
"(",
")",
"for",
"m",
"in",
"self",
".",
"methods",
"}",
",",
"\"protocols\"",
":",
"self",
".",
"protocols",
",",
"\"notific... | Return dict presentation of this service.
Useful for dumping the device information into JSON. | [
"Return",
"dict",
"presentation",
"of",
"this",
"service",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L283-L292 |
4,601 | scivision/lowtran | lowtran/scenarios.py | horizrad | def horizrad(infn: Path, outfn: Path, c1: dict) -> xarray.Dataset:
"""
read CSV, simulate, write, plot
"""
if infn is not None:
infn = Path(infn).expanduser()
if infn.suffix == '.h5':
TR = xarray.open_dataset(infn)
return TR
c1.update({'model': 0, # 0: user meterological data
'itype': 1, # 1: horizontal path
'iemsct': 1, # 1: radiance model
'im': 1, # 1: for horizontal path (see Lowtran manual p.42)
'ird1': 1, # 1: use card 2C2)
})
# %% read csv file
if not infn: # demo mode
c1['p'] = [949., 959.]
c1['t'] = [283.8, 285.]
c1['wmol'] = [[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]
c1['time'] = [parse('2017-04-05T12'),
parse('2017-04-05T18')]
else: # read csv, normal case
PTdata = read_csv(infn)
c1['p'] = PTdata['p']
c1['t'] = PTdata['Ta']
c1['wmol'] = np.zeros((PTdata.shape[0], 12))
c1['wmol'][:, 0] = PTdata['RH']
c1['time'] = [parse(t) for t in PTdata['time']]
# %% TR is 3-D array with axes: time, wavelength, and [transmission,radiance]
TR = loopuserdef(c1)
return TR | python | def horizrad(infn: Path, outfn: Path, c1: dict) -> xarray.Dataset:
if infn is not None:
infn = Path(infn).expanduser()
if infn.suffix == '.h5':
TR = xarray.open_dataset(infn)
return TR
c1.update({'model': 0, # 0: user meterological data
'itype': 1, # 1: horizontal path
'iemsct': 1, # 1: radiance model
'im': 1, # 1: for horizontal path (see Lowtran manual p.42)
'ird1': 1, # 1: use card 2C2)
})
# %% read csv file
if not infn: # demo mode
c1['p'] = [949., 959.]
c1['t'] = [283.8, 285.]
c1['wmol'] = [[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]
c1['time'] = [parse('2017-04-05T12'),
parse('2017-04-05T18')]
else: # read csv, normal case
PTdata = read_csv(infn)
c1['p'] = PTdata['p']
c1['t'] = PTdata['Ta']
c1['wmol'] = np.zeros((PTdata.shape[0], 12))
c1['wmol'][:, 0] = PTdata['RH']
c1['time'] = [parse(t) for t in PTdata['time']]
# %% TR is 3-D array with axes: time, wavelength, and [transmission,radiance]
TR = loopuserdef(c1)
return TR | [
"def",
"horizrad",
"(",
"infn",
":",
"Path",
",",
"outfn",
":",
"Path",
",",
"c1",
":",
"dict",
")",
"->",
"xarray",
".",
"Dataset",
":",
"if",
"infn",
"is",
"not",
"None",
":",
"infn",
"=",
"Path",
"(",
"infn",
")",
".",
"expanduser",
"(",
")",
... | read CSV, simulate, write, plot | [
"read",
"CSV",
"simulate",
"write",
"plot"
] | 9954d859e53437436103f9ab54a7e2602ecaa1b7 | https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/scenarios.py#L50-L85 |
4,602 | scivision/lowtran | lowtran/base.py | nm2lt7 | def nm2lt7(short_nm: float, long_nm: float, step_cminv: float = 20) -> Tuple[float, float, float]:
"""converts wavelength in nm to cm^-1
minimum meaningful step is 20, but 5 is minimum before crashing lowtran
short: shortest wavelength e.g. 200 nm
long: longest wavelength e.g. 30000 nm
step: step size in cm^-1 e.g. 20
output in cm^-1
"""
short = 1e7 / short_nm
long = 1e7 / long_nm
N = int(np.ceil((short-long) / step_cminv)) + 1 # yes, ceil
return short, long, N | python | def nm2lt7(short_nm: float, long_nm: float, step_cminv: float = 20) -> Tuple[float, float, float]:
short = 1e7 / short_nm
long = 1e7 / long_nm
N = int(np.ceil((short-long) / step_cminv)) + 1 # yes, ceil
return short, long, N | [
"def",
"nm2lt7",
"(",
"short_nm",
":",
"float",
",",
"long_nm",
":",
"float",
",",
"step_cminv",
":",
"float",
"=",
"20",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
":",
"short",
"=",
"1e7",
"/",
"short_nm",
"long",
"=",
"1e... | converts wavelength in nm to cm^-1
minimum meaningful step is 20, but 5 is minimum before crashing lowtran
short: shortest wavelength e.g. 200 nm
long: longest wavelength e.g. 30000 nm
step: step size in cm^-1 e.g. 20
output in cm^-1 | [
"converts",
"wavelength",
"in",
"nm",
"to",
"cm^",
"-",
"1",
"minimum",
"meaningful",
"step",
"is",
"20",
"but",
"5",
"is",
"minimum",
"before",
"crashing",
"lowtran"
] | 9954d859e53437436103f9ab54a7e2602ecaa1b7 | https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L12-L27 |
4,603 | scivision/lowtran | lowtran/base.py | loopangle | def loopangle(c1: Dict[str, Any]) -> xarray.Dataset:
"""
loop over "ANGLE"
"""
angles = np.atleast_1d(c1['angle'])
TR = xarray.Dataset(coords={'wavelength_nm': None, 'angle_deg': angles})
for a in angles:
c = c1.copy()
c['angle'] = a
TR = TR.merge(golowtran(c))
return TR | python | def loopangle(c1: Dict[str, Any]) -> xarray.Dataset:
angles = np.atleast_1d(c1['angle'])
TR = xarray.Dataset(coords={'wavelength_nm': None, 'angle_deg': angles})
for a in angles:
c = c1.copy()
c['angle'] = a
TR = TR.merge(golowtran(c))
return TR | [
"def",
"loopangle",
"(",
"c1",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"xarray",
".",
"Dataset",
":",
"angles",
"=",
"np",
".",
"atleast_1d",
"(",
"c1",
"[",
"'angle'",
"]",
")",
"TR",
"=",
"xarray",
".",
"Dataset",
"(",
"coords",
"=... | loop over "ANGLE" | [
"loop",
"over",
"ANGLE"
] | 9954d859e53437436103f9ab54a7e2602ecaa1b7 | https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L63-L75 |
4,604 | scivision/lowtran | lowtran/base.py | golowtran | def golowtran(c1: Dict[str, Any]) -> xarray.Dataset:
"""directly run Fortran code"""
# %% default parameters
c1.setdefault('time', None)
defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't')
for p in defp:
c1.setdefault(p, 0)
c1.setdefault('wmol', [0]*12)
# %% input check
assert len(c1['wmol']) == 12, 'see Lowtran user manual for 12 values of WMOL'
assert np.isfinite(c1['h1']), 'per Lowtran user manual Table 14, H1 must always be defined'
# %% setup wavelength
c1.setdefault('wlstep', 20)
if c1['wlstep'] < 5:
logging.critical('minimum resolution 5 cm^-1, specified resolution 20 cm^-1')
wlshort, wllong, nwl = nm2lt7(c1['wlshort'], c1['wllong'], c1['wlstep'])
if not 0 < wlshort and wllong <= 50000:
logging.critical('specified model range 0 <= wavelength [cm^-1] <= 50000')
# %% invoke lowtran
"""
Note we invoke case "3a" from table 14, only observer altitude and apparent
angle are specified
"""
Tx, V, Alam, trace, unif, suma, irrad, sumvv = lowtran7.lwtrn7(
True, nwl, wllong, wlshort, c1['wlstep'],
c1['model'], c1['itype'], c1['iemsct'], c1['im'],
c1['iseasn'], c1['ird1'],
c1['zmdl'], c1['p'], c1['t'], c1['wmol'],
c1['h1'], c1['h2'], c1['angle'], c1['range_km'])
dims = ('time', 'wavelength_nm', 'angle_deg')
TR = xarray.Dataset({'transmission': (dims, Tx[:, 9][None, :, None]),
'radiance': (dims, sumvv[None, :, None]),
'irradiance': (dims, irrad[:, 0][None, :, None]),
'pathscatter': (dims, irrad[:, 2][None, :, None])},
coords={'time': [c1['time']],
'wavelength_nm': Alam*1e3,
'angle_deg': [c1['angle']]})
return TR | python | def golowtran(c1: Dict[str, Any]) -> xarray.Dataset:
# %% default parameters
c1.setdefault('time', None)
defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't')
for p in defp:
c1.setdefault(p, 0)
c1.setdefault('wmol', [0]*12)
# %% input check
assert len(c1['wmol']) == 12, 'see Lowtran user manual for 12 values of WMOL'
assert np.isfinite(c1['h1']), 'per Lowtran user manual Table 14, H1 must always be defined'
# %% setup wavelength
c1.setdefault('wlstep', 20)
if c1['wlstep'] < 5:
logging.critical('minimum resolution 5 cm^-1, specified resolution 20 cm^-1')
wlshort, wllong, nwl = nm2lt7(c1['wlshort'], c1['wllong'], c1['wlstep'])
if not 0 < wlshort and wllong <= 50000:
logging.critical('specified model range 0 <= wavelength [cm^-1] <= 50000')
# %% invoke lowtran
"""
Note we invoke case "3a" from table 14, only observer altitude and apparent
angle are specified
"""
Tx, V, Alam, trace, unif, suma, irrad, sumvv = lowtran7.lwtrn7(
True, nwl, wllong, wlshort, c1['wlstep'],
c1['model'], c1['itype'], c1['iemsct'], c1['im'],
c1['iseasn'], c1['ird1'],
c1['zmdl'], c1['p'], c1['t'], c1['wmol'],
c1['h1'], c1['h2'], c1['angle'], c1['range_km'])
dims = ('time', 'wavelength_nm', 'angle_deg')
TR = xarray.Dataset({'transmission': (dims, Tx[:, 9][None, :, None]),
'radiance': (dims, sumvv[None, :, None]),
'irradiance': (dims, irrad[:, 0][None, :, None]),
'pathscatter': (dims, irrad[:, 2][None, :, None])},
coords={'time': [c1['time']],
'wavelength_nm': Alam*1e3,
'angle_deg': [c1['angle']]})
return TR | [
"def",
"golowtran",
"(",
"c1",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"xarray",
".",
"Dataset",
":",
"# %% default parameters",
"c1",
".",
"setdefault",
"(",
"'time'",
",",
"None",
")",
"defp",
"=",
"(",
"'h1'",
",",
"'h2'",
",",
"'angl... | directly run Fortran code | [
"directly",
"run",
"Fortran",
"code"
] | 9954d859e53437436103f9ab54a7e2602ecaa1b7 | https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L78-L121 |
4,605 | scivision/lowtran | lowtran/plots.py | plotradtime | def plotradtime(TR: xarray.Dataset, c1: Dict[str, Any], log: bool = False):
"""
make one plot per time for now.
TR: 3-D array: time, wavelength, [transmittance, radiance]
radiance is currently single-scatter solar
"""
for t in TR.time: # for each time
plotirrad(TR.sel(time=t), c1, log) | python | def plotradtime(TR: xarray.Dataset, c1: Dict[str, Any], log: bool = False):
for t in TR.time: # for each time
plotirrad(TR.sel(time=t), c1, log) | [
"def",
"plotradtime",
"(",
"TR",
":",
"xarray",
".",
"Dataset",
",",
"c1",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"log",
":",
"bool",
"=",
"False",
")",
":",
"for",
"t",
"in",
"TR",
".",
"time",
":",
"# for each time",
"plotirrad",
"(",
"... | make one plot per time for now.
TR: 3-D array: time, wavelength, [transmittance, radiance]
radiance is currently single-scatter solar | [
"make",
"one",
"plot",
"per",
"time",
"for",
"now",
"."
] | 9954d859e53437436103f9ab54a7e2602ecaa1b7 | https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/plots.py#L90-L100 |
4,606 | rytilahti/python-songpal | songpal/method.py | Method.asdict | def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]:
"""Return a dictionary describing the method.
This can be used to dump the information into a JSON file.
"""
return {
"service": self.service.name,
**self.signature.serialize(),
} | python | def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]:
return {
"service": self.service.name,
**self.signature.serialize(),
} | [
"def",
"asdict",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Union",
"[",
"Dict",
",",
"Union",
"[",
"str",
",",
"Dict",
"]",
"]",
"]",
":",
"return",
"{",
"\"service\"",
":",
"self",
".",
"service",
".",
"name",
",",
"*",
"*",
"self",
".... | Return a dictionary describing the method.
This can be used to dump the information into a JSON file. | [
"Return",
"a",
"dictionary",
"describing",
"the",
"method",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/method.py#L107-L115 |
4,607 | rytilahti/python-songpal | songpal/common.py | DeviceError.error | def error(self):
"""Return user-friendly error message."""
try:
errcode = DeviceErrorCode(self.error_code)
return "%s (%s): %s" % (errcode.name, errcode.value, self.error_message)
except:
return "Error %s: %s" % (self.error_code, self.error_message) | python | def error(self):
try:
errcode = DeviceErrorCode(self.error_code)
return "%s (%s): %s" % (errcode.name, errcode.value, self.error_message)
except:
return "Error %s: %s" % (self.error_code, self.error_message) | [
"def",
"error",
"(",
"self",
")",
":",
"try",
":",
"errcode",
"=",
"DeviceErrorCode",
"(",
"self",
".",
"error_code",
")",
"return",
"\"%s (%s): %s\"",
"%",
"(",
"errcode",
".",
"name",
",",
"errcode",
".",
"value",
",",
"self",
".",
"error_message",
")"... | Return user-friendly error message. | [
"Return",
"user",
"-",
"friendly",
"error",
"message",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/common.py#L29-L35 |
4,608 | rytilahti/python-songpal | songpal/main.py | err | def err(msg):
"""Pretty-print an error."""
click.echo(click.style(msg, fg="red", bold=True)) | python | def err(msg):
click.echo(click.style(msg, fg="red", bold=True)) | [
"def",
"err",
"(",
"msg",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"msg",
",",
"fg",
"=",
"\"red\"",
",",
"bold",
"=",
"True",
")",
")"
] | Pretty-print an error. | [
"Pretty",
"-",
"print",
"an",
"error",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L33-L35 |
4,609 | rytilahti/python-songpal | songpal/main.py | coro | def coro(f):
"""Run a coroutine and handle possible errors for the click cli.
Source https://github.com/pallets/click/issues/85#issuecomment-43378930
"""
f = asyncio.coroutine(f)
def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
try:
return loop.run_until_complete(f(*args, **kwargs))
except KeyboardInterrupt:
click.echo("Got CTRL+C, quitting..")
dev = args[0]
loop.run_until_complete(dev.stop_listen_notifications())
except SongpalException as ex:
err("Error: %s" % ex)
if len(args) > 0 and hasattr(args[0], "debug"):
if args[0].debug > 0:
raise ex
return update_wrapper(wrapper, f) | python | def coro(f):
f = asyncio.coroutine(f)
def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
try:
return loop.run_until_complete(f(*args, **kwargs))
except KeyboardInterrupt:
click.echo("Got CTRL+C, quitting..")
dev = args[0]
loop.run_until_complete(dev.stop_listen_notifications())
except SongpalException as ex:
err("Error: %s" % ex)
if len(args) > 0 and hasattr(args[0], "debug"):
if args[0].debug > 0:
raise ex
return update_wrapper(wrapper, f) | [
"def",
"coro",
"(",
"f",
")",
":",
"f",
"=",
"asyncio",
".",
"coroutine",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"try",
":",
"return",
"loop",... | Run a coroutine and handle possible errors for the click cli.
Source https://github.com/pallets/click/issues/85#issuecomment-43378930 | [
"Run",
"a",
"coroutine",
"and",
"handle",
"possible",
"errors",
"for",
"the",
"click",
"cli",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L38-L59 |
4,610 | rytilahti/python-songpal | songpal/main.py | traverse_settings | async def traverse_settings(dev, module, settings, depth=0):
"""Print all available settings."""
for setting in settings:
if setting.is_directory:
print("%s%s (%s)" % (depth * " ", setting.title, module))
return await traverse_settings(dev, module, setting.settings, depth + 2)
else:
try:
print_settings([await setting.get_value(dev)], depth=depth)
except SongpalException as ex:
err("Unable to read setting %s: %s" % (setting, ex))
continue | python | async def traverse_settings(dev, module, settings, depth=0):
for setting in settings:
if setting.is_directory:
print("%s%s (%s)" % (depth * " ", setting.title, module))
return await traverse_settings(dev, module, setting.settings, depth + 2)
else:
try:
print_settings([await setting.get_value(dev)], depth=depth)
except SongpalException as ex:
err("Unable to read setting %s: %s" % (setting, ex))
continue | [
"async",
"def",
"traverse_settings",
"(",
"dev",
",",
"module",
",",
"settings",
",",
"depth",
"=",
"0",
")",
":",
"for",
"setting",
"in",
"settings",
":",
"if",
"setting",
".",
"is_directory",
":",
"print",
"(",
"\"%s%s (%s)\"",
"%",
"(",
"depth",
"*",
... | Print all available settings. | [
"Print",
"all",
"available",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L62-L73 |
4,611 | rytilahti/python-songpal | songpal/main.py | print_settings | def print_settings(settings, depth=0):
"""Print all available settings of the device."""
# handle the case where a single setting is passed
if isinstance(settings, Setting):
settings = [settings]
for setting in settings:
cur = setting.currentValue
print(
"%s* %s (%s, value: %s, type: %s)"
% (
" " * depth,
setting.title,
setting.target,
click.style(cur, bold=True),
setting.type,
)
)
for opt in setting.candidate:
if not opt.isAvailable:
logging.debug("Unavailable setting %s", opt)
continue
click.echo(
click.style(
"%s - %s (%s)" % (" " * depth, opt.title, opt.value),
bold=opt.value == cur,
)
) | python | def print_settings(settings, depth=0):
# handle the case where a single setting is passed
if isinstance(settings, Setting):
settings = [settings]
for setting in settings:
cur = setting.currentValue
print(
"%s* %s (%s, value: %s, type: %s)"
% (
" " * depth,
setting.title,
setting.target,
click.style(cur, bold=True),
setting.type,
)
)
for opt in setting.candidate:
if not opt.isAvailable:
logging.debug("Unavailable setting %s", opt)
continue
click.echo(
click.style(
"%s - %s (%s)" % (" " * depth, opt.title, opt.value),
bold=opt.value == cur,
)
) | [
"def",
"print_settings",
"(",
"settings",
",",
"depth",
"=",
"0",
")",
":",
"# handle the case where a single setting is passed",
"if",
"isinstance",
"(",
"settings",
",",
"Setting",
")",
":",
"settings",
"=",
"[",
"settings",
"]",
"for",
"setting",
"in",
"setti... | Print all available settings of the device. | [
"Print",
"all",
"available",
"settings",
"of",
"the",
"device",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L76-L102 |
4,612 | rytilahti/python-songpal | songpal/main.py | cli | async def cli(ctx, endpoint, debug, websocket, post):
"""Songpal CLI."""
lvl = logging.INFO
if debug:
lvl = logging.DEBUG
click.echo("Setting debug level to %s" % debug)
logging.basicConfig(level=lvl)
if ctx.invoked_subcommand == "discover":
ctx.obj = {"debug": debug}
return
if endpoint is None:
err("Endpoint is required except when with 'discover'!")
return
protocol = None
if post and websocket:
err("You can force either --post or --websocket")
return
elif websocket:
protocol = ProtocolType.WebSocket
elif post:
protocol = ProtocolType.XHRPost
logging.debug("Using endpoint %s", endpoint)
x = Device(endpoint, force_protocol=protocol, debug=debug)
try:
await x.get_supported_methods()
except (requests.exceptions.ConnectionError, SongpalException) as ex:
err("Unable to get supported methods: %s" % ex)
sys.exit(-1)
ctx.obj = x | python | async def cli(ctx, endpoint, debug, websocket, post):
lvl = logging.INFO
if debug:
lvl = logging.DEBUG
click.echo("Setting debug level to %s" % debug)
logging.basicConfig(level=lvl)
if ctx.invoked_subcommand == "discover":
ctx.obj = {"debug": debug}
return
if endpoint is None:
err("Endpoint is required except when with 'discover'!")
return
protocol = None
if post and websocket:
err("You can force either --post or --websocket")
return
elif websocket:
protocol = ProtocolType.WebSocket
elif post:
protocol = ProtocolType.XHRPost
logging.debug("Using endpoint %s", endpoint)
x = Device(endpoint, force_protocol=protocol, debug=debug)
try:
await x.get_supported_methods()
except (requests.exceptions.ConnectionError, SongpalException) as ex:
err("Unable to get supported methods: %s" % ex)
sys.exit(-1)
ctx.obj = x | [
"async",
"def",
"cli",
"(",
"ctx",
",",
"endpoint",
",",
"debug",
",",
"websocket",
",",
"post",
")",
":",
"lvl",
"=",
"logging",
".",
"INFO",
"if",
"debug",
":",
"lvl",
"=",
"logging",
".",
"DEBUG",
"click",
".",
"echo",
"(",
"\"Setting debug level to... | Songpal CLI. | [
"Songpal",
"CLI",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L115-L147 |
4,613 | rytilahti/python-songpal | songpal/main.py | status | async def status(dev: Device):
"""Display status information."""
power = await dev.get_power()
click.echo(click.style("%s" % power, bold=power))
vol = await dev.get_volume_information()
click.echo(vol.pop())
play_info = await dev.get_play_info()
if not play_info.is_idle:
click.echo("Playing %s" % play_info)
else:
click.echo("Not playing any media")
outs = await dev.get_inputs()
for out in outs:
if out.active:
click.echo("Active output: %s" % out)
sysinfo = await dev.get_system_info()
click.echo("System information: %s" % sysinfo) | python | async def status(dev: Device):
power = await dev.get_power()
click.echo(click.style("%s" % power, bold=power))
vol = await dev.get_volume_information()
click.echo(vol.pop())
play_info = await dev.get_play_info()
if not play_info.is_idle:
click.echo("Playing %s" % play_info)
else:
click.echo("Not playing any media")
outs = await dev.get_inputs()
for out in outs:
if out.active:
click.echo("Active output: %s" % out)
sysinfo = await dev.get_system_info()
click.echo("System information: %s" % sysinfo) | [
"async",
"def",
"status",
"(",
"dev",
":",
"Device",
")",
":",
"power",
"=",
"await",
"dev",
".",
"get_power",
"(",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"%s\"",
"%",
"power",
",",
"bold",
"=",
"power",
")",
")",
"vol",
"=... | Display status information. | [
"Display",
"status",
"information",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L157-L177 |
4,614 | rytilahti/python-songpal | songpal/main.py | power | async def power(dev: Device, cmd, target, value):
"""Turn on and off, control power settings.
Accepts commands 'on', 'off', and 'settings'.
"""
async def try_turn(cmd):
state = True if cmd == "on" else False
try:
return await dev.set_power(state)
except SongpalException as ex:
if ex.code == 3:
err("The device is already %s." % cmd)
else:
raise ex
if cmd == "on" or cmd == "off":
click.echo(await try_turn(cmd))
elif cmd == "settings":
settings = await dev.get_power_settings()
print_settings(settings)
elif cmd == "set" and target and value:
click.echo(await dev.set_power_settings(target, value))
else:
power = await dev.get_power()
click.echo(click.style(str(power), bold=power)) | python | async def power(dev: Device, cmd, target, value):
async def try_turn(cmd):
state = True if cmd == "on" else False
try:
return await dev.set_power(state)
except SongpalException as ex:
if ex.code == 3:
err("The device is already %s." % cmd)
else:
raise ex
if cmd == "on" or cmd == "off":
click.echo(await try_turn(cmd))
elif cmd == "settings":
settings = await dev.get_power_settings()
print_settings(settings)
elif cmd == "set" and target and value:
click.echo(await dev.set_power_settings(target, value))
else:
power = await dev.get_power()
click.echo(click.style(str(power), bold=power)) | [
"async",
"def",
"power",
"(",
"dev",
":",
"Device",
",",
"cmd",
",",
"target",
",",
"value",
")",
":",
"async",
"def",
"try_turn",
"(",
"cmd",
")",
":",
"state",
"=",
"True",
"if",
"cmd",
"==",
"\"on\"",
"else",
"False",
"try",
":",
"return",
"awai... | Turn on and off, control power settings.
Accepts commands 'on', 'off', and 'settings'. | [
"Turn",
"on",
"and",
"off",
"control",
"power",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L213-L237 |
4,615 | rytilahti/python-songpal | songpal/main.py | googlecast | async def googlecast(dev: Device, target, value):
"""Return Googlecast settings."""
if target and value:
click.echo("Setting %s = %s" % (target, value))
await dev.set_googlecast_settings(target, value)
print_settings(await dev.get_googlecast_settings()) | python | async def googlecast(dev: Device, target, value):
if target and value:
click.echo("Setting %s = %s" % (target, value))
await dev.set_googlecast_settings(target, value)
print_settings(await dev.get_googlecast_settings()) | [
"async",
"def",
"googlecast",
"(",
"dev",
":",
"Device",
",",
"target",
",",
"value",
")",
":",
"if",
"target",
"and",
"value",
":",
"click",
".",
"echo",
"(",
"\"Setting %s = %s\"",
"%",
"(",
"target",
",",
"value",
")",
")",
"await",
"dev",
".",
"s... | Return Googlecast settings. | [
"Return",
"Googlecast",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L299-L304 |
4,616 | rytilahti/python-songpal | songpal/main.py | source | async def source(dev: Device, scheme):
"""List available sources.
If no `scheme` is given, will list sources for all sc hemes.
"""
if scheme is None:
schemes = await dev.get_schemes()
schemes = [scheme.scheme for scheme in schemes] # noqa: T484
else:
schemes = [scheme]
for schema in schemes:
try:
sources = await dev.get_source_list(schema)
except SongpalException as ex:
click.echo("Unable to get sources for %s" % schema)
continue
for src in sources:
click.echo(src)
if src.isBrowsable:
try:
count = await dev.get_content_count(src.source)
if count.count > 0:
click.echo(" %s" % count)
for content in await dev.get_contents(src.source):
click.echo(" %s\n\t%s" % (content.title, content.uri))
else:
click.echo(" No content to list.")
except SongpalException as ex:
click.echo(" %s" % ex) | python | async def source(dev: Device, scheme):
if scheme is None:
schemes = await dev.get_schemes()
schemes = [scheme.scheme for scheme in schemes] # noqa: T484
else:
schemes = [scheme]
for schema in schemes:
try:
sources = await dev.get_source_list(schema)
except SongpalException as ex:
click.echo("Unable to get sources for %s" % schema)
continue
for src in sources:
click.echo(src)
if src.isBrowsable:
try:
count = await dev.get_content_count(src.source)
if count.count > 0:
click.echo(" %s" % count)
for content in await dev.get_contents(src.source):
click.echo(" %s\n\t%s" % (content.title, content.uri))
else:
click.echo(" No content to list.")
except SongpalException as ex:
click.echo(" %s" % ex) | [
"async",
"def",
"source",
"(",
"dev",
":",
"Device",
",",
"scheme",
")",
":",
"if",
"scheme",
"is",
"None",
":",
"schemes",
"=",
"await",
"dev",
".",
"get_schemes",
"(",
")",
"schemes",
"=",
"[",
"scheme",
".",
"scheme",
"for",
"scheme",
"in",
"schem... | List available sources.
If no `scheme` is given, will list sources for all sc hemes. | [
"List",
"available",
"sources",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L311-L340 |
4,617 | rytilahti/python-songpal | songpal/main.py | volume | async def volume(dev: Device, volume, output):
"""Get and set the volume settings.
Passing 'mute' as new volume will mute the volume,
'unmute' removes it.
"""
vol = None
vol_controls = await dev.get_volume_information()
if output is not None:
click.echo("Using output: %s" % output)
output_uri = (await dev.get_zone(output)).uri
for v in vol_controls:
if v.output == output_uri:
vol = v
break
else:
vol = vol_controls[0]
if vol is None:
err("Unable to find volume controller: %s" % output)
return
if volume and volume == "mute":
click.echo("Muting")
await vol.set_mute(True)
elif volume and volume == "unmute":
click.echo("Unmuting")
await vol.set_mute(False)
elif volume:
click.echo("Setting volume to %s" % volume)
await vol.set_volume(volume)
if output is not None:
click.echo(vol)
else:
[click.echo(x) for x in vol_controls] | python | async def volume(dev: Device, volume, output):
vol = None
vol_controls = await dev.get_volume_information()
if output is not None:
click.echo("Using output: %s" % output)
output_uri = (await dev.get_zone(output)).uri
for v in vol_controls:
if v.output == output_uri:
vol = v
break
else:
vol = vol_controls[0]
if vol is None:
err("Unable to find volume controller: %s" % output)
return
if volume and volume == "mute":
click.echo("Muting")
await vol.set_mute(True)
elif volume and volume == "unmute":
click.echo("Unmuting")
await vol.set_mute(False)
elif volume:
click.echo("Setting volume to %s" % volume)
await vol.set_volume(volume)
if output is not None:
click.echo(vol)
else:
[click.echo(x) for x in vol_controls] | [
"async",
"def",
"volume",
"(",
"dev",
":",
"Device",
",",
"volume",
",",
"output",
")",
":",
"vol",
"=",
"None",
"vol_controls",
"=",
"await",
"dev",
".",
"get_volume_information",
"(",
")",
"if",
"output",
"is",
"not",
"None",
":",
"click",
".",
"echo... | Get and set the volume settings.
Passing 'mute' as new volume will mute the volume,
'unmute' removes it. | [
"Get",
"and",
"set",
"the",
"volume",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L348-L383 |
4,618 | rytilahti/python-songpal | songpal/main.py | schemes | async def schemes(dev: Device):
"""Print supported uri schemes."""
schemes = await dev.get_schemes()
for scheme in schemes:
click.echo(scheme) | python | async def schemes(dev: Device):
schemes = await dev.get_schemes()
for scheme in schemes:
click.echo(scheme) | [
"async",
"def",
"schemes",
"(",
"dev",
":",
"Device",
")",
":",
"schemes",
"=",
"await",
"dev",
".",
"get_schemes",
"(",
")",
"for",
"scheme",
"in",
"schemes",
":",
"click",
".",
"echo",
"(",
"scheme",
")"
] | Print supported uri schemes. | [
"Print",
"supported",
"uri",
"schemes",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L389-L393 |
4,619 | rytilahti/python-songpal | songpal/main.py | check_update | async def check_update(dev: Device, internet: bool, update: bool):
"""Print out update information."""
if internet:
print("Checking updates from network")
else:
print("Not checking updates from internet")
update_info = await dev.get_update_info(from_network=internet)
if not update_info.isUpdatable:
click.echo("No updates available.")
return
if not update:
click.echo("Update available: %s" % update_info)
click.echo("Use --update to activate update!")
else:
click.echo("Activating update, please be seated.")
res = await dev.activate_system_update()
click.echo("Update result: %s" % res) | python | async def check_update(dev: Device, internet: bool, update: bool):
if internet:
print("Checking updates from network")
else:
print("Not checking updates from internet")
update_info = await dev.get_update_info(from_network=internet)
if not update_info.isUpdatable:
click.echo("No updates available.")
return
if not update:
click.echo("Update available: %s" % update_info)
click.echo("Use --update to activate update!")
else:
click.echo("Activating update, please be seated.")
res = await dev.activate_system_update()
click.echo("Update result: %s" % res) | [
"async",
"def",
"check_update",
"(",
"dev",
":",
"Device",
",",
"internet",
":",
"bool",
",",
"update",
":",
"bool",
")",
":",
"if",
"internet",
":",
"print",
"(",
"\"Checking updates from network\"",
")",
"else",
":",
"print",
"(",
"\"Not checking updates fro... | Print out update information. | [
"Print",
"out",
"update",
"information",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L401-L417 |
4,620 | rytilahti/python-songpal | songpal/main.py | bluetooth | async def bluetooth(dev: Device, target, value):
"""Get or set bluetooth settings."""
if target and value:
await dev.set_bluetooth_settings(target, value)
print_settings(await dev.get_bluetooth_settings()) | python | async def bluetooth(dev: Device, target, value):
if target and value:
await dev.set_bluetooth_settings(target, value)
print_settings(await dev.get_bluetooth_settings()) | [
"async",
"def",
"bluetooth",
"(",
"dev",
":",
"Device",
",",
"target",
",",
"value",
")",
":",
"if",
"target",
"and",
"value",
":",
"await",
"dev",
".",
"set_bluetooth_settings",
"(",
"target",
",",
"value",
")",
"print_settings",
"(",
"await",
"dev",
".... | Get or set bluetooth settings. | [
"Get",
"or",
"set",
"bluetooth",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L425-L430 |
4,621 | rytilahti/python-songpal | songpal/main.py | settings | async def settings(dev: Device):
"""Print out all possible settings."""
settings_tree = await dev.get_settings()
for module in settings_tree:
await traverse_settings(dev, module.usage, module.settings) | python | async def settings(dev: Device):
settings_tree = await dev.get_settings()
for module in settings_tree:
await traverse_settings(dev, module.usage, module.settings) | [
"async",
"def",
"settings",
"(",
"dev",
":",
"Device",
")",
":",
"settings_tree",
"=",
"await",
"dev",
".",
"get_settings",
"(",
")",
"for",
"module",
"in",
"settings_tree",
":",
"await",
"traverse_settings",
"(",
"dev",
",",
"module",
".",
"usage",
",",
... | Print out all possible settings. | [
"Print",
"out",
"all",
"possible",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L453-L458 |
4,622 | rytilahti/python-songpal | songpal/main.py | storage | async def storage(dev: Device):
"""Print storage information."""
storages = await dev.get_storage_list()
for storage in storages:
click.echo(storage) | python | async def storage(dev: Device):
storages = await dev.get_storage_list()
for storage in storages:
click.echo(storage) | [
"async",
"def",
"storage",
"(",
"dev",
":",
"Device",
")",
":",
"storages",
"=",
"await",
"dev",
".",
"get_storage_list",
"(",
")",
"for",
"storage",
"in",
"storages",
":",
"click",
".",
"echo",
"(",
"storage",
")"
] | Print storage information. | [
"Print",
"storage",
"information",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L464-L468 |
4,623 | rytilahti/python-songpal | songpal/main.py | sound | async def sound(dev: Device, target, value):
"""Get or set sound settings."""
if target and value:
click.echo("Setting %s to %s" % (target, value))
click.echo(await dev.set_sound_settings(target, value))
print_settings(await dev.get_sound_settings()) | python | async def sound(dev: Device, target, value):
if target and value:
click.echo("Setting %s to %s" % (target, value))
click.echo(await dev.set_sound_settings(target, value))
print_settings(await dev.get_sound_settings()) | [
"async",
"def",
"sound",
"(",
"dev",
":",
"Device",
",",
"target",
",",
"value",
")",
":",
"if",
"target",
"and",
"value",
":",
"click",
".",
"echo",
"(",
"\"Setting %s to %s\"",
"%",
"(",
"target",
",",
"value",
")",
")",
"click",
".",
"echo",
"(",
... | Get or set sound settings. | [
"Get",
"or",
"set",
"sound",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L476-L482 |
4,624 | rytilahti/python-songpal | songpal/main.py | soundfield | async def soundfield(dev: Device, soundfield: str):
"""Get or set sound field."""
if soundfield is not None:
await dev.set_sound_settings("soundField", soundfield)
soundfields = await dev.get_sound_settings("soundField")
print_settings(soundfields) | python | async def soundfield(dev: Device, soundfield: str):
if soundfield is not None:
await dev.set_sound_settings("soundField", soundfield)
soundfields = await dev.get_sound_settings("soundField")
print_settings(soundfields) | [
"async",
"def",
"soundfield",
"(",
"dev",
":",
"Device",
",",
"soundfield",
":",
"str",
")",
":",
"if",
"soundfield",
"is",
"not",
"None",
":",
"await",
"dev",
".",
"set_sound_settings",
"(",
"\"soundField\"",
",",
"soundfield",
")",
"soundfields",
"=",
"a... | Get or set sound field. | [
"Get",
"or",
"set",
"sound",
"field",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L489-L494 |
4,625 | rytilahti/python-songpal | songpal/main.py | speaker | async def speaker(dev: Device, target, value):
"""Get and set external speaker settings."""
if target and value:
click.echo("Setting %s to %s" % (target, value))
await dev.set_speaker_settings(target, value)
print_settings(await dev.get_speaker_settings()) | python | async def speaker(dev: Device, target, value):
if target and value:
click.echo("Setting %s to %s" % (target, value))
await dev.set_speaker_settings(target, value)
print_settings(await dev.get_speaker_settings()) | [
"async",
"def",
"speaker",
"(",
"dev",
":",
"Device",
",",
"target",
",",
"value",
")",
":",
"if",
"target",
"and",
"value",
":",
"click",
".",
"echo",
"(",
"\"Setting %s to %s\"",
"%",
"(",
"target",
",",
"value",
")",
")",
"await",
"dev",
".",
"set... | Get and set external speaker settings. | [
"Get",
"and",
"set",
"external",
"speaker",
"settings",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L534-L540 |
4,626 | rytilahti/python-songpal | songpal/main.py | notifications | async def notifications(dev: Device, notification: str, listen_all: bool):
"""List available notifications and listen to them.
Using --listen-all [notification] allows to listen to all notifications
from the given subsystem.
If the subsystem is omited, notifications from all subsystems are
requested.
"""
notifications = await dev.get_notifications()
async def handle_notification(x):
click.echo("got notification: %s" % x)
if listen_all:
if notification is not None:
await dev.services[notification].listen_all_notifications(
handle_notification
)
else:
click.echo("Listening to all possible notifications")
await dev.listen_notifications(fallback_callback=handle_notification)
elif notification:
click.echo("Subscribing to notification %s" % notification)
for notif in notifications:
if notif.name == notification:
await notif.activate(handle_notification)
click.echo("Unable to find notification %s" % notification)
else:
click.echo(click.style("Available notifications", bold=True))
for notification in notifications:
click.echo("* %s" % notification) | python | async def notifications(dev: Device, notification: str, listen_all: bool):
notifications = await dev.get_notifications()
async def handle_notification(x):
click.echo("got notification: %s" % x)
if listen_all:
if notification is not None:
await dev.services[notification].listen_all_notifications(
handle_notification
)
else:
click.echo("Listening to all possible notifications")
await dev.listen_notifications(fallback_callback=handle_notification)
elif notification:
click.echo("Subscribing to notification %s" % notification)
for notif in notifications:
if notif.name == notification:
await notif.activate(handle_notification)
click.echo("Unable to find notification %s" % notification)
else:
click.echo(click.style("Available notifications", bold=True))
for notification in notifications:
click.echo("* %s" % notification) | [
"async",
"def",
"notifications",
"(",
"dev",
":",
"Device",
",",
"notification",
":",
"str",
",",
"listen_all",
":",
"bool",
")",
":",
"notifications",
"=",
"await",
"dev",
".",
"get_notifications",
"(",
")",
"async",
"def",
"handle_notification",
"(",
"x",
... | List available notifications and listen to them.
Using --listen-all [notification] allows to listen to all notifications
from the given subsystem.
If the subsystem is omited, notifications from all subsystems are
requested. | [
"List",
"available",
"notifications",
"and",
"listen",
"to",
"them",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L548-L581 |
4,627 | rytilahti/python-songpal | songpal/main.py | list_all | def list_all(dev: Device):
"""List all available API calls."""
for name, service in dev.services.items():
click.echo(click.style("\nService %s" % name, bold=True))
for method in service.methods:
click.echo(" %s" % method.name) | python | def list_all(dev: Device):
for name, service in dev.services.items():
click.echo(click.style("\nService %s" % name, bold=True))
for method in service.methods:
click.echo(" %s" % method.name) | [
"def",
"list_all",
"(",
"dev",
":",
"Device",
")",
":",
"for",
"name",
",",
"service",
"in",
"dev",
".",
"services",
".",
"items",
"(",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"\\nService %s\"",
"%",
"name",
",",
"bold",
... | List all available API calls. | [
"List",
"all",
"available",
"API",
"calls",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L594-L599 |
4,628 | rytilahti/python-songpal | songpal/main.py | command | async def command(dev, service, method, parameters):
"""Run a raw command."""
params = None
if parameters is not None:
params = ast.literal_eval(parameters)
click.echo("Calling %s.%s with params %s" % (service, method, params))
res = await dev.raw_command(service, method, params)
click.echo(res) | python | async def command(dev, service, method, parameters):
params = None
if parameters is not None:
params = ast.literal_eval(parameters)
click.echo("Calling %s.%s with params %s" % (service, method, params))
res = await dev.raw_command(service, method, params)
click.echo(res) | [
"async",
"def",
"command",
"(",
"dev",
",",
"service",
",",
"method",
",",
"parameters",
")",
":",
"params",
"=",
"None",
"if",
"parameters",
"is",
"not",
"None",
":",
"params",
"=",
"ast",
".",
"literal_eval",
"(",
"parameters",
")",
"click",
".",
"ec... | Run a raw command. | [
"Run",
"a",
"raw",
"command",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L608-L615 |
4,629 | rytilahti/python-songpal | songpal/main.py | dump_devinfo | async def dump_devinfo(dev: Device, file):
"""Dump developer information.
Pass `file` to write the results directly into a file.
"""
import attr
methods = await dev.get_supported_methods()
res = {
"supported_methods": {k: v.asdict() for k, v in methods.items()},
"settings": [attr.asdict(x) for x in await dev.get_settings()],
"sysinfo": attr.asdict(await dev.get_system_info()),
"interface_info": attr.asdict(await dev.get_interface_information()),
}
if file:
click.echo("Saving to file: %s" % file.name)
json.dump(res, file, sort_keys=True, indent=4)
else:
click.echo(json.dumps(res, sort_keys=True, indent=4)) | python | async def dump_devinfo(dev: Device, file):
import attr
methods = await dev.get_supported_methods()
res = {
"supported_methods": {k: v.asdict() for k, v in methods.items()},
"settings": [attr.asdict(x) for x in await dev.get_settings()],
"sysinfo": attr.asdict(await dev.get_system_info()),
"interface_info": attr.asdict(await dev.get_interface_information()),
}
if file:
click.echo("Saving to file: %s" % file.name)
json.dump(res, file, sort_keys=True, indent=4)
else:
click.echo(json.dumps(res, sort_keys=True, indent=4)) | [
"async",
"def",
"dump_devinfo",
"(",
"dev",
":",
"Device",
",",
"file",
")",
":",
"import",
"attr",
"methods",
"=",
"await",
"dev",
".",
"get_supported_methods",
"(",
")",
"res",
"=",
"{",
"\"supported_methods\"",
":",
"{",
"k",
":",
"v",
".",
"asdict",
... | Dump developer information.
Pass `file` to write the results directly into a file. | [
"Dump",
"developer",
"information",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L622-L640 |
4,630 | rytilahti/python-songpal | songpal/main.py | state | async def state(gc: GroupControl):
"""Current group state."""
state = await gc.state()
click.echo(state)
click.echo("Full state info: %s" % repr(state)) | python | async def state(gc: GroupControl):
state = await gc.state()
click.echo(state)
click.echo("Full state info: %s" % repr(state)) | [
"async",
"def",
"state",
"(",
"gc",
":",
"GroupControl",
")",
":",
"state",
"=",
"await",
"gc",
".",
"state",
"(",
")",
"click",
".",
"echo",
"(",
"state",
")",
"click",
".",
"echo",
"(",
"\"Full state info: %s\"",
"%",
"repr",
"(",
"state",
")",
")"... | Current group state. | [
"Current",
"group",
"state",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L667-L671 |
4,631 | rytilahti/python-songpal | songpal/main.py | create | async def create(gc: GroupControl, name, slaves):
"""Create new group"""
click.echo("Creating group %s with slaves: %s" % (name, slaves))
click.echo(await gc.create(name, slaves)) | python | async def create(gc: GroupControl, name, slaves):
click.echo("Creating group %s with slaves: %s" % (name, slaves))
click.echo(await gc.create(name, slaves)) | [
"async",
"def",
"create",
"(",
"gc",
":",
"GroupControl",
",",
"name",
",",
"slaves",
")",
":",
"click",
".",
"echo",
"(",
"\"Creating group %s with slaves: %s\"",
"%",
"(",
"name",
",",
"slaves",
")",
")",
"click",
".",
"echo",
"(",
"await",
"gc",
".",
... | Create new group | [
"Create",
"new",
"group"
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L697-L700 |
4,632 | rytilahti/python-songpal | songpal/main.py | add | async def add(gc: GroupControl, slaves):
"""Add speakers to group."""
click.echo("Adding to existing group: %s" % slaves)
click.echo(await gc.add(slaves)) | python | async def add(gc: GroupControl, slaves):
click.echo("Adding to existing group: %s" % slaves)
click.echo(await gc.add(slaves)) | [
"async",
"def",
"add",
"(",
"gc",
":",
"GroupControl",
",",
"slaves",
")",
":",
"click",
".",
"echo",
"(",
"\"Adding to existing group: %s\"",
"%",
"slaves",
")",
"click",
".",
"echo",
"(",
"await",
"gc",
".",
"add",
"(",
"slaves",
")",
")"
] | Add speakers to group. | [
"Add",
"speakers",
"to",
"group",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L715-L718 |
4,633 | rytilahti/python-songpal | songpal/main.py | remove | async def remove(gc: GroupControl, slaves):
"""Remove speakers from group."""
click.echo("Removing from existing group: %s" % slaves)
click.echo(await gc.remove(slaves)) | python | async def remove(gc: GroupControl, slaves):
click.echo("Removing from existing group: %s" % slaves)
click.echo(await gc.remove(slaves)) | [
"async",
"def",
"remove",
"(",
"gc",
":",
"GroupControl",
",",
"slaves",
")",
":",
"click",
".",
"echo",
"(",
"\"Removing from existing group: %s\"",
"%",
"slaves",
")",
"click",
".",
"echo",
"(",
"await",
"gc",
".",
"remove",
"(",
"slaves",
")",
")"
] | Remove speakers from group. | [
"Remove",
"speakers",
"from",
"group",
"."
] | 0443de6b3d960b9067a851d82261ca00e46b4618 | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L724-L727 |
4,634 | kanboard/python-api-client | kanboard/client.py | Kanboard.execute | def execute(self, method, **kwargs):
"""
Call remote API procedure
Args:
method: Procedure name
kwargs: Procedure named arguments
Returns:
Procedure result
Raises:
urllib2.HTTPError: Any HTTP error (Python 2)
urllib.error.HTTPError: Any HTTP error (Python 3)
"""
payload = {
'id': 1,
'jsonrpc': '2.0',
'method': method,
'params': kwargs
}
credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode())
auth_header_prefix = 'Basic ' if self._auth_header == DEFAULT_AUTH_HEADER else ''
headers = {
self._auth_header: auth_header_prefix + credentials.decode(),
'Content-Type': 'application/json',
}
return self._do_request(headers, payload) | python | def execute(self, method, **kwargs):
payload = {
'id': 1,
'jsonrpc': '2.0',
'method': method,
'params': kwargs
}
credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode())
auth_header_prefix = 'Basic ' if self._auth_header == DEFAULT_AUTH_HEADER else ''
headers = {
self._auth_header: auth_header_prefix + credentials.decode(),
'Content-Type': 'application/json',
}
return self._do_request(headers, payload) | [
"def",
"execute",
"(",
"self",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"'id'",
":",
"1",
",",
"'jsonrpc'",
":",
"'2.0'",
",",
"'method'",
":",
"method",
",",
"'params'",
":",
"kwargs",
"}",
"credentials",
"=",
"base64",... | Call remote API procedure
Args:
method: Procedure name
kwargs: Procedure named arguments
Returns:
Procedure result
Raises:
urllib2.HTTPError: Any HTTP error (Python 2)
urllib.error.HTTPError: Any HTTP error (Python 3) | [
"Call",
"remote",
"API",
"procedure"
] | a1e81094bb399a9a3f4f14de67406e1d2bbee393 | https://github.com/kanboard/python-api-client/blob/a1e81094bb399a9a3f4f14de67406e1d2bbee393/kanboard/client.py#L106-L135 |
4,635 | bwesterb/py-tarjan | src/tc.py | tc | def tc(g):
""" Given a graph @g, returns the transitive closure of @g """
ret = {}
for scc in tarjan(g):
ws = set()
ews = set()
for v in scc:
ws.update(g[v])
for w in ws:
assert w in ret or w in scc
ews.add(w)
ews.update(ret.get(w,()))
if len(scc) > 1:
ews.update(scc)
ews = tuple(ews)
for v in scc:
ret[v] = ews
return ret | python | def tc(g):
ret = {}
for scc in tarjan(g):
ws = set()
ews = set()
for v in scc:
ws.update(g[v])
for w in ws:
assert w in ret or w in scc
ews.add(w)
ews.update(ret.get(w,()))
if len(scc) > 1:
ews.update(scc)
ews = tuple(ews)
for v in scc:
ret[v] = ews
return ret | [
"def",
"tc",
"(",
"g",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"scc",
"in",
"tarjan",
"(",
"g",
")",
":",
"ws",
"=",
"set",
"(",
")",
"ews",
"=",
"set",
"(",
")",
"for",
"v",
"in",
"scc",
":",
"ws",
".",
"update",
"(",
"g",
"[",
"v",
"]"... | Given a graph @g, returns the transitive closure of @g | [
"Given",
"a",
"graph"
] | 60b0e3a1a7b925514fdce2ffbd84e1e246aba6d8 | https://github.com/bwesterb/py-tarjan/blob/60b0e3a1a7b925514fdce2ffbd84e1e246aba6d8/src/tc.py#L3-L20 |
4,636 | manolomartinez/greg | greg/classes.py | Session.list_feeds | def list_feeds(self):
"""
Output a list of all feed names
"""
feeds = configparser.ConfigParser()
feeds.read(self.data_filename)
return feeds.sections() | python | def list_feeds(self):
feeds = configparser.ConfigParser()
feeds.read(self.data_filename)
return feeds.sections() | [
"def",
"list_feeds",
"(",
"self",
")",
":",
"feeds",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"feeds",
".",
"read",
"(",
"self",
".",
"data_filename",
")",
"return",
"feeds",
".",
"sections",
"(",
")"
] | Output a list of all feed names | [
"Output",
"a",
"list",
"of",
"all",
"feed",
"names"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L52-L58 |
4,637 | manolomartinez/greg | greg/classes.py | Session.retrieve_config_file | def retrieve_config_file(self):
"""
Retrieve config file
"""
try:
if self.args["configfile"]:
return self.args["configfile"]
except KeyError:
pass
return os.path.expanduser('~/.config/greg/greg.conf') | python | def retrieve_config_file(self):
try:
if self.args["configfile"]:
return self.args["configfile"]
except KeyError:
pass
return os.path.expanduser('~/.config/greg/greg.conf') | [
"def",
"retrieve_config_file",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"args",
"[",
"\"configfile\"",
"]",
":",
"return",
"self",
".",
"args",
"[",
"\"configfile\"",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"os",
".",
"path",
".",
... | Retrieve config file | [
"Retrieve",
"config",
"file"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L60-L69 |
4,638 | manolomartinez/greg | greg/classes.py | Session.retrieve_data_directory | def retrieve_data_directory(self):
"""
Retrieve the data directory
Look first into config_filename_global
then into config_filename_user. The latter takes preeminence.
"""
args = self.args
try:
if args['datadirectory']:
aux.ensure_dir(args['datadirectory'])
return args['datadirectory']
except KeyError:
pass
config = configparser.ConfigParser()
config.read([config_filename_global, self.config_filename_user])
section = config.default_section
data_path = config.get(section, 'Data directory',
fallback='~/.local/share/greg')
data_path_expanded = os.path.expanduser(data_path)
aux.ensure_dir(data_path_expanded)
return os.path.expanduser(data_path_expanded) | python | def retrieve_data_directory(self):
args = self.args
try:
if args['datadirectory']:
aux.ensure_dir(args['datadirectory'])
return args['datadirectory']
except KeyError:
pass
config = configparser.ConfigParser()
config.read([config_filename_global, self.config_filename_user])
section = config.default_section
data_path = config.get(section, 'Data directory',
fallback='~/.local/share/greg')
data_path_expanded = os.path.expanduser(data_path)
aux.ensure_dir(data_path_expanded)
return os.path.expanduser(data_path_expanded) | [
"def",
"retrieve_data_directory",
"(",
"self",
")",
":",
"args",
"=",
"self",
".",
"args",
"try",
":",
"if",
"args",
"[",
"'datadirectory'",
"]",
":",
"aux",
".",
"ensure_dir",
"(",
"args",
"[",
"'datadirectory'",
"]",
")",
"return",
"args",
"[",
"'datad... | Retrieve the data directory
Look first into config_filename_global
then into config_filename_user. The latter takes preeminence. | [
"Retrieve",
"the",
"data",
"directory",
"Look",
"first",
"into",
"config_filename_global",
"then",
"into",
"config_filename_user",
".",
"The",
"latter",
"takes",
"preeminence",
"."
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L71-L91 |
4,639 | manolomartinez/greg | greg/classes.py | Feed.will_tag | def will_tag(self):
"""
Check whether the feed should be tagged
"""
wanttags = self.retrieve_config('Tag', 'no')
if wanttags == 'yes':
if aux.staggerexists:
willtag = True
else:
willtag = False
print(("You want me to tag {0}, but you have not installed "
"the Stagger module. I cannot honour your request.").
format(self.name), file=sys.stderr, flush=True)
else:
willtag = False
return willtag | python | def will_tag(self):
wanttags = self.retrieve_config('Tag', 'no')
if wanttags == 'yes':
if aux.staggerexists:
willtag = True
else:
willtag = False
print(("You want me to tag {0}, but you have not installed "
"the Stagger module. I cannot honour your request.").
format(self.name), file=sys.stderr, flush=True)
else:
willtag = False
return willtag | [
"def",
"will_tag",
"(",
"self",
")",
":",
"wanttags",
"=",
"self",
".",
"retrieve_config",
"(",
"'Tag'",
",",
"'no'",
")",
"if",
"wanttags",
"==",
"'yes'",
":",
"if",
"aux",
".",
"staggerexists",
":",
"willtag",
"=",
"True",
"else",
":",
"willtag",
"="... | Check whether the feed should be tagged | [
"Check",
"whether",
"the",
"feed",
"should",
"be",
"tagged"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L202-L217 |
4,640 | manolomartinez/greg | greg/classes.py | Feed.how_many | def how_many(self):
"""
Ascertain where to start downloading, and how many entries.
"""
if self.linkdates != []:
# What follows is a quick sanity check: if the entry date is in the
# future, this is probably a mistake, and we just count the entry
# date as right now.
if max(self.linkdates) <= list(time.localtime()):
currentdate = max(self.linkdates)
else:
currentdate = list(time.localtime())
print(("This entry has its date set in the future. "
"I will use your current local time as its date "
"instead."),
file=sys.stderr, flush=True)
stop = sys.maxsize
else:
currentdate = [1, 1, 1, 0, 0]
firstsync = self.retrieve_config('firstsync', '1')
if firstsync == 'all':
stop = sys.maxsize
else:
stop = int(firstsync)
return currentdate, stop | python | def how_many(self):
if self.linkdates != []:
# What follows is a quick sanity check: if the entry date is in the
# future, this is probably a mistake, and we just count the entry
# date as right now.
if max(self.linkdates) <= list(time.localtime()):
currentdate = max(self.linkdates)
else:
currentdate = list(time.localtime())
print(("This entry has its date set in the future. "
"I will use your current local time as its date "
"instead."),
file=sys.stderr, flush=True)
stop = sys.maxsize
else:
currentdate = [1, 1, 1, 0, 0]
firstsync = self.retrieve_config('firstsync', '1')
if firstsync == 'all':
stop = sys.maxsize
else:
stop = int(firstsync)
return currentdate, stop | [
"def",
"how_many",
"(",
"self",
")",
":",
"if",
"self",
".",
"linkdates",
"!=",
"[",
"]",
":",
"# What follows is a quick sanity check: if the entry date is in the",
"# future, this is probably a mistake, and we just count the entry",
"# date as right now.",
"if",
"max",
"(",
... | Ascertain where to start downloading, and how many entries. | [
"Ascertain",
"where",
"to",
"start",
"downloading",
"and",
"how",
"many",
"entries",
"."
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L219-L243 |
4,641 | manolomartinez/greg | greg/classes.py | Feed.fix_linkdate | def fix_linkdate(self, entry):
"""
Give a date for the entry, depending on feed.sync_by_date
Save it as feed.linkdate
"""
if self.sync_by_date:
try:
entry.linkdate = list(entry.published_parsed)
self.linkdate = list(entry.published_parsed)
except (AttributeError, TypeError):
try:
entry.linkdate = list(entry.updated_parsed)
self.linkdate = list(entry.updated_parsed)
except (AttributeError, TypeError):
print(("This entry doesn't seem to have a parseable date. "
"I will use your local time instead."),
file=sys.stderr, flush=True)
entry.linkdate = list(time.localtime())
self.linkdate = list(time.localtime())
else:
entry.linkdate = list(time.localtime()) | python | def fix_linkdate(self, entry):
if self.sync_by_date:
try:
entry.linkdate = list(entry.published_parsed)
self.linkdate = list(entry.published_parsed)
except (AttributeError, TypeError):
try:
entry.linkdate = list(entry.updated_parsed)
self.linkdate = list(entry.updated_parsed)
except (AttributeError, TypeError):
print(("This entry doesn't seem to have a parseable date. "
"I will use your local time instead."),
file=sys.stderr, flush=True)
entry.linkdate = list(time.localtime())
self.linkdate = list(time.localtime())
else:
entry.linkdate = list(time.localtime()) | [
"def",
"fix_linkdate",
"(",
"self",
",",
"entry",
")",
":",
"if",
"self",
".",
"sync_by_date",
":",
"try",
":",
"entry",
".",
"linkdate",
"=",
"list",
"(",
"entry",
".",
"published_parsed",
")",
"self",
".",
"linkdate",
"=",
"list",
"(",
"entry",
".",
... | Give a date for the entry, depending on feed.sync_by_date
Save it as feed.linkdate | [
"Give",
"a",
"date",
"for",
"the",
"entry",
"depending",
"on",
"feed",
".",
"sync_by_date",
"Save",
"it",
"as",
"feed",
".",
"linkdate"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L245-L265 |
4,642 | manolomartinez/greg | greg/classes.py | Feed.retrieve_mime | def retrieve_mime(self):
"""
Check the mime-type to download
"""
mime = self.retrieve_config('mime', 'audio')
mimedict = {"number": mime}
# the input that parse_for_download expects
return aux.parse_for_download(mimedict) | python | def retrieve_mime(self):
mime = self.retrieve_config('mime', 'audio')
mimedict = {"number": mime}
# the input that parse_for_download expects
return aux.parse_for_download(mimedict) | [
"def",
"retrieve_mime",
"(",
"self",
")",
":",
"mime",
"=",
"self",
".",
"retrieve_config",
"(",
"'mime'",
",",
"'audio'",
")",
"mimedict",
"=",
"{",
"\"number\"",
":",
"mime",
"}",
"# the input that parse_for_download expects",
"return",
"aux",
".",
"parse_for_... | Check the mime-type to download | [
"Check",
"the",
"mime",
"-",
"type",
"to",
"download"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L267-L274 |
4,643 | manolomartinez/greg | greg/classes.py | Feed.download_entry | def download_entry(self, entry):
"""
Find entry link and download entry
"""
downloadlinks = {}
downloaded = False
ignoreenclosures = self.retrieve_config('ignoreenclosures', 'no')
notype = self.retrieve_config('notype', 'no')
if ignoreenclosures == 'no':
for enclosure in entry.enclosures:
if notype == 'yes':
downloadlinks[urlparse(enclosure["href"]).path.split(
"/")[-1]] = enclosure["href"]
# preserve original name
else:
try:
# We will download all enclosures of the desired
# mime-type
if any([mimetype in enclosure["type"] for mimetype in
self.mime]):
downloadlinks[urlparse(
enclosure["href"]).path.split(
"/")[-1]] = enclosure["href"]
# preserve original name
except KeyError:
print("This podcast carries no information about "
"enclosure types. Try using the notype "
"option in your greg.conf", file=sys.stderr,
flush=True)
else:
downloadlinks[urlparse(entry.link).query.split(
"/")[-1]] = entry.link
for podname in downloadlinks:
if (podname, entry.linkdate) not in zip(self.entrylinks,
self.linkdates):
try:
title = entry.title
except:
title = podname
try:
sanitizedsummary = aux.html_to_text(entry.summary)
if sanitizedsummary == "":
sanitizedsummary = "No summary available"
except:
sanitizedsummary = "No summary available"
try:
placeholders = Placeholders(
self, entry, downloadlinks[podname], podname, title,
sanitizedsummary)
placeholders = aux.check_directory(placeholders)
condition = aux.filtercond(placeholders)
if condition:
print("Downloading {} -- {}".format(title, podname))
aux.download_handler(self, placeholders)
if self.willtag:
aux.tag(placeholders)
downloaded = True
else:
print("Skipping {} -- {}".format(title, podname))
downloaded = False
if self.info:
with open(self.info, 'a') as current:
# We write to file this often to ensure that
# downloaded entries count as downloaded.
current.write(''.join([podname, ' ',
str(entry.linkdate), '\n']))
except URLError:
sys.exit(("... something went wrong. "
"Are you connected to the internet?"))
return downloaded | python | def download_entry(self, entry):
downloadlinks = {}
downloaded = False
ignoreenclosures = self.retrieve_config('ignoreenclosures', 'no')
notype = self.retrieve_config('notype', 'no')
if ignoreenclosures == 'no':
for enclosure in entry.enclosures:
if notype == 'yes':
downloadlinks[urlparse(enclosure["href"]).path.split(
"/")[-1]] = enclosure["href"]
# preserve original name
else:
try:
# We will download all enclosures of the desired
# mime-type
if any([mimetype in enclosure["type"] for mimetype in
self.mime]):
downloadlinks[urlparse(
enclosure["href"]).path.split(
"/")[-1]] = enclosure["href"]
# preserve original name
except KeyError:
print("This podcast carries no information about "
"enclosure types. Try using the notype "
"option in your greg.conf", file=sys.stderr,
flush=True)
else:
downloadlinks[urlparse(entry.link).query.split(
"/")[-1]] = entry.link
for podname in downloadlinks:
if (podname, entry.linkdate) not in zip(self.entrylinks,
self.linkdates):
try:
title = entry.title
except:
title = podname
try:
sanitizedsummary = aux.html_to_text(entry.summary)
if sanitizedsummary == "":
sanitizedsummary = "No summary available"
except:
sanitizedsummary = "No summary available"
try:
placeholders = Placeholders(
self, entry, downloadlinks[podname], podname, title,
sanitizedsummary)
placeholders = aux.check_directory(placeholders)
condition = aux.filtercond(placeholders)
if condition:
print("Downloading {} -- {}".format(title, podname))
aux.download_handler(self, placeholders)
if self.willtag:
aux.tag(placeholders)
downloaded = True
else:
print("Skipping {} -- {}".format(title, podname))
downloaded = False
if self.info:
with open(self.info, 'a') as current:
# We write to file this often to ensure that
# downloaded entries count as downloaded.
current.write(''.join([podname, ' ',
str(entry.linkdate), '\n']))
except URLError:
sys.exit(("... something went wrong. "
"Are you connected to the internet?"))
return downloaded | [
"def",
"download_entry",
"(",
"self",
",",
"entry",
")",
":",
"downloadlinks",
"=",
"{",
"}",
"downloaded",
"=",
"False",
"ignoreenclosures",
"=",
"self",
".",
"retrieve_config",
"(",
"'ignoreenclosures'",
",",
"'no'",
")",
"notype",
"=",
"self",
".",
"retri... | Find entry link and download entry | [
"Find",
"entry",
"link",
"and",
"download",
"entry"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L276-L345 |
4,644 | manolomartinez/greg | greg/parser.py | main | def main():
"""
Parse the args and call whatever function was selected
"""
args = parser.parse_args()
try:
function = args.func
except AttributeError:
parser.print_usage()
parser.exit(1)
function(vars(args)) | python | def main():
args = parser.parse_args()
try:
function = args.func
except AttributeError:
parser.print_usage()
parser.exit(1)
function(vars(args)) | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"try",
":",
"function",
"=",
"args",
".",
"func",
"except",
"AttributeError",
":",
"parser",
".",
"print_usage",
"(",
")",
"parser",
".",
"exit",
"(",
"1",
")",
"functi... | Parse the args and call whatever function was selected | [
"Parse",
"the",
"args",
"and",
"call",
"whatever",
"function",
"was",
"selected"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/parser.py#L128-L138 |
4,645 | manolomartinez/greg | greg/commands.py | add | def add(args):
"""
Add a new feed
"""
session = c.Session(args)
if args["name"] in session.feeds.sections():
sys.exit("You already have a feed with that name.")
if args["name"] in ["all", "DEFAULT"]:
sys.exit(
("greg uses ""{}"" for a special purpose."
"Please choose another name for your feed.").format(args["name"]))
entry = {}
for key, value in args.items():
if value is not None and key != "func" and key != "name":
entry[key] = value
session.feeds[args["name"]] = entry
with open(session.data_filename, 'w') as configfile:
session.feeds.write(configfile) | python | def add(args):
session = c.Session(args)
if args["name"] in session.feeds.sections():
sys.exit("You already have a feed with that name.")
if args["name"] in ["all", "DEFAULT"]:
sys.exit(
("greg uses ""{}"" for a special purpose."
"Please choose another name for your feed.").format(args["name"]))
entry = {}
for key, value in args.items():
if value is not None and key != "func" and key != "name":
entry[key] = value
session.feeds[args["name"]] = entry
with open(session.data_filename, 'w') as configfile:
session.feeds.write(configfile) | [
"def",
"add",
"(",
"args",
")",
":",
"session",
"=",
"c",
".",
"Session",
"(",
"args",
")",
"if",
"args",
"[",
"\"name\"",
"]",
"in",
"session",
".",
"feeds",
".",
"sections",
"(",
")",
":",
"sys",
".",
"exit",
"(",
"\"You already have a feed with that... | Add a new feed | [
"Add",
"a",
"new",
"feed"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L35-L52 |
4,646 | manolomartinez/greg | greg/commands.py | info | def info(args):
"""
Provide information of a number of feeds
"""
session = c.Session(args)
if "all" in args["names"]:
feeds = session.list_feeds()
else:
feeds = args["names"]
for feed in feeds:
aux.pretty_print(session, feed) | python | def info(args):
session = c.Session(args)
if "all" in args["names"]:
feeds = session.list_feeds()
else:
feeds = args["names"]
for feed in feeds:
aux.pretty_print(session, feed) | [
"def",
"info",
"(",
"args",
")",
":",
"session",
"=",
"c",
".",
"Session",
"(",
"args",
")",
"if",
"\"all\"",
"in",
"args",
"[",
"\"names\"",
"]",
":",
"feeds",
"=",
"session",
".",
"list_feeds",
"(",
")",
"else",
":",
"feeds",
"=",
"args",
"[",
... | Provide information of a number of feeds | [
"Provide",
"information",
"of",
"a",
"number",
"of",
"feeds"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L120-L130 |
4,647 | manolomartinez/greg | greg/commands.py | sync | def sync(args):
"""
Implement the 'greg sync' command
"""
import operator
session = c.Session(args)
if "all" in args["names"]:
targetfeeds = session.list_feeds()
else:
targetfeeds = []
for name in args["names"]:
if name not in session.feeds:
print("You don't have a feed called {}."
.format(name), file=sys.stderr, flush=True)
else:
targetfeeds.append(name)
for target in targetfeeds:
feed = c.Feed(session, target, None)
if not feed.wentwrong:
try:
title = feed.podcast.target.title
except AttributeError:
title = target
print("Checking", title, end="...\n")
currentdate, stop = feed.how_many()
entrycounter = 0
entries_to_download = feed.podcast.entries
for entry in entries_to_download:
feed.fix_linkdate(entry)
# Sort entries_to_download, but only if you want to download as
# many as there are
if stop >= len(entries_to_download):
entries_to_download.sort(key=operator.attrgetter("linkdate"),
reverse=False)
for entry in entries_to_download:
if entry.linkdate > currentdate:
downloaded = feed.download_entry(entry)
entrycounter += downloaded
if entrycounter >= stop:
break
print("Done")
else:
msg = ''.join(["I cannot sync ", feed,
" just now. Are you connected to the internet?"])
print(msg, file=sys.stderr, flush=True) | python | def sync(args):
import operator
session = c.Session(args)
if "all" in args["names"]:
targetfeeds = session.list_feeds()
else:
targetfeeds = []
for name in args["names"]:
if name not in session.feeds:
print("You don't have a feed called {}."
.format(name), file=sys.stderr, flush=True)
else:
targetfeeds.append(name)
for target in targetfeeds:
feed = c.Feed(session, target, None)
if not feed.wentwrong:
try:
title = feed.podcast.target.title
except AttributeError:
title = target
print("Checking", title, end="...\n")
currentdate, stop = feed.how_many()
entrycounter = 0
entries_to_download = feed.podcast.entries
for entry in entries_to_download:
feed.fix_linkdate(entry)
# Sort entries_to_download, but only if you want to download as
# many as there are
if stop >= len(entries_to_download):
entries_to_download.sort(key=operator.attrgetter("linkdate"),
reverse=False)
for entry in entries_to_download:
if entry.linkdate > currentdate:
downloaded = feed.download_entry(entry)
entrycounter += downloaded
if entrycounter >= stop:
break
print("Done")
else:
msg = ''.join(["I cannot sync ", feed,
" just now. Are you connected to the internet?"])
print(msg, file=sys.stderr, flush=True) | [
"def",
"sync",
"(",
"args",
")",
":",
"import",
"operator",
"session",
"=",
"c",
".",
"Session",
"(",
"args",
")",
"if",
"\"all\"",
"in",
"args",
"[",
"\"names\"",
"]",
":",
"targetfeeds",
"=",
"session",
".",
"list_feeds",
"(",
")",
"else",
":",
"ta... | Implement the 'greg sync' command | [
"Implement",
"the",
"greg",
"sync",
"command"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L140-L184 |
4,648 | manolomartinez/greg | greg/commands.py | check | def check(args):
"""
Implement the 'greg check' command
"""
session = c.Session(args)
if str(args["url"]) != 'None':
url = args["url"]
name = "DEFAULT"
else:
try:
url = session.feeds[args["feed"]]["url"]
name = args["feed"]
except KeyError:
sys.exit("You don't appear to have a feed with that name.")
podcast = aux.parse_podcast(url)
for entry in enumerate(podcast.entries):
listentry = list(entry)
print(listentry[0], end=": ")
try:
print(listentry[1]["title"], end=" (")
except:
print(listentry[1]["link"], end=" (")
try:
print(listentry[1]["updated"], end=")")
except:
print("", end=")")
print()
dumpfilename = os.path.join(session.data_dir, 'feeddump')
with open(dumpfilename, mode='wb') as dumpfile:
dump = [name, podcast]
pickle.dump(dump, dumpfile) | python | def check(args):
session = c.Session(args)
if str(args["url"]) != 'None':
url = args["url"]
name = "DEFAULT"
else:
try:
url = session.feeds[args["feed"]]["url"]
name = args["feed"]
except KeyError:
sys.exit("You don't appear to have a feed with that name.")
podcast = aux.parse_podcast(url)
for entry in enumerate(podcast.entries):
listentry = list(entry)
print(listentry[0], end=": ")
try:
print(listentry[1]["title"], end=" (")
except:
print(listentry[1]["link"], end=" (")
try:
print(listentry[1]["updated"], end=")")
except:
print("", end=")")
print()
dumpfilename = os.path.join(session.data_dir, 'feeddump')
with open(dumpfilename, mode='wb') as dumpfile:
dump = [name, podcast]
pickle.dump(dump, dumpfile) | [
"def",
"check",
"(",
"args",
")",
":",
"session",
"=",
"c",
".",
"Session",
"(",
"args",
")",
"if",
"str",
"(",
"args",
"[",
"\"url\"",
"]",
")",
"!=",
"'None'",
":",
"url",
"=",
"args",
"[",
"\"url\"",
"]",
"name",
"=",
"\"DEFAULT\"",
"else",
":... | Implement the 'greg check' command | [
"Implement",
"the",
"greg",
"check",
"command"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L187-L217 |
4,649 | manolomartinez/greg | greg/aux_functions.py | parse_podcast | def parse_podcast(url):
"""
Try to parse podcast
"""
try:
podcast = feedparser.parse(url)
wentwrong = "urlopen" in str(podcast["bozo_exception"])
except KeyError:
wentwrong = False
if wentwrong:
print("Error: ", url, ": ", str(podcast["bozo_exception"]))
return podcast | python | def parse_podcast(url):
try:
podcast = feedparser.parse(url)
wentwrong = "urlopen" in str(podcast["bozo_exception"])
except KeyError:
wentwrong = False
if wentwrong:
print("Error: ", url, ": ", str(podcast["bozo_exception"]))
return podcast | [
"def",
"parse_podcast",
"(",
"url",
")",
":",
"try",
":",
"podcast",
"=",
"feedparser",
".",
"parse",
"(",
"url",
")",
"wentwrong",
"=",
"\"urlopen\"",
"in",
"str",
"(",
"podcast",
"[",
"\"bozo_exception\"",
"]",
")",
"except",
"KeyError",
":",
"wentwrong"... | Try to parse podcast | [
"Try",
"to",
"parse",
"podcast"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L93-L104 |
4,650 | manolomartinez/greg | greg/aux_functions.py | check_directory | def check_directory(placeholders):
"""
Find out, and create if needed,
the directory in which the feed will be downloaded
"""
feed = placeholders.feed
args = feed.args
placeholders.directory = "This very directory" # wink, wink
placeholders.fullpath = os.path.join(
placeholders.directory, placeholders.filename)
try:
if args["downloaddirectory"]:
ensure_dir(args["downloaddirectory"])
placeholders.directory = args["downloaddirectory"]
except KeyError:
pass
download_path = os.path.expanduser(
feed.retrieve_config("Download Directory", "~/Podcasts"))
subdirectory = feed.retrieve_config(
"Create subdirectory", "no")
if "no" in subdirectory:
placeholders.directory = download_path
elif "yes" in subdirectory:
subdnametemplate = feed.retrieve_config(
"subdirectory_name", "{podcasttitle}")
subdname = substitute_placeholders(
subdnametemplate, placeholders)
placeholders.directory = os.path.join(download_path, subdname)
ensure_dir(placeholders.directory)
placeholders.fullpath = os.path.join(
placeholders.directory, placeholders.filename)
return placeholders | python | def check_directory(placeholders):
feed = placeholders.feed
args = feed.args
placeholders.directory = "This very directory" # wink, wink
placeholders.fullpath = os.path.join(
placeholders.directory, placeholders.filename)
try:
if args["downloaddirectory"]:
ensure_dir(args["downloaddirectory"])
placeholders.directory = args["downloaddirectory"]
except KeyError:
pass
download_path = os.path.expanduser(
feed.retrieve_config("Download Directory", "~/Podcasts"))
subdirectory = feed.retrieve_config(
"Create subdirectory", "no")
if "no" in subdirectory:
placeholders.directory = download_path
elif "yes" in subdirectory:
subdnametemplate = feed.retrieve_config(
"subdirectory_name", "{podcasttitle}")
subdname = substitute_placeholders(
subdnametemplate, placeholders)
placeholders.directory = os.path.join(download_path, subdname)
ensure_dir(placeholders.directory)
placeholders.fullpath = os.path.join(
placeholders.directory, placeholders.filename)
return placeholders | [
"def",
"check_directory",
"(",
"placeholders",
")",
":",
"feed",
"=",
"placeholders",
".",
"feed",
"args",
"=",
"feed",
".",
"args",
"placeholders",
".",
"directory",
"=",
"\"This very directory\"",
"# wink, wink",
"placeholders",
".",
"fullpath",
"=",
"os",
"."... | Find out, and create if needed,
the directory in which the feed will be downloaded | [
"Find",
"out",
"and",
"create",
"if",
"needed",
"the",
"directory",
"in",
"which",
"the",
"feed",
"will",
"be",
"downloaded"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L116-L147 |
4,651 | manolomartinez/greg | greg/aux_functions.py | tag | def tag(placeholders):
"""
Tag the file at podpath with the information in podcast and entry
"""
# We first recover the name of the file to be tagged...
template = placeholders.feed.retrieve_config("file_to_tag", "{filename}")
filename = substitute_placeholders(template, placeholders)
podpath = os.path.join(placeholders.directory, filename)
# ... and this is it
# now we create a dictionary of tags and values
tagdict = placeholders.feed.defaulttagdict # these are the defaults
try: # We do as if there was a section with potential tag info
feedoptions = placeholders.feed.config.options(placeholders.name)
# this monstruous concatenation of classes... surely a bad idea.
tags = [[option.replace("tag_", ""), placeholders.feed.config[
placeholders.name][option]] for option in feedoptions if "tag_" in
option] # these are the tags to be filled
if tags:
for tag in tags:
tagdict[tag[0]] = tag[1]
except configparser.NoSectionError:
pass
for tag in tagdict:
metadata = substitute_placeholders(
tagdict[tag], placeholders)
if metadata:
stagger.util.set_frames(podpath, {tag: metadata})
else:
stagger.util.remove_frames(podpath, tag) | python | def tag(placeholders):
# We first recover the name of the file to be tagged...
template = placeholders.feed.retrieve_config("file_to_tag", "{filename}")
filename = substitute_placeholders(template, placeholders)
podpath = os.path.join(placeholders.directory, filename)
# ... and this is it
# now we create a dictionary of tags and values
tagdict = placeholders.feed.defaulttagdict # these are the defaults
try: # We do as if there was a section with potential tag info
feedoptions = placeholders.feed.config.options(placeholders.name)
# this monstruous concatenation of classes... surely a bad idea.
tags = [[option.replace("tag_", ""), placeholders.feed.config[
placeholders.name][option]] for option in feedoptions if "tag_" in
option] # these are the tags to be filled
if tags:
for tag in tags:
tagdict[tag[0]] = tag[1]
except configparser.NoSectionError:
pass
for tag in tagdict:
metadata = substitute_placeholders(
tagdict[tag], placeholders)
if metadata:
stagger.util.set_frames(podpath, {tag: metadata})
else:
stagger.util.remove_frames(podpath, tag) | [
"def",
"tag",
"(",
"placeholders",
")",
":",
"# We first recover the name of the file to be tagged...",
"template",
"=",
"placeholders",
".",
"feed",
".",
"retrieve_config",
"(",
"\"file_to_tag\"",
",",
"\"{filename}\"",
")",
"filename",
"=",
"substitute_placeholders",
"(... | Tag the file at podpath with the information in podcast and entry | [
"Tag",
"the",
"file",
"at",
"podpath",
"with",
"the",
"information",
"in",
"podcast",
"and",
"entry"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L171-L200 |
4,652 | manolomartinez/greg | greg/aux_functions.py | download_handler | def download_handler(feed, placeholders):
import shlex
"""
Parse and execute the download handler
"""
value = feed.retrieve_config('downloadhandler', 'greg')
if value == 'greg':
while os.path.isfile(placeholders.fullpath):
placeholders.fullpath = placeholders.fullpath + '_'
placeholders.filename = placeholders.filename + '_'
urlretrieve(placeholders.link, placeholders.fullpath)
else:
value_list = shlex.split(value)
instruction_list = [substitute_placeholders(part, placeholders) for
part in value_list]
returncode = subprocess.call(instruction_list)
if returncode:
raise URLError | python | def download_handler(feed, placeholders):
import shlex
value = feed.retrieve_config('downloadhandler', 'greg')
if value == 'greg':
while os.path.isfile(placeholders.fullpath):
placeholders.fullpath = placeholders.fullpath + '_'
placeholders.filename = placeholders.filename + '_'
urlretrieve(placeholders.link, placeholders.fullpath)
else:
value_list = shlex.split(value)
instruction_list = [substitute_placeholders(part, placeholders) for
part in value_list]
returncode = subprocess.call(instruction_list)
if returncode:
raise URLError | [
"def",
"download_handler",
"(",
"feed",
",",
"placeholders",
")",
":",
"import",
"shlex",
"value",
"=",
"feed",
".",
"retrieve_config",
"(",
"'downloadhandler'",
",",
"'greg'",
")",
"if",
"value",
"==",
"'greg'",
":",
"while",
"os",
".",
"path",
".",
"isfi... | Parse and execute the download handler | [
"Parse",
"and",
"execute",
"the",
"download",
"handler"
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L214-L231 |
4,653 | manolomartinez/greg | greg/aux_functions.py | pretty_print | def pretty_print(session, feed):
"""
Print the dictionary entry of a feed in a nice way.
"""
if feed in session.feeds:
print()
feed_info = os.path.join(session.data_dir, feed)
entrylinks, linkdates = parse_feed_info(feed_info)
print(feed)
print("-"*len(feed))
print(''.join([" url: ", session.feeds[feed]["url"]]))
if linkdates != []:
print(''.join([" Next sync will download from: ", time.strftime(
"%d %b %Y %H:%M:%S", tuple(max(linkdates))), "."]))
else:
print("You don't have a feed called {}.".format(feed), file=sys.stderr,
flush=True) | python | def pretty_print(session, feed):
if feed in session.feeds:
print()
feed_info = os.path.join(session.data_dir, feed)
entrylinks, linkdates = parse_feed_info(feed_info)
print(feed)
print("-"*len(feed))
print(''.join([" url: ", session.feeds[feed]["url"]]))
if linkdates != []:
print(''.join([" Next sync will download from: ", time.strftime(
"%d %b %Y %H:%M:%S", tuple(max(linkdates))), "."]))
else:
print("You don't have a feed called {}.".format(feed), file=sys.stderr,
flush=True) | [
"def",
"pretty_print",
"(",
"session",
",",
"feed",
")",
":",
"if",
"feed",
"in",
"session",
".",
"feeds",
":",
"print",
"(",
")",
"feed_info",
"=",
"os",
".",
"path",
".",
"join",
"(",
"session",
".",
"data_dir",
",",
"feed",
")",
"entrylinks",
",",... | Print the dictionary entry of a feed in a nice way. | [
"Print",
"the",
"dictionary",
"entry",
"of",
"a",
"feed",
"in",
"a",
"nice",
"way",
"."
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L255-L271 |
4,654 | manolomartinez/greg | greg/aux_functions.py | substitute_placeholders | def substitute_placeholders(inputstring, placeholders):
"""
Take a string with placeholders, and return the strings with substitutions.
"""
newst = inputstring.format(link=placeholders.link,
filename=placeholders.filename,
directory=placeholders.directory,
fullpath=placeholders.fullpath,
title=placeholders.title,
filename_title=placeholders.filename_title,
date=placeholders.date_string(),
podcasttitle=placeholders.podcasttitle,
filename_podcasttitle=
placeholders.filename_podcasttitle,
name=placeholders.name,
subtitle=placeholders.sanitizedsubtitle,
entrysummary=placeholders.entrysummary)
return newst | python | def substitute_placeholders(inputstring, placeholders):
newst = inputstring.format(link=placeholders.link,
filename=placeholders.filename,
directory=placeholders.directory,
fullpath=placeholders.fullpath,
title=placeholders.title,
filename_title=placeholders.filename_title,
date=placeholders.date_string(),
podcasttitle=placeholders.podcasttitle,
filename_podcasttitle=
placeholders.filename_podcasttitle,
name=placeholders.name,
subtitle=placeholders.sanitizedsubtitle,
entrysummary=placeholders.entrysummary)
return newst | [
"def",
"substitute_placeholders",
"(",
"inputstring",
",",
"placeholders",
")",
":",
"newst",
"=",
"inputstring",
".",
"format",
"(",
"link",
"=",
"placeholders",
".",
"link",
",",
"filename",
"=",
"placeholders",
".",
"filename",
",",
"directory",
"=",
"place... | Take a string with placeholders, and return the strings with substitutions. | [
"Take",
"a",
"string",
"with",
"placeholders",
"and",
"return",
"the",
"strings",
"with",
"substitutions",
"."
] | 63bb24197c13087a01963ac439cd8380007d9467 | https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L274-L291 |
4,655 | mattjj/pylds | pylds/util.py | symm_block_tridiag_matmul | def symm_block_tridiag_matmul(H_diag, H_upper_diag, v):
"""
Compute matrix-vector product with a symmetric block
tridiagonal matrix H and vector v.
:param H_diag: block diagonal terms of H
:param H_upper_diag: upper block diagonal terms of H
:param v: vector to multiple
:return: H * v
"""
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T-1, D, D)
assert v.shape == (T, D)
out = np.matmul(H_diag, v[:, :, None])[:, :, 0]
out[:-1] += np.matmul(H_upper_diag, v[1:][:, :, None])[:, :, 0]
out[1:] += np.matmul(np.swapaxes(H_upper_diag, -2, -1), v[:-1][:, :, None])[:, :, 0]
return out | python | def symm_block_tridiag_matmul(H_diag, H_upper_diag, v):
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T-1, D, D)
assert v.shape == (T, D)
out = np.matmul(H_diag, v[:, :, None])[:, :, 0]
out[:-1] += np.matmul(H_upper_diag, v[1:][:, :, None])[:, :, 0]
out[1:] += np.matmul(np.swapaxes(H_upper_diag, -2, -1), v[:-1][:, :, None])[:, :, 0]
return out | [
"def",
"symm_block_tridiag_matmul",
"(",
"H_diag",
",",
"H_upper_diag",
",",
"v",
")",
":",
"T",
",",
"D",
",",
"_",
"=",
"H_diag",
".",
"shape",
"assert",
"H_diag",
".",
"ndim",
"==",
"3",
"and",
"H_diag",
".",
"shape",
"[",
"2",
"]",
"==",
"D",
"... | Compute matrix-vector product with a symmetric block
tridiagonal matrix H and vector v.
:param H_diag: block diagonal terms of H
:param H_upper_diag: upper block diagonal terms of H
:param v: vector to multiple
:return: H * v | [
"Compute",
"matrix",
"-",
"vector",
"product",
"with",
"a",
"symmetric",
"block",
"tridiagonal",
"matrix",
"H",
"and",
"vector",
"v",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/util.py#L21-L39 |
4,656 | mattjj/pylds | pylds/util.py | scipy_solve_symm_block_tridiag | def scipy_solve_symm_block_tridiag(H_diag, H_upper_diag, v, ab=None):
"""
use scipy.linalg.solve_banded to solve a symmetric block tridiagonal system
see https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solveh_banded.html
"""
from scipy.linalg import solveh_banded
ab = convert_block_tridiag_to_banded(H_diag, H_upper_diag) \
if ab is None else ab
x = solveh_banded(ab, v.ravel(), lower=True)
return x.reshape(v.shape) | python | def scipy_solve_symm_block_tridiag(H_diag, H_upper_diag, v, ab=None):
from scipy.linalg import solveh_banded
ab = convert_block_tridiag_to_banded(H_diag, H_upper_diag) \
if ab is None else ab
x = solveh_banded(ab, v.ravel(), lower=True)
return x.reshape(v.shape) | [
"def",
"scipy_solve_symm_block_tridiag",
"(",
"H_diag",
",",
"H_upper_diag",
",",
"v",
",",
"ab",
"=",
"None",
")",
":",
"from",
"scipy",
".",
"linalg",
"import",
"solveh_banded",
"ab",
"=",
"convert_block_tridiag_to_banded",
"(",
"H_diag",
",",
"H_upper_diag",
... | use scipy.linalg.solve_banded to solve a symmetric block tridiagonal system
see https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solveh_banded.html | [
"use",
"scipy",
".",
"linalg",
".",
"solve_banded",
"to",
"solve",
"a",
"symmetric",
"block",
"tridiagonal",
"system"
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/util.py#L114-L124 |
4,657 | mattjj/pylds | pylds/util.py | sample_block_tridiag | def sample_block_tridiag(H_diag, H_upper_diag):
"""
helper function for sampling block tridiag gaussians.
this is only for speed comparison with the solve approach.
"""
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T - 1, D, D)
J_init = J_11 = J_22 = np.zeros((D, D))
h_init = h_1 = h_2 = np.zeros((D,))
J_21 = np.swapaxes(H_upper_diag, -1, -2)
J_node = H_diag
h_node = np.zeros((T,D))
y = info_sample(J_init, h_init, 0,
J_11, J_21, J_22, h_1, h_2, np.zeros((T-1)),
J_node, h_node, np.zeros(T))
return y | python | def sample_block_tridiag(H_diag, H_upper_diag):
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T - 1, D, D)
J_init = J_11 = J_22 = np.zeros((D, D))
h_init = h_1 = h_2 = np.zeros((D,))
J_21 = np.swapaxes(H_upper_diag, -1, -2)
J_node = H_diag
h_node = np.zeros((T,D))
y = info_sample(J_init, h_init, 0,
J_11, J_21, J_22, h_1, h_2, np.zeros((T-1)),
J_node, h_node, np.zeros(T))
return y | [
"def",
"sample_block_tridiag",
"(",
"H_diag",
",",
"H_upper_diag",
")",
":",
"T",
",",
"D",
",",
"_",
"=",
"H_diag",
".",
"shape",
"assert",
"H_diag",
".",
"ndim",
"==",
"3",
"and",
"H_diag",
".",
"shape",
"[",
"2",
"]",
"==",
"D",
"assert",
"H_upper... | helper function for sampling block tridiag gaussians.
this is only for speed comparison with the solve approach. | [
"helper",
"function",
"for",
"sampling",
"block",
"tridiag",
"gaussians",
".",
"this",
"is",
"only",
"for",
"speed",
"comparison",
"with",
"the",
"solve",
"approach",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/util.py#L141-L160 |
4,658 | mattjj/pylds | pylds/util.py | compute_symm_block_tridiag_covariances | def compute_symm_block_tridiag_covariances(H_diag, H_upper_diag):
"""
use the info smoother to solve a symmetric block tridiagonal system
"""
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T - 1, D, D)
J_init = J_11 = J_22 = np.zeros((D, D))
h_init = h_1 = h_2 = np.zeros((D,))
J_21 = np.swapaxes(H_upper_diag, -1, -2)
J_node = H_diag
h_node = np.zeros((T, D))
_, _, sigmas, E_xt_xtp1 = \
info_E_step(J_init, h_init, 0,
J_11, J_21, J_22, h_1, h_2, np.zeros((T-1)),
J_node, h_node, np.zeros(T))
return sigmas, E_xt_xtp1 | python | def compute_symm_block_tridiag_covariances(H_diag, H_upper_diag):
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T - 1, D, D)
J_init = J_11 = J_22 = np.zeros((D, D))
h_init = h_1 = h_2 = np.zeros((D,))
J_21 = np.swapaxes(H_upper_diag, -1, -2)
J_node = H_diag
h_node = np.zeros((T, D))
_, _, sigmas, E_xt_xtp1 = \
info_E_step(J_init, h_init, 0,
J_11, J_21, J_22, h_1, h_2, np.zeros((T-1)),
J_node, h_node, np.zeros(T))
return sigmas, E_xt_xtp1 | [
"def",
"compute_symm_block_tridiag_covariances",
"(",
"H_diag",
",",
"H_upper_diag",
")",
":",
"T",
",",
"D",
",",
"_",
"=",
"H_diag",
".",
"shape",
"assert",
"H_diag",
".",
"ndim",
"==",
"3",
"and",
"H_diag",
".",
"shape",
"[",
"2",
"]",
"==",
"D",
"a... | use the info smoother to solve a symmetric block tridiagonal system | [
"use",
"the",
"info",
"smoother",
"to",
"solve",
"a",
"symmetric",
"block",
"tridiagonal",
"system"
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/util.py#L199-L218 |
4,659 | mattjj/pylds | pylds/states.py | LDSStatesZeroInflatedCountData.resample_zeroinflation_variables | def resample_zeroinflation_variables(self):
"""
There's no way around the fact that we have to look at every
data point, even the zeros here.
"""
# TODO: move this to cython?
T, N, C, D, b = self.T, self.D_emission, self.C, self.D, self.emission_distn.b
indptr = [0]
indices = []
vals = []
offset = 0
X = np.hstack((self.gaussian_states, self.inputs))
for t in range(T):
# Evaluate probability of data
y_t = np.zeros(N)
ns_t = self.data.indices[self.data.indptr[t]:self.data.indptr[t+1]]
y_t[ns_t] = self.data.data[self.data.indptr[t]:self.data.indptr[t+1]]
ll = self.emission_distn._elementwise_log_likelihood((X[t], y_t))
ll = ll.ravel()
# Evaluate the probability that each emission was "exposed",
# i.e. p(z_tn = 1 | y_tn, x_tn)
log_p_exposed = np.log(self.rho) + ll
log_p_exposed -= np.log(np.exp(log_p_exposed) + (1-self.rho) * (y_t == 0))
# Sample zero inflation mask
z_t = np.random.rand(N) < np.exp(log_p_exposed)
# Construct the sparse matrix
t_inds = np.where(z_t)[0]
indices.append(t_inds)
vals.append(y_t[t_inds])
offset += t_inds.size
indptr.append(offset)
# Construct a sparse matrix
vals = np.concatenate(vals)
indices = np.concatenate(indices)
indptr = np.array(indptr)
self.masked_data = csr_matrix((vals, indices, indptr), shape=(T, N)) | python | def resample_zeroinflation_variables(self):
# TODO: move this to cython?
T, N, C, D, b = self.T, self.D_emission, self.C, self.D, self.emission_distn.b
indptr = [0]
indices = []
vals = []
offset = 0
X = np.hstack((self.gaussian_states, self.inputs))
for t in range(T):
# Evaluate probability of data
y_t = np.zeros(N)
ns_t = self.data.indices[self.data.indptr[t]:self.data.indptr[t+1]]
y_t[ns_t] = self.data.data[self.data.indptr[t]:self.data.indptr[t+1]]
ll = self.emission_distn._elementwise_log_likelihood((X[t], y_t))
ll = ll.ravel()
# Evaluate the probability that each emission was "exposed",
# i.e. p(z_tn = 1 | y_tn, x_tn)
log_p_exposed = np.log(self.rho) + ll
log_p_exposed -= np.log(np.exp(log_p_exposed) + (1-self.rho) * (y_t == 0))
# Sample zero inflation mask
z_t = np.random.rand(N) < np.exp(log_p_exposed)
# Construct the sparse matrix
t_inds = np.where(z_t)[0]
indices.append(t_inds)
vals.append(y_t[t_inds])
offset += t_inds.size
indptr.append(offset)
# Construct a sparse matrix
vals = np.concatenate(vals)
indices = np.concatenate(indices)
indptr = np.array(indptr)
self.masked_data = csr_matrix((vals, indices, indptr), shape=(T, N)) | [
"def",
"resample_zeroinflation_variables",
"(",
"self",
")",
":",
"# TODO: move this to cython?",
"T",
",",
"N",
",",
"C",
",",
"D",
",",
"b",
"=",
"self",
".",
"T",
",",
"self",
".",
"D_emission",
",",
"self",
".",
"C",
",",
"self",
".",
"D",
",",
"... | There's no way around the fact that we have to look at every
data point, even the zeros here. | [
"There",
"s",
"no",
"way",
"around",
"the",
"fact",
"that",
"we",
"have",
"to",
"look",
"at",
"every",
"data",
"point",
"even",
"the",
"zeros",
"here",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/states.py#L905-L944 |
4,660 | mattjj/pylds | pylds/distributions.py | PoissonRegression.expected_log_likelihood | def expected_log_likelihood(self, mus, sigmas, y):
"""
Compute the expected log likelihood for a mean and
covariance of x and an observed value of y.
"""
# Flatten the covariance
T = mus.shape[0]
D = self.D_in
sigs_vec = sigmas.reshape((T, D ** 2))
# Compute the log likelihood of each column
ll = np.zeros((T, self.D_out))
for n in range(self.D_out):
an = self.A[n]
E_loglmbda = np.dot(mus, an)
ll[:,n] += y[:,n] * E_loglmbda
# Vectorized log likelihood calculation
aa_vec = np.outer(an, an).reshape((D ** 2,))
ll[:,n] = -np.exp(E_loglmbda + 0.5 * np.dot(sigs_vec, aa_vec))
return ll | python | def expected_log_likelihood(self, mus, sigmas, y):
# Flatten the covariance
T = mus.shape[0]
D = self.D_in
sigs_vec = sigmas.reshape((T, D ** 2))
# Compute the log likelihood of each column
ll = np.zeros((T, self.D_out))
for n in range(self.D_out):
an = self.A[n]
E_loglmbda = np.dot(mus, an)
ll[:,n] += y[:,n] * E_loglmbda
# Vectorized log likelihood calculation
aa_vec = np.outer(an, an).reshape((D ** 2,))
ll[:,n] = -np.exp(E_loglmbda + 0.5 * np.dot(sigs_vec, aa_vec))
return ll | [
"def",
"expected_log_likelihood",
"(",
"self",
",",
"mus",
",",
"sigmas",
",",
"y",
")",
":",
"# Flatten the covariance",
"T",
"=",
"mus",
".",
"shape",
"[",
"0",
"]",
"D",
"=",
"self",
".",
"D_in",
"sigs_vec",
"=",
"sigmas",
".",
"reshape",
"(",
"(",
... | Compute the expected log likelihood for a mean and
covariance of x and an observed value of y. | [
"Compute",
"the",
"expected",
"log",
"likelihood",
"for",
"a",
"mean",
"and",
"covariance",
"of",
"x",
"and",
"an",
"observed",
"value",
"of",
"y",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/distributions.py#L55-L79 |
4,661 | mattjj/pylds | pylds/laplace.py | _LaplaceApproxLDSStatesBase.sparse_hessian_log_joint | def sparse_hessian_log_joint(self, x):
"""
The Hessian includes the quadratic terms of the Gaussian LDS prior
as well as the Hessian of the local log likelihood.
"""
T, D = self.T, self.D_latent
assert x.shape == (T, D)
# Collect the Gaussian LDS prior terms
J_diag, J_upper_diag = self.sparse_J_prior
H_diag, H_upper_diag = -J_diag, -J_upper_diag
# Collect the likelihood terms
H_diag += self.hessian_local_log_likelihood(x)
# Subtract a little bit to ensure negative definiteness
H_diag -= 1e-8 * np.eye(D)
return H_diag, H_upper_diag | python | def sparse_hessian_log_joint(self, x):
T, D = self.T, self.D_latent
assert x.shape == (T, D)
# Collect the Gaussian LDS prior terms
J_diag, J_upper_diag = self.sparse_J_prior
H_diag, H_upper_diag = -J_diag, -J_upper_diag
# Collect the likelihood terms
H_diag += self.hessian_local_log_likelihood(x)
# Subtract a little bit to ensure negative definiteness
H_diag -= 1e-8 * np.eye(D)
return H_diag, H_upper_diag | [
"def",
"sparse_hessian_log_joint",
"(",
"self",
",",
"x",
")",
":",
"T",
",",
"D",
"=",
"self",
".",
"T",
",",
"self",
".",
"D_latent",
"assert",
"x",
".",
"shape",
"==",
"(",
"T",
",",
"D",
")",
"# Collect the Gaussian LDS prior terms",
"J_diag",
",",
... | The Hessian includes the quadratic terms of the Gaussian LDS prior
as well as the Hessian of the local log likelihood. | [
"The",
"Hessian",
"includes",
"the",
"quadratic",
"terms",
"of",
"the",
"Gaussian",
"LDS",
"prior",
"as",
"well",
"as",
"the",
"Hessian",
"of",
"the",
"local",
"log",
"likelihood",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/laplace.py#L109-L127 |
4,662 | mattjj/pylds | pylds/laplace.py | _LaplaceApproxLDSStatesBase.gradient_log_joint | def gradient_log_joint(self, x):
"""
The gradient of the log joint probability.
For the Gaussian terms, this is
d/dx [-1/2 x^T J x + h^T x] = -Jx + h.
For the likelihood terms, we have for each time t
d/dx log p(yt | xt)
"""
T, D = self.T, self.D_latent
assert x.shape == (T, D)
# Collect the Gaussian LDS prior terms
_, h_init, _ = self.info_init_params
_, _, _, h1, h2, _ = self.info_dynamics_params
H_diag, H_upper_diag = self.sparse_J_prior
# Compute the gradient from the prior
g = -1 * symm_block_tridiag_matmul(H_diag, H_upper_diag, x)
g[0] += h_init
g[:-1] += h1
g[1:] += h2
# Compute gradient from the likelihood terms
g += self.grad_local_log_likelihood(x)
return g | python | def gradient_log_joint(self, x):
T, D = self.T, self.D_latent
assert x.shape == (T, D)
# Collect the Gaussian LDS prior terms
_, h_init, _ = self.info_init_params
_, _, _, h1, h2, _ = self.info_dynamics_params
H_diag, H_upper_diag = self.sparse_J_prior
# Compute the gradient from the prior
g = -1 * symm_block_tridiag_matmul(H_diag, H_upper_diag, x)
g[0] += h_init
g[:-1] += h1
g[1:] += h2
# Compute gradient from the likelihood terms
g += self.grad_local_log_likelihood(x)
return g | [
"def",
"gradient_log_joint",
"(",
"self",
",",
"x",
")",
":",
"T",
",",
"D",
"=",
"self",
".",
"T",
",",
"self",
".",
"D_latent",
"assert",
"x",
".",
"shape",
"==",
"(",
"T",
",",
"D",
")",
"# Collect the Gaussian LDS prior terms",
"_",
",",
"h_init",
... | The gradient of the log joint probability.
For the Gaussian terms, this is
d/dx [-1/2 x^T J x + h^T x] = -Jx + h.
For the likelihood terms, we have for each time t
d/dx log p(yt | xt) | [
"The",
"gradient",
"of",
"the",
"log",
"joint",
"probability",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/laplace.py#L133-L162 |
4,663 | mattjj/pylds | pylds/laplace.py | _LaplaceApproxLDSStatesBase._laplace_approximation_newton | def _laplace_approximation_newton(self, tol=1e-6, stepsz=0.9, verbose=False):
"""
Solve a block tridiagonal system with message passing.
"""
from pylds.util import solve_symm_block_tridiag, scipy_solve_symm_block_tridiag
scale = self.T * self.D_emission
def newton_step(x, stepsz):
assert 0 <= stepsz <= 1
g = self.gradient_log_joint(x)
H_diag, H_upper_diag = self.sparse_hessian_log_joint(x)
Hinv_g = -scipy_solve_symm_block_tridiag(-H_diag / scale,
-H_upper_diag / scale,
g / scale)
return x - stepsz * Hinv_g
if verbose:
print("Fitting Laplace approximation")
itr = [0]
def cbk(x):
print("Iteration: ", itr[0],
"\tObjective: ", (self.log_joint(x) / scale).round(4),
"\tAvg Grad: ", (self.gradient_log_joint(x).mean() / scale).round(4))
itr[0] += 1
# Solve for optimal x with Newton's method
x = self.gaussian_states
dx = np.inf
while dx >= tol:
xnew = newton_step(x, stepsz)
dx = np.mean(abs(xnew - x))
x = xnew
if verbose:
cbk(x)
assert np.all(np.isfinite(x))
if verbose:
print("Done")
return x | python | def _laplace_approximation_newton(self, tol=1e-6, stepsz=0.9, verbose=False):
from pylds.util import solve_symm_block_tridiag, scipy_solve_symm_block_tridiag
scale = self.T * self.D_emission
def newton_step(x, stepsz):
assert 0 <= stepsz <= 1
g = self.gradient_log_joint(x)
H_diag, H_upper_diag = self.sparse_hessian_log_joint(x)
Hinv_g = -scipy_solve_symm_block_tridiag(-H_diag / scale,
-H_upper_diag / scale,
g / scale)
return x - stepsz * Hinv_g
if verbose:
print("Fitting Laplace approximation")
itr = [0]
def cbk(x):
print("Iteration: ", itr[0],
"\tObjective: ", (self.log_joint(x) / scale).round(4),
"\tAvg Grad: ", (self.gradient_log_joint(x).mean() / scale).round(4))
itr[0] += 1
# Solve for optimal x with Newton's method
x = self.gaussian_states
dx = np.inf
while dx >= tol:
xnew = newton_step(x, stepsz)
dx = np.mean(abs(xnew - x))
x = xnew
if verbose:
cbk(x)
assert np.all(np.isfinite(x))
if verbose:
print("Done")
return x | [
"def",
"_laplace_approximation_newton",
"(",
"self",
",",
"tol",
"=",
"1e-6",
",",
"stepsz",
"=",
"0.9",
",",
"verbose",
"=",
"False",
")",
":",
"from",
"pylds",
".",
"util",
"import",
"solve_symm_block_tridiag",
",",
"scipy_solve_symm_block_tridiag",
"scale",
"... | Solve a block tridiagonal system with message passing. | [
"Solve",
"a",
"block",
"tridiagonal",
"system",
"with",
"message",
"passing",
"."
] | e946bfa5aa76e8f8284614561a0f40ffd5d868fb | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/laplace.py#L212-L253 |
4,664 | FirefighterBlu3/python-pam | pam.py | pam.authenticate | def authenticate(self, username, password, service='login', encoding='utf-8', resetcreds=True):
"""username and password authentication for the given service.
Returns True for success, or False for failure.
self.code (integer) and self.reason (string) are always stored and may
be referenced for the reason why authentication failed. 0/'Success' will
be stored for success.
Python3 expects bytes() for ctypes inputs. This function will make
necessary conversions using the supplied encoding.
Inputs:
username: username to authenticate
password: password in plain text
service: PAM service to authenticate against, defaults to 'login'
Returns:
success: True
failure: False
"""
@conv_func
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = calloc(n_messages, sizeof(PamResponse))
response = cast(addr, POINTER(PamResponse))
p_response[0] = response
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
dst = calloc(len(password)+1, sizeof(c_char))
memmove(dst, cpassword, len(password))
response[i].resp = dst
response[i].resp_retcode = 0
return 0
# python3 ctypes prefers bytes
if sys.version_info >= (3,):
if isinstance(username, str): username = username.encode(encoding)
if isinstance(password, str): password = password.encode(encoding)
if isinstance(service, str): service = service.encode(encoding)
else:
if isinstance(username, unicode):
username = username.encode(encoding)
if isinstance(password, unicode):
password = password.encode(encoding)
if isinstance(service, unicode):
service = service.encode(encoding)
if b'\x00' in username or b'\x00' in password or b'\x00' in service:
self.code = 4 # PAM_SYSTEM_ERR in Linux-PAM
self.reason = 'strings may not contain NUL'
return False
# do this up front so we can safely throw an exception if there's
# anything wrong with it
cpassword = c_char_p(password)
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = pam_start(service, username, byref(conv), byref(handle))
if retval != 0:
# This is not an authentication error, something has gone wrong starting up PAM
self.code = retval
self.reason = "pam_start() failed"
return False
retval = pam_authenticate(handle, 0)
auth_success = retval == 0
if auth_success and resetcreds:
retval = pam_setcred(handle, PAM_REINITIALIZE_CRED);
# store information to inform the caller why we failed
self.code = retval
self.reason = pam_strerror(handle, retval)
if sys.version_info >= (3,):
self.reason = self.reason.decode(encoding)
if hasattr(libpam, 'pam_end'):
pam_end(handle, retval)
return auth_success | python | def authenticate(self, username, password, service='login', encoding='utf-8', resetcreds=True):
@conv_func
def my_conv(n_messages, messages, p_response, app_data):
"""Simple conversation function that responds to any
prompt where the echo is off with the supplied password"""
# Create an array of n_messages response objects
addr = calloc(n_messages, sizeof(PamResponse))
response = cast(addr, POINTER(PamResponse))
p_response[0] = response
for i in range(n_messages):
if messages[i].contents.msg_style == PAM_PROMPT_ECHO_OFF:
dst = calloc(len(password)+1, sizeof(c_char))
memmove(dst, cpassword, len(password))
response[i].resp = dst
response[i].resp_retcode = 0
return 0
# python3 ctypes prefers bytes
if sys.version_info >= (3,):
if isinstance(username, str): username = username.encode(encoding)
if isinstance(password, str): password = password.encode(encoding)
if isinstance(service, str): service = service.encode(encoding)
else:
if isinstance(username, unicode):
username = username.encode(encoding)
if isinstance(password, unicode):
password = password.encode(encoding)
if isinstance(service, unicode):
service = service.encode(encoding)
if b'\x00' in username or b'\x00' in password or b'\x00' in service:
self.code = 4 # PAM_SYSTEM_ERR in Linux-PAM
self.reason = 'strings may not contain NUL'
return False
# do this up front so we can safely throw an exception if there's
# anything wrong with it
cpassword = c_char_p(password)
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = pam_start(service, username, byref(conv), byref(handle))
if retval != 0:
# This is not an authentication error, something has gone wrong starting up PAM
self.code = retval
self.reason = "pam_start() failed"
return False
retval = pam_authenticate(handle, 0)
auth_success = retval == 0
if auth_success and resetcreds:
retval = pam_setcred(handle, PAM_REINITIALIZE_CRED);
# store information to inform the caller why we failed
self.code = retval
self.reason = pam_strerror(handle, retval)
if sys.version_info >= (3,):
self.reason = self.reason.decode(encoding)
if hasattr(libpam, 'pam_end'):
pam_end(handle, retval)
return auth_success | [
"def",
"authenticate",
"(",
"self",
",",
"username",
",",
"password",
",",
"service",
"=",
"'login'",
",",
"encoding",
"=",
"'utf-8'",
",",
"resetcreds",
"=",
"True",
")",
":",
"@",
"conv_func",
"def",
"my_conv",
"(",
"n_messages",
",",
"messages",
",",
... | username and password authentication for the given service.
Returns True for success, or False for failure.
self.code (integer) and self.reason (string) are always stored and may
be referenced for the reason why authentication failed. 0/'Success' will
be stored for success.
Python3 expects bytes() for ctypes inputs. This function will make
necessary conversions using the supplied encoding.
Inputs:
username: username to authenticate
password: password in plain text
service: PAM service to authenticate against, defaults to 'login'
Returns:
success: True
failure: False | [
"username",
"and",
"password",
"authentication",
"for",
"the",
"given",
"service",
"."
] | fe44b334970f421635d9e373b563c9e6566613bd | https://github.com/FirefighterBlu3/python-pam/blob/fe44b334970f421635d9e373b563c9e6566613bd/pam.py#L106-L191 |
4,665 | cloudmesh/cloudmesh-common | cloudmesh/common/ssh/ssh_config.py | ssh_config.load | def load(self):
"""list the hosts defined in the ssh config file"""
with open(self.filename) as f:
content = f.readlines()
content = [" ".join(x.split()).strip('\n').lstrip().split(' ', 1) for x in content]
# removes duplicated spaces, and splits in two fields, removes leading spaces
hosts = {}
host = "NA"
for line in content:
if line[0].startswith('#') or line[0] is '':
pass # ignore line
else:
attribute = line[0]
value = line[1]
if attribute.lower().strip() in ['Host', 'host']:
host = value
hosts[host] = {'host': host}
else:
# In case of special configuration lines, such as port
# forwarding,
# there would be no 'Host india' line.
if host in hosts:
hosts[host][attribute] = value
# pass
self.hosts = hosts | python | def load(self):
with open(self.filename) as f:
content = f.readlines()
content = [" ".join(x.split()).strip('\n').lstrip().split(' ', 1) for x in content]
# removes duplicated spaces, and splits in two fields, removes leading spaces
hosts = {}
host = "NA"
for line in content:
if line[0].startswith('#') or line[0] is '':
pass # ignore line
else:
attribute = line[0]
value = line[1]
if attribute.lower().strip() in ['Host', 'host']:
host = value
hosts[host] = {'host': host}
else:
# In case of special configuration lines, such as port
# forwarding,
# there would be no 'Host india' line.
if host in hosts:
hosts[host][attribute] = value
# pass
self.hosts = hosts | [
"def",
"load",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"readlines",
"(",
")",
"content",
"=",
"[",
"\" \"",
".",
"join",
"(",
"x",
".",
"split",
"(",
")",
")",
".",
"... | list the hosts defined in the ssh config file | [
"list",
"the",
"hosts",
"defined",
"in",
"the",
"ssh",
"config",
"file"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/ssh/ssh_config.py#L48-L73 |
4,666 | cloudmesh/cloudmesh-common | cloudmesh/common/logger.py | LOGGER | def LOGGER(filename):
"""creates a logger with the given name.
You can use it as follows::
log = cloudmesh.common.LOGGER(__file__)
log.error("this is an error")
log.info("this is an info")
log.warning("this is a warning")
"""
pwd = os.getcwd()
name = filename.replace(pwd, "$PWD")
try:
(first, name) = name.split("site-packages")
name += "... site"
except:
pass
loglevel = logging.CRITICAL
try:
level = grep("loglevel:", config_file(
"/cloudmesh_debug.yaml")).strip().split(":")[1].strip().lower()
if level.upper() == "DEBUG":
loglevel = logging.DEBUG
elif level.upper() == "INFO":
loglevel = logging.INFO
elif level.upper() == "WARNING":
loglevel = logging.WARNING
elif level.upper() == "ERROR":
loglevel = logging.ERROR
else:
level = logging.CRITICAL
except:
# print "LOGLEVEL NOT FOUND"
loglevel = logging.DEBUG
log = logging.getLogger(name)
log.setLevel(loglevel)
formatter = logging.Formatter(
'CM {0:>50}:%(lineno)s: %(levelname)6s - %(message)s'.format(name))
# formatter = logging.Formatter(
# 'CM {0:>50}: %(levelname)6s - %(module)s:%(lineno)s %funcName)s: %(message)s'.format(name))
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
return log | python | def LOGGER(filename):
pwd = os.getcwd()
name = filename.replace(pwd, "$PWD")
try:
(first, name) = name.split("site-packages")
name += "... site"
except:
pass
loglevel = logging.CRITICAL
try:
level = grep("loglevel:", config_file(
"/cloudmesh_debug.yaml")).strip().split(":")[1].strip().lower()
if level.upper() == "DEBUG":
loglevel = logging.DEBUG
elif level.upper() == "INFO":
loglevel = logging.INFO
elif level.upper() == "WARNING":
loglevel = logging.WARNING
elif level.upper() == "ERROR":
loglevel = logging.ERROR
else:
level = logging.CRITICAL
except:
# print "LOGLEVEL NOT FOUND"
loglevel = logging.DEBUG
log = logging.getLogger(name)
log.setLevel(loglevel)
formatter = logging.Formatter(
'CM {0:>50}:%(lineno)s: %(levelname)6s - %(message)s'.format(name))
# formatter = logging.Formatter(
# 'CM {0:>50}: %(levelname)6s - %(module)s:%(lineno)s %funcName)s: %(message)s'.format(name))
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
return log | [
"def",
"LOGGER",
"(",
"filename",
")",
":",
"pwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"name",
"=",
"filename",
".",
"replace",
"(",
"pwd",
",",
"\"$PWD\"",
")",
"try",
":",
"(",
"first",
",",
"name",
")",
"=",
"name",
".",
"split",
"(",
"\"site-... | creates a logger with the given name.
You can use it as follows::
log = cloudmesh.common.LOGGER(__file__)
log.error("this is an error")
log.info("this is an info")
log.warning("this is a warning") | [
"creates",
"a",
"logger",
"with",
"the",
"given",
"name",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/logger.py#L12-L61 |
4,667 | cloudmesh/cloudmesh-common | cloudmesh/common/FlatDict.py | key_prefix_replace | def key_prefix_replace(d, prefix, new_prefix=""):
"""
replaces the list of prefix in keys of a flattened dict
:param d: the flattened dict
:param prefix: a list of prefixes that are replaced with a new prefix.
Typically this will be ""
:type prefix: list of str
:param new_prefix: The new prefix. By default it is set to ""
:return: the dict with the keys replaced as specified
"""
items = []
for k, v in d.items():
new_key = k
for p in prefix:
new_key = new_key.replace(p, new_prefix, 1)
items.append((new_key, v))
return dict(items) | python | def key_prefix_replace(d, prefix, new_prefix=""):
items = []
for k, v in d.items():
new_key = k
for p in prefix:
new_key = new_key.replace(p, new_prefix, 1)
items.append((new_key, v))
return dict(items) | [
"def",
"key_prefix_replace",
"(",
"d",
",",
"prefix",
",",
"new_prefix",
"=",
"\"\"",
")",
":",
"items",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"new_key",
"=",
"k",
"for",
"p",
"in",
"prefix",
":",
"new_key",... | replaces the list of prefix in keys of a flattened dict
:param d: the flattened dict
:param prefix: a list of prefixes that are replaced with a new prefix.
Typically this will be ""
:type prefix: list of str
:param new_prefix: The new prefix. By default it is set to ""
:return: the dict with the keys replaced as specified | [
"replaces",
"the",
"list",
"of",
"prefix",
"in",
"keys",
"of",
"a",
"flattened",
"dict"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/FlatDict.py#L14-L31 |
4,668 | cloudmesh/cloudmesh-common | cloudmesh/common/FlatDict.py | flatten | def flatten(d, parent_key='', sep='__'):
"""
flattens the dict into a one dimensional dictionary
:param d: multidimensional dict
:param parent_key: replaces from the parent key
:param sep: the separation character used when fattening. the default is __
:return: the flattened dict
"""
# http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys
if type(d) == list:
flat = []
for entry in d:
flat.append(flatten(entry, parent_key=parent_key, sep=sep))
return flat
else:
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collectionsAbc.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items) | python | def flatten(d, parent_key='', sep='__'):
# http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys
if type(d) == list:
flat = []
for entry in d:
flat.append(flatten(entry, parent_key=parent_key, sep=sep))
return flat
else:
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collectionsAbc.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items) | [
"def",
"flatten",
"(",
"d",
",",
"parent_key",
"=",
"''",
",",
"sep",
"=",
"'__'",
")",
":",
"# http://stackoverflow.com/questions/6027558/flatten-nested-python-dictionaries-compressing-keys",
"if",
"type",
"(",
"d",
")",
"==",
"list",
":",
"flat",
"=",
"[",
"]",
... | flattens the dict into a one dimensional dictionary
:param d: multidimensional dict
:param parent_key: replaces from the parent key
:param sep: the separation character used when fattening. the default is __
:return: the flattened dict | [
"flattens",
"the",
"dict",
"into",
"a",
"one",
"dimensional",
"dictionary"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/FlatDict.py#L41-L67 |
4,669 | cloudmesh/cloudmesh-common | cloudmesh/common/FlatDict.py | FlatDict2.object_to_dict | def object_to_dict(cls, obj):
"""
This function converts Objects into Dictionary
"""
dict_obj = dict()
if obj is not None:
if type(obj) == list:
dict_list = []
for inst in obj:
dict_list.append(cls.object_to_dict(inst))
dict_obj["list"] = dict_list
elif not cls.is_primitive(obj):
for key in obj.__dict__:
# is an object
if type(obj.__dict__[key]) == list:
dict_list = []
for inst in obj.__dict__[key]:
dict_list.append(cls.object_to_dict(inst))
dict_obj[key] = dict_list
elif not cls.is_primitive(obj.__dict__[key]):
temp_dict = cls.object_to_dict(obj.__dict__[key])
dict_obj[key] = temp_dict
else:
dict_obj[key] = obj.__dict__[key]
elif cls.is_primitive(obj):
return obj
return dict_obj | python | def object_to_dict(cls, obj):
dict_obj = dict()
if obj is not None:
if type(obj) == list:
dict_list = []
for inst in obj:
dict_list.append(cls.object_to_dict(inst))
dict_obj["list"] = dict_list
elif not cls.is_primitive(obj):
for key in obj.__dict__:
# is an object
if type(obj.__dict__[key]) == list:
dict_list = []
for inst in obj.__dict__[key]:
dict_list.append(cls.object_to_dict(inst))
dict_obj[key] = dict_list
elif not cls.is_primitive(obj.__dict__[key]):
temp_dict = cls.object_to_dict(obj.__dict__[key])
dict_obj[key] = temp_dict
else:
dict_obj[key] = obj.__dict__[key]
elif cls.is_primitive(obj):
return obj
return dict_obj | [
"def",
"object_to_dict",
"(",
"cls",
",",
"obj",
")",
":",
"dict_obj",
"=",
"dict",
"(",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"if",
"type",
"(",
"obj",
")",
"==",
"list",
":",
"dict_list",
"=",
"[",
"]",
"for",
"inst",
"in",
"obj",
":",
... | This function converts Objects into Dictionary | [
"This",
"function",
"converts",
"Objects",
"into",
"Dictionary"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/FlatDict.py#L156-L183 |
4,670 | cloudmesh/cloudmesh-common | cloudmesh/common/StopWatch.py | StopWatch.start | def start(cls, name):
"""
starts a timer with the given name.
:param name: the name of the timer
:type name: string
"""
if cls.debug:
print("Timer", name, "started ...")
cls.timer_start[name] = time.time() | python | def start(cls, name):
if cls.debug:
print("Timer", name, "started ...")
cls.timer_start[name] = time.time() | [
"def",
"start",
"(",
"cls",
",",
"name",
")",
":",
"if",
"cls",
".",
"debug",
":",
"print",
"(",
"\"Timer\"",
",",
"name",
",",
"\"started ...\"",
")",
"cls",
".",
"timer_start",
"[",
"name",
"]",
"=",
"time",
".",
"time",
"(",
")"
] | starts a timer with the given name.
:param name: the name of the timer
:type name: string | [
"starts",
"a",
"timer",
"with",
"the",
"given",
"name",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/StopWatch.py#L33-L42 |
4,671 | cloudmesh/cloudmesh-common | cloudmesh/common/StopWatch.py | StopWatch.stop | def stop(cls, name):
"""
stops the timer with a given name.
:param name: the name of the timer
:type name: string
"""
cls.timer_end[name] = time.time()
if cls.debug:
print("Timer", name, "stopped ...") | python | def stop(cls, name):
cls.timer_end[name] = time.time()
if cls.debug:
print("Timer", name, "stopped ...") | [
"def",
"stop",
"(",
"cls",
",",
"name",
")",
":",
"cls",
".",
"timer_end",
"[",
"name",
"]",
"=",
"time",
".",
"time",
"(",
")",
"if",
"cls",
".",
"debug",
":",
"print",
"(",
"\"Timer\"",
",",
"name",
",",
"\"stopped ...\"",
")"
] | stops the timer with a given name.
:param name: the name of the timer
:type name: string | [
"stops",
"the",
"timer",
"with",
"a",
"given",
"name",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/StopWatch.py#L45-L54 |
4,672 | cloudmesh/cloudmesh-common | cloudmesh/common/StopWatch.py | StopWatch.get | def get(cls, name):
"""
returns the time of the timer.
:param name: the name of the timer
:type name: string
:rtype: the elapsed time
"""
if name in cls.timer_end:
cls.timer_elapsed[name] = cls.timer_end[name] - \
cls.timer_start[name]
return cls.timer_elapsed[name]
else:
return "undefined" | python | def get(cls, name):
if name in cls.timer_end:
cls.timer_elapsed[name] = cls.timer_end[name] - \
cls.timer_start[name]
return cls.timer_elapsed[name]
else:
return "undefined" | [
"def",
"get",
"(",
"cls",
",",
"name",
")",
":",
"if",
"name",
"in",
"cls",
".",
"timer_end",
":",
"cls",
".",
"timer_elapsed",
"[",
"name",
"]",
"=",
"cls",
".",
"timer_end",
"[",
"name",
"]",
"-",
"cls",
".",
"timer_start",
"[",
"name",
"]",
"r... | returns the time of the timer.
:param name: the name of the timer
:type name: string
:rtype: the elapsed time | [
"returns",
"the",
"time",
"of",
"the",
"timer",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/StopWatch.py#L57-L70 |
4,673 | cloudmesh/cloudmesh-common | cloudmesh/common/Shell.py | Shell.find_cygwin_executables | def find_cygwin_executables(cls):
"""
find the executables in cygwin
"""
exe_paths = glob.glob(cls.cygwin_path + r'\*.exe')
# print cls.cygwin_path
# list all *.exe in cygwin path, use glob
for c in exe_paths:
exe = c.split('\\')
name = exe[1].split('.')[0]
# command['windows'][name] = "{:}\{:}.exe".format(cygwin_path, c)
cls.command['windows'][name] = c | python | def find_cygwin_executables(cls):
exe_paths = glob.glob(cls.cygwin_path + r'\*.exe')
# print cls.cygwin_path
# list all *.exe in cygwin path, use glob
for c in exe_paths:
exe = c.split('\\')
name = exe[1].split('.')[0]
# command['windows'][name] = "{:}\{:}.exe".format(cygwin_path, c)
cls.command['windows'][name] = c | [
"def",
"find_cygwin_executables",
"(",
"cls",
")",
":",
"exe_paths",
"=",
"glob",
".",
"glob",
"(",
"cls",
".",
"cygwin_path",
"+",
"r'\\*.exe'",
")",
"# print cls.cygwin_path",
"# list all *.exe in cygwin path, use glob",
"for",
"c",
"in",
"exe_paths",
":",
"exe",... | find the executables in cygwin | [
"find",
"the",
"executables",
"in",
"cygwin"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/Shell.py#L622-L633 |
4,674 | cloudmesh/cloudmesh-common | cloudmesh/common/Shell.py | Shell.terminal_type | def terminal_type(cls):
"""
returns darwin, cygwin, cmd, or linux
"""
what = sys.platform
kind = 'UNDEFINED_TERMINAL_TYPE'
if 'linux' in what:
kind = 'linux'
elif 'darwin' in what:
kind = 'darwin'
elif 'cygwin' in what:
kind = 'cygwin'
elif 'windows' in what:
kind = 'windows'
return kind | python | def terminal_type(cls):
what = sys.platform
kind = 'UNDEFINED_TERMINAL_TYPE'
if 'linux' in what:
kind = 'linux'
elif 'darwin' in what:
kind = 'darwin'
elif 'cygwin' in what:
kind = 'cygwin'
elif 'windows' in what:
kind = 'windows'
return kind | [
"def",
"terminal_type",
"(",
"cls",
")",
":",
"what",
"=",
"sys",
".",
"platform",
"kind",
"=",
"'UNDEFINED_TERMINAL_TYPE'",
"if",
"'linux'",
"in",
"what",
":",
"kind",
"=",
"'linux'",
"elif",
"'darwin'",
"in",
"what",
":",
"kind",
"=",
"'darwin'",
"elif",... | returns darwin, cygwin, cmd, or linux | [
"returns",
"darwin",
"cygwin",
"cmd",
"or",
"linux"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/Shell.py#L636-L652 |
4,675 | cloudmesh/cloudmesh-common | cloudmesh/common/Shell.py | Shell.execute | def execute(cls,
cmd,
arguments="",
shell=False,
cwd=None,
traceflag=True,
witherror=True):
"""Run Shell command
:param witherror: if set to False the error will not be printed
:param traceflag: if set to true the trace is printed in case of an error
:param cwd: the current working directory in whcih the command is supposed to be executed.
:param shell: if set to true the subprocess is called as part of a shell
:param cmd: command to run
:param arguments: we do not know yet
:return:
"""
# print "--------------"
result = None
terminal = cls.terminal_type()
# print cls.command
os_command = [cmd]
if terminal in ['linux', 'windows']:
os_command = [cmd]
elif 'cygwin' in terminal:
if not cls.command_exists(cmd):
print("ERROR: the command could not be found", cmd)
return
else:
os_command = [cls.command[cls.operating_system()][cmd]]
if isinstance(arguments, list):
os_command = os_command + arguments
elif isinstance(arguments, tuple):
os_command = os_command + list(arguments)
elif isinstance(arguments, str):
os_command = os_command + arguments.split()
else:
print("ERROR: Wrong parameter type", type(arguments))
if cwd is None:
cwd = os.getcwd()
try:
if shell:
result = subprocess.check_output(
os_command,
stderr=subprocess.STDOUT,
shell=True,
cwd=cwd)
else:
result = subprocess.check_output(
os_command,
# shell=True,
stderr=subprocess.STDOUT,
cwd=cwd)
except:
if witherror:
Console.error("problem executing subprocess",
traceflag=traceflag)
if result is not None:
result = result.strip().decode()
return result | python | def execute(cls,
cmd,
arguments="",
shell=False,
cwd=None,
traceflag=True,
witherror=True):
# print "--------------"
result = None
terminal = cls.terminal_type()
# print cls.command
os_command = [cmd]
if terminal in ['linux', 'windows']:
os_command = [cmd]
elif 'cygwin' in terminal:
if not cls.command_exists(cmd):
print("ERROR: the command could not be found", cmd)
return
else:
os_command = [cls.command[cls.operating_system()][cmd]]
if isinstance(arguments, list):
os_command = os_command + arguments
elif isinstance(arguments, tuple):
os_command = os_command + list(arguments)
elif isinstance(arguments, str):
os_command = os_command + arguments.split()
else:
print("ERROR: Wrong parameter type", type(arguments))
if cwd is None:
cwd = os.getcwd()
try:
if shell:
result = subprocess.check_output(
os_command,
stderr=subprocess.STDOUT,
shell=True,
cwd=cwd)
else:
result = subprocess.check_output(
os_command,
# shell=True,
stderr=subprocess.STDOUT,
cwd=cwd)
except:
if witherror:
Console.error("problem executing subprocess",
traceflag=traceflag)
if result is not None:
result = result.strip().decode()
return result | [
"def",
"execute",
"(",
"cls",
",",
"cmd",
",",
"arguments",
"=",
"\"\"",
",",
"shell",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"traceflag",
"=",
"True",
",",
"witherror",
"=",
"True",
")",
":",
"# print \"--------------\"",
"result",
"=",
"None",
"... | Run Shell command
:param witherror: if set to False the error will not be printed
:param traceflag: if set to true the trace is printed in case of an error
:param cwd: the current working directory in whcih the command is supposed to be executed.
:param shell: if set to true the subprocess is called as part of a shell
:param cmd: command to run
:param arguments: we do not know yet
:return: | [
"Run",
"Shell",
"command"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/Shell.py#L681-L742 |
4,676 | cloudmesh/cloudmesh-common | cloudmesh/common/util.py | tempdir | def tempdir(*args, **kwargs):
"""A contextmanager to work in an auto-removed temporary directory
Arguments are passed through to tempfile.mkdtemp
example:
>>> with tempdir() as path:
... pass
"""
d = tempfile.mkdtemp(*args, **kwargs)
try:
yield d
finally:
shutil.rmtree(d) | python | def tempdir(*args, **kwargs):
d = tempfile.mkdtemp(*args, **kwargs)
try:
yield d
finally:
shutil.rmtree(d) | [
"def",
"tempdir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"d",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"d",
")"
] | A contextmanager to work in an auto-removed temporary directory
Arguments are passed through to tempfile.mkdtemp
example:
>>> with tempdir() as path:
... pass | [
"A",
"contextmanager",
"to",
"work",
"in",
"an",
"auto",
"-",
"removed",
"temporary",
"directory"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/util.py#L34-L49 |
4,677 | cloudmesh/cloudmesh-common | cloudmesh/common/util.py | exponential_backoff | def exponential_backoff(fn, sleeptime_s_max=30 * 60):
"""Calls `fn` until it returns True, with an exponentially increasing wait time between calls"""
sleeptime_ms = 500
while True:
if fn():
return True
else:
print('Sleeping {} ms'.format(sleeptime_ms))
time.sleep(sleeptime_ms / 1000.0)
sleeptime_ms *= 2
if sleeptime_ms / 1000.0 > sleeptime_s_max:
return False | python | def exponential_backoff(fn, sleeptime_s_max=30 * 60):
sleeptime_ms = 500
while True:
if fn():
return True
else:
print('Sleeping {} ms'.format(sleeptime_ms))
time.sleep(sleeptime_ms / 1000.0)
sleeptime_ms *= 2
if sleeptime_ms / 1000.0 > sleeptime_s_max:
return False | [
"def",
"exponential_backoff",
"(",
"fn",
",",
"sleeptime_s_max",
"=",
"30",
"*",
"60",
")",
":",
"sleeptime_ms",
"=",
"500",
"while",
"True",
":",
"if",
"fn",
"(",
")",
":",
"return",
"True",
"else",
":",
"print",
"(",
"'Sleeping {} ms'",
".",
"format",
... | Calls `fn` until it returns True, with an exponentially increasing wait time between calls | [
"Calls",
"fn",
"until",
"it",
"returns",
"True",
"with",
"an",
"exponentially",
"increasing",
"wait",
"time",
"between",
"calls"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/util.py#L52-L65 |
4,678 | cloudmesh/cloudmesh-common | cloudmesh/common/util.py | grep | def grep(pattern, filename):
"""Very simple grep that returns the first matching line in a file.
String matching only, does not do REs as currently implemented.
"""
try:
# for line in file
# if line matches pattern:
# return line
return next((L for L in open(filename) if L.find(pattern) >= 0))
except StopIteration:
return '' | python | def grep(pattern, filename):
try:
# for line in file
# if line matches pattern:
# return line
return next((L for L in open(filename) if L.find(pattern) >= 0))
except StopIteration:
return '' | [
"def",
"grep",
"(",
"pattern",
",",
"filename",
")",
":",
"try",
":",
"# for line in file",
"# if line matches pattern:",
"# return line",
"return",
"next",
"(",
"(",
"L",
"for",
"L",
"in",
"open",
"(",
"filename",
")",
"if",
"L",
".",
"find",
"(",
"pat... | Very simple grep that returns the first matching line in a file.
String matching only, does not do REs as currently implemented. | [
"Very",
"simple",
"grep",
"that",
"returns",
"the",
"first",
"matching",
"line",
"in",
"a",
"file",
".",
"String",
"matching",
"only",
"does",
"not",
"do",
"REs",
"as",
"currently",
"implemented",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/util.py#L86-L96 |
4,679 | cloudmesh/cloudmesh-common | cloudmesh/common/util.py | path_expand | def path_expand(text):
""" returns a string with expanded variable.
:param text: the path to be expanded, which can include ~ and environment $ variables
:param text: string
"""
result = os.path.expandvars(os.path.expanduser(text))
# template = Template(text)
# result = template.substitute(os.environ)
if result.startswith("."):
result = result.replace(".", os.getcwd(), 1)
return result | python | def path_expand(text):
result = os.path.expandvars(os.path.expanduser(text))
# template = Template(text)
# result = template.substitute(os.environ)
if result.startswith("."):
result = result.replace(".", os.getcwd(), 1)
return result | [
"def",
"path_expand",
"(",
"text",
")",
":",
"result",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"text",
")",
")",
"# template = Template(text)",
"# result = template.substitute(os.environ)",
"if",
"result",
".",
... | returns a string with expanded variable.
:param text: the path to be expanded, which can include ~ and environment $ variables
:param text: string | [
"returns",
"a",
"string",
"with",
"expanded",
"variable",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/util.py#L99-L114 |
4,680 | cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | ordered_load | def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
"""
Loads an ordered dict into a yaml while preserving the order
:param stream: the name of the stream
:param Loader: the yam loader (such as yaml.SafeLoader)
:param object_pairs_hook: the ordered dict
"""
# noinspection PyClassHasNoInit
class OrderedLoader(Loader):
"""
A helper class to define an Ordered Loader
"""
pass
def construct_mapping(loader, node):
"""
construct a flattened node mapping
:param loader: the loader
:param node: the node dict
:return:
"""
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return yaml.load(stream, OrderedLoader) | python | def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
# noinspection PyClassHasNoInit
class OrderedLoader(Loader):
"""
A helper class to define an Ordered Loader
"""
pass
def construct_mapping(loader, node):
"""
construct a flattened node mapping
:param loader: the loader
:param node: the node dict
:return:
"""
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))
OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)
return yaml.load(stream, OrderedLoader) | [
"def",
"ordered_load",
"(",
"stream",
",",
"Loader",
"=",
"yaml",
".",
"Loader",
",",
"object_pairs_hook",
"=",
"OrderedDict",
")",
":",
"# noinspection PyClassHasNoInit",
"class",
"OrderedLoader",
"(",
"Loader",
")",
":",
"\"\"\"\n A helper class to define an Or... | Loads an ordered dict into a yaml while preserving the order
:param stream: the name of the stream
:param Loader: the yam loader (such as yaml.SafeLoader)
:param object_pairs_hook: the ordered dict | [
"Loads",
"an",
"ordered",
"dict",
"into",
"a",
"yaml",
"while",
"preserving",
"the",
"order"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L63-L92 |
4,681 | cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | read_yaml_config | def read_yaml_config(filename, check=True, osreplace=True, exit=True):
"""
reads in a yaml file from the specified filename. If check is set to true
the code will fail if the file does not exist. However if it is set to
false and the file does not exist, None is returned.
:param exit: if true is exist with sys exit
:param osreplace: if true replaces environment variables from the OS
:param filename: the file name
:param check: if True fails if the file does not exist,
if False and the file does not exist return will be None
"""
location = filename
if location is not None:
location = path_expand(location)
if not os.path.exists(location) and not check:
return None
if check and os.path.exists(location):
# test for tab in yaml file
if check_file_for_tabs(location):
log.error("The file {0} contains tabs. yaml "
"Files are not allowed to contain tabs".format(location))
sys.exit()
result = None
try:
if osreplace:
result = open(location, 'r').read()
t = Template(result)
result = t.substitute(os.environ)
# data = yaml.safe_load(result)
data = ordered_load(result, yaml.SafeLoader)
else:
f = open(location, "r")
# data = yaml.safe_load(f)
data = ordered_load(result, yaml.SafeLoader)
f.close()
return data
except Exception as e:
log.error(
"The file {0} fails with a yaml read error".format(filename))
Error.traceback(e)
sys.exit()
else:
log.error("The file {0} does not exist.".format(filename))
if exit:
sys.exit()
return None | python | def read_yaml_config(filename, check=True, osreplace=True, exit=True):
location = filename
if location is not None:
location = path_expand(location)
if not os.path.exists(location) and not check:
return None
if check and os.path.exists(location):
# test for tab in yaml file
if check_file_for_tabs(location):
log.error("The file {0} contains tabs. yaml "
"Files are not allowed to contain tabs".format(location))
sys.exit()
result = None
try:
if osreplace:
result = open(location, 'r').read()
t = Template(result)
result = t.substitute(os.environ)
# data = yaml.safe_load(result)
data = ordered_load(result, yaml.SafeLoader)
else:
f = open(location, "r")
# data = yaml.safe_load(f)
data = ordered_load(result, yaml.SafeLoader)
f.close()
return data
except Exception as e:
log.error(
"The file {0} fails with a yaml read error".format(filename))
Error.traceback(e)
sys.exit()
else:
log.error("The file {0} does not exist.".format(filename))
if exit:
sys.exit()
return None | [
"def",
"read_yaml_config",
"(",
"filename",
",",
"check",
"=",
"True",
",",
"osreplace",
"=",
"True",
",",
"exit",
"=",
"True",
")",
":",
"location",
"=",
"filename",
"if",
"location",
"is",
"not",
"None",
":",
"location",
"=",
"path_expand",
"(",
"locat... | reads in a yaml file from the specified filename. If check is set to true
the code will fail if the file does not exist. However if it is set to
false and the file does not exist, None is returned.
:param exit: if true is exist with sys exit
:param osreplace: if true replaces environment variables from the OS
:param filename: the file name
:param check: if True fails if the file does not exist,
if False and the file does not exist return will be None | [
"reads",
"in",
"a",
"yaml",
"file",
"from",
"the",
"specified",
"filename",
".",
"If",
"check",
"is",
"set",
"to",
"true",
"the",
"code",
"will",
"fail",
"if",
"the",
"file",
"does",
"not",
"exist",
".",
"However",
"if",
"it",
"is",
"set",
"to",
"fal... | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L129-L185 |
4,682 | cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | BaseConfigDict._update_meta | def _update_meta(self):
"""
internal function to define the metadata regarding filename, location,
and prefix.
"""
for v in ["filename", "location", "prefix"]:
if "meta" not in self:
self["meta"] = {}
self["meta"][v] = self[v]
del self[v] | python | def _update_meta(self):
for v in ["filename", "location", "prefix"]:
if "meta" not in self:
self["meta"] = {}
self["meta"][v] = self[v]
del self[v] | [
"def",
"_update_meta",
"(",
"self",
")",
":",
"for",
"v",
"in",
"[",
"\"filename\"",
",",
"\"location\"",
",",
"\"prefix\"",
"]",
":",
"if",
"\"meta\"",
"not",
"in",
"self",
":",
"self",
"[",
"\"meta\"",
"]",
"=",
"{",
"}",
"self",
"[",
"\"meta\"",
"... | internal function to define the metadata regarding filename, location,
and prefix. | [
"internal",
"function",
"to",
"define",
"the",
"metadata",
"regarding",
"filename",
"location",
"and",
"prefix",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L264-L273 |
4,683 | cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | BaseConfigDict.load | def load(self, filename):
"""
Loads the yaml file with the given filename.
:param filename: the name of the yaml file
"""
self._set_filename(filename)
if os.path.isfile(self['location']):
# d = OrderedDict(read_yaml_config(self['location'], check=True))
d = read_yaml_config(self['location'], check=True)
with open(self['location']) as myfile:
document = myfile.read()
x = yaml.load(document, Loader=yaml.FullLoader)
try:
self.update(d)
except:
print("ERROR: can not find", self["location"])
sys.exit()
else:
print(
"Error while reading and updating the configuration file {:}".format(
filename)) | python | def load(self, filename):
self._set_filename(filename)
if os.path.isfile(self['location']):
# d = OrderedDict(read_yaml_config(self['location'], check=True))
d = read_yaml_config(self['location'], check=True)
with open(self['location']) as myfile:
document = myfile.read()
x = yaml.load(document, Loader=yaml.FullLoader)
try:
self.update(d)
except:
print("ERROR: can not find", self["location"])
sys.exit()
else:
print(
"Error while reading and updating the configuration file {:}".format(
filename)) | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_set_filename",
"(",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
"[",
"'location'",
"]",
")",
":",
"# d = OrderedDict(read_yaml_config(self['location'], check=True))",... | Loads the yaml file with the given filename.
:param filename: the name of the yaml file | [
"Loads",
"the",
"yaml",
"file",
"with",
"the",
"given",
"filename",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L284-L307 |
4,684 | cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | BaseConfigDict.error_keys_not_found | def error_keys_not_found(self, keys):
"""
Check if the requested keys are found in the dict.
:param keys: keys to be looked for
"""
try:
log.error("Filename: {0}".format(self['meta']['location']))
except:
log.error("Filename: {0}".format(self['location']))
log.error("Key '{0}' does not exist".format('.'.join(keys)))
indent = ""
last_index = len(keys) - 1
for i, k in enumerate(keys):
if i == last_index:
log.error(indent + k + ": <- this value is missing")
else:
log.error(indent + k + ":")
indent += " " | python | def error_keys_not_found(self, keys):
try:
log.error("Filename: {0}".format(self['meta']['location']))
except:
log.error("Filename: {0}".format(self['location']))
log.error("Key '{0}' does not exist".format('.'.join(keys)))
indent = ""
last_index = len(keys) - 1
for i, k in enumerate(keys):
if i == last_index:
log.error(indent + k + ": <- this value is missing")
else:
log.error(indent + k + ":")
indent += " " | [
"def",
"error_keys_not_found",
"(",
"self",
",",
"keys",
")",
":",
"try",
":",
"log",
".",
"error",
"(",
"\"Filename: {0}\"",
".",
"format",
"(",
"self",
"[",
"'meta'",
"]",
"[",
"'location'",
"]",
")",
")",
"except",
":",
"log",
".",
"error",
"(",
"... | Check if the requested keys are found in the dict.
:param keys: keys to be looked for | [
"Check",
"if",
"the",
"requested",
"keys",
"are",
"found",
"in",
"the",
"dict",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L361-L379 |
4,685 | cloudmesh/cloudmesh-common | cloudmesh/common/BaseConfigDict.py | BaseConfigDict.yaml | def yaml(self):
"""
returns the yaml output of the dict.
"""
return ordered_dump(OrderedDict(self),
Dumper=yaml.SafeDumper,
default_flow_style=False) | python | def yaml(self):
return ordered_dump(OrderedDict(self),
Dumper=yaml.SafeDumper,
default_flow_style=False) | [
"def",
"yaml",
"(",
"self",
")",
":",
"return",
"ordered_dump",
"(",
"OrderedDict",
"(",
"self",
")",
",",
"Dumper",
"=",
"yaml",
".",
"SafeDumper",
",",
"default_flow_style",
"=",
"False",
")"
] | returns the yaml output of the dict. | [
"returns",
"the",
"yaml",
"output",
"of",
"the",
"dict",
"."
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/BaseConfigDict.py#L393-L399 |
4,686 | cloudmesh/cloudmesh-common | cloudmesh/common/Printer.py | Printer.csv | def csv(cls,
d,
order=None,
header=None,
sort_keys=True):
"""
prints a table in csv format
:param d: A a dict with dicts of the same type.
:type d: dict
:param order:The order in which the columns are printed.
The order is specified by the key names of the dict.
:type order:
:param header: The Header of each of the columns
:type header: list or tuple of field names
:param sort_keys: TODO: not yet implemented
:type sort_keys: bool
:return: a string representing the table in csv format
"""
first_element = list(d)[0]
def _keys():
return list(d[first_element])
# noinspection PyBroadException
def _get(element, key):
try:
tmp = str(d[element][key])
except:
tmp = ' '
return tmp
if d is None or d == {}:
return None
if order is None:
order = _keys()
if header is None and order is not None:
header = order
elif header is None:
header = _keys()
table = ""
content = []
for attribute in order:
content.append(attribute)
table = table + ",".join([str(e) for e in content]) + "\n"
for job in d:
content = []
for attribute in order:
try:
content.append(d[job][attribute])
except:
content.append("None")
table = table + ",".join([str(e) for e in content]) + "\n"
return table | python | def csv(cls,
d,
order=None,
header=None,
sort_keys=True):
first_element = list(d)[0]
def _keys():
return list(d[first_element])
# noinspection PyBroadException
def _get(element, key):
try:
tmp = str(d[element][key])
except:
tmp = ' '
return tmp
if d is None or d == {}:
return None
if order is None:
order = _keys()
if header is None and order is not None:
header = order
elif header is None:
header = _keys()
table = ""
content = []
for attribute in order:
content.append(attribute)
table = table + ",".join([str(e) for e in content]) + "\n"
for job in d:
content = []
for attribute in order:
try:
content.append(d[job][attribute])
except:
content.append("None")
table = table + ",".join([str(e) for e in content]) + "\n"
return table | [
"def",
"csv",
"(",
"cls",
",",
"d",
",",
"order",
"=",
"None",
",",
"header",
"=",
"None",
",",
"sort_keys",
"=",
"True",
")",
":",
"first_element",
"=",
"list",
"(",
"d",
")",
"[",
"0",
"]",
"def",
"_keys",
"(",
")",
":",
"return",
"list",
"("... | prints a table in csv format
:param d: A a dict with dicts of the same type.
:type d: dict
:param order:The order in which the columns are printed.
The order is specified by the key names of the dict.
:type order:
:param header: The Header of each of the columns
:type header: list or tuple of field names
:param sort_keys: TODO: not yet implemented
:type sort_keys: bool
:return: a string representing the table in csv format | [
"prints",
"a",
"table",
"in",
"csv",
"format"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/Printer.py#L169-L226 |
4,687 | cloudmesh/cloudmesh-common | cloudmesh/common/ssh/authorized_keys.py | get_fingerprint_from_public_key | def get_fingerprint_from_public_key(pubkey):
"""Generate the fingerprint of a public key
:param str pubkey: the value of the public key
:returns: fingerprint
:rtype: str
"""
# TODO: why is there a tmpdir?
with tempdir() as workdir:
key = os.path.join(workdir, 'key.pub')
with open(key, 'w') as fd:
fd.write(pubkey)
cmd = [
'ssh-keygen',
'-l',
'-f', key,
]
p = Subprocess(cmd)
output = p.stdout.strip()
bits, fingerprint, _ = output.split(' ', 2)
return fingerprint | python | def get_fingerprint_from_public_key(pubkey):
# TODO: why is there a tmpdir?
with tempdir() as workdir:
key = os.path.join(workdir, 'key.pub')
with open(key, 'w') as fd:
fd.write(pubkey)
cmd = [
'ssh-keygen',
'-l',
'-f', key,
]
p = Subprocess(cmd)
output = p.stdout.strip()
bits, fingerprint, _ = output.split(' ', 2)
return fingerprint | [
"def",
"get_fingerprint_from_public_key",
"(",
"pubkey",
")",
":",
"# TODO: why is there a tmpdir?",
"with",
"tempdir",
"(",
")",
"as",
"workdir",
":",
"key",
"=",
"os",
".",
"path",
".",
"join",
"(",
"workdir",
",",
"'key.pub'",
")",
"with",
"open",
"(",
"k... | Generate the fingerprint of a public key
:param str pubkey: the value of the public key
:returns: fingerprint
:rtype: str | [
"Generate",
"the",
"fingerprint",
"of",
"a",
"public",
"key"
] | ae4fae09cd78205d179ea692dc58f0b0c8fea2b8 | https://github.com/cloudmesh/cloudmesh-common/blob/ae4fae09cd78205d179ea692dc58f0b0c8fea2b8/cloudmesh/common/ssh/authorized_keys.py#L17-L40 |
4,688 | ella/ella | ella/photos/newman_admin.py | PhotoAdmin.thumb | def thumb(self, obj):
"""
Generates html and thumbnails for admin site.
"""
format, created = Format.objects.get_or_create(name='newman_thumb',
defaults={
'max_width': 100,
'max_height': 100,
'flexible_height': False,
'stretch': False,
'nocrop': True,
})
if created:
format.sites = Site.objects.all()
info = obj.get_formated_photo(format)
return '<a href="%(href)s"><img src="%(src)s"></a>' % {
'href': '%s/' % obj.pk,
'src': info['url']
} | python | def thumb(self, obj):
format, created = Format.objects.get_or_create(name='newman_thumb',
defaults={
'max_width': 100,
'max_height': 100,
'flexible_height': False,
'stretch': False,
'nocrop': True,
})
if created:
format.sites = Site.objects.all()
info = obj.get_formated_photo(format)
return '<a href="%(href)s"><img src="%(src)s"></a>' % {
'href': '%s/' % obj.pk,
'src': info['url']
} | [
"def",
"thumb",
"(",
"self",
",",
"obj",
")",
":",
"format",
",",
"created",
"=",
"Format",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"'newman_thumb'",
",",
"defaults",
"=",
"{",
"'max_width'",
":",
"100",
",",
"'max_height'",
":",
"100",
... | Generates html and thumbnails for admin site. | [
"Generates",
"html",
"and",
"thumbnails",
"for",
"admin",
"site",
"."
] | 4a1414991f649dc21c4b777dc6b41a922a13faa7 | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/newman_admin.py#L125-L146 |
4,689 | ssalentin/plip | plip/plipcmd.py | process_pdb | def process_pdb(pdbfile, outpath, as_string=False, outputprefix='report'):
"""Analysis of a single PDB file. Can generate textual reports XML, PyMOL session files and images as output."""
if not as_string:
startmessage = '\nStarting analysis of %s\n' % pdbfile.split('/')[-1]
else:
startmessage = "Starting analysis from stdin.\n"
write_message(startmessage)
write_message('='*len(startmessage)+'\n')
mol = PDBComplex()
mol.output_path = outpath
mol.load_pdb(pdbfile, as_string=as_string)
# #@todo Offers possibility for filter function from command line (by ligand chain, position, hetid)
for ligand in mol.ligands:
mol.characterize_complex(ligand)
create_folder_if_not_exists(outpath)
# Generate the report files
streport = StructureReport(mol, outputprefix=outputprefix)
config.MAXTHREADS = min(config.MAXTHREADS, len(mol.interaction_sets))
######################################
# PyMOL Visualization (parallelized) #
######################################
if config.PYMOL or config.PICS:
try:
from plip.modules.visualize import visualize_in_pymol
except ImportError:
from modules.visualize import visualize_in_pymol
complexes = [VisualizerData(mol, site) for site in sorted(mol.interaction_sets)
if not len(mol.interaction_sets[site].interacting_res) == 0]
if config.MAXTHREADS > 1:
write_message('\nGenerating visualizations in parallel on %i cores ...' % config.MAXTHREADS)
parfn = parallel_fn(visualize_in_pymol)
parfn(complexes, processes=config.MAXTHREADS)
else:
[visualize_in_pymol(plcomplex) for plcomplex in complexes]
if config.XML: # Generate report in xml format
streport.write_xml(as_string=config.STDOUT)
if config.TXT: # Generate report in txt (rst) format
streport.write_txt(as_string=config.STDOUT) | python | def process_pdb(pdbfile, outpath, as_string=False, outputprefix='report'):
if not as_string:
startmessage = '\nStarting analysis of %s\n' % pdbfile.split('/')[-1]
else:
startmessage = "Starting analysis from stdin.\n"
write_message(startmessage)
write_message('='*len(startmessage)+'\n')
mol = PDBComplex()
mol.output_path = outpath
mol.load_pdb(pdbfile, as_string=as_string)
# #@todo Offers possibility for filter function from command line (by ligand chain, position, hetid)
for ligand in mol.ligands:
mol.characterize_complex(ligand)
create_folder_if_not_exists(outpath)
# Generate the report files
streport = StructureReport(mol, outputprefix=outputprefix)
config.MAXTHREADS = min(config.MAXTHREADS, len(mol.interaction_sets))
######################################
# PyMOL Visualization (parallelized) #
######################################
if config.PYMOL or config.PICS:
try:
from plip.modules.visualize import visualize_in_pymol
except ImportError:
from modules.visualize import visualize_in_pymol
complexes = [VisualizerData(mol, site) for site in sorted(mol.interaction_sets)
if not len(mol.interaction_sets[site].interacting_res) == 0]
if config.MAXTHREADS > 1:
write_message('\nGenerating visualizations in parallel on %i cores ...' % config.MAXTHREADS)
parfn = parallel_fn(visualize_in_pymol)
parfn(complexes, processes=config.MAXTHREADS)
else:
[visualize_in_pymol(plcomplex) for plcomplex in complexes]
if config.XML: # Generate report in xml format
streport.write_xml(as_string=config.STDOUT)
if config.TXT: # Generate report in txt (rst) format
streport.write_txt(as_string=config.STDOUT) | [
"def",
"process_pdb",
"(",
"pdbfile",
",",
"outpath",
",",
"as_string",
"=",
"False",
",",
"outputprefix",
"=",
"'report'",
")",
":",
"if",
"not",
"as_string",
":",
"startmessage",
"=",
"'\\nStarting analysis of %s\\n'",
"%",
"pdbfile",
".",
"split",
"(",
"'/'... | Analysis of a single PDB file. Can generate textual reports XML, PyMOL session files and images as output. | [
"Analysis",
"of",
"a",
"single",
"PDB",
"file",
".",
"Can",
"generate",
"textual",
"reports",
"XML",
"PyMOL",
"session",
"files",
"and",
"images",
"as",
"output",
"."
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/plipcmd.py#L53-L97 |
4,690 | ssalentin/plip | plip/plipcmd.py | download_structure | def download_structure(inputpdbid):
"""Given a PDB ID, downloads the corresponding PDB structure.
Checks for validity of ID and handles error while downloading.
Returns the path of the downloaded file."""
try:
if len(inputpdbid) != 4 or extract_pdbid(inputpdbid.lower()) == 'UnknownProtein':
sysexit(3, 'Invalid PDB ID (Wrong format)\n')
pdbfile, pdbid = fetch_pdb(inputpdbid.lower())
pdbpath = tilde_expansion('%s/%s.pdb' % (config.BASEPATH.rstrip('/'), pdbid))
create_folder_if_not_exists(config.BASEPATH)
with open(pdbpath, 'w') as g:
g.write(pdbfile)
write_message('file downloaded as %s\n\n' % pdbpath)
return pdbpath, pdbid
except ValueError: # Invalid PDB ID, cannot fetch from RCBS server
sysexit(3, 'Invalid PDB ID (Entry does not exist)\n') | python | def download_structure(inputpdbid):
try:
if len(inputpdbid) != 4 or extract_pdbid(inputpdbid.lower()) == 'UnknownProtein':
sysexit(3, 'Invalid PDB ID (Wrong format)\n')
pdbfile, pdbid = fetch_pdb(inputpdbid.lower())
pdbpath = tilde_expansion('%s/%s.pdb' % (config.BASEPATH.rstrip('/'), pdbid))
create_folder_if_not_exists(config.BASEPATH)
with open(pdbpath, 'w') as g:
g.write(pdbfile)
write_message('file downloaded as %s\n\n' % pdbpath)
return pdbpath, pdbid
except ValueError: # Invalid PDB ID, cannot fetch from RCBS server
sysexit(3, 'Invalid PDB ID (Entry does not exist)\n') | [
"def",
"download_structure",
"(",
"inputpdbid",
")",
":",
"try",
":",
"if",
"len",
"(",
"inputpdbid",
")",
"!=",
"4",
"or",
"extract_pdbid",
"(",
"inputpdbid",
".",
"lower",
"(",
")",
")",
"==",
"'UnknownProtein'",
":",
"sysexit",
"(",
"3",
",",
"'Invali... | Given a PDB ID, downloads the corresponding PDB structure.
Checks for validity of ID and handles error while downloading.
Returns the path of the downloaded file. | [
"Given",
"a",
"PDB",
"ID",
"downloads",
"the",
"corresponding",
"PDB",
"structure",
".",
"Checks",
"for",
"validity",
"of",
"ID",
"and",
"handles",
"error",
"while",
"downloading",
".",
"Returns",
"the",
"path",
"of",
"the",
"downloaded",
"file",
"."
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/plipcmd.py#L100-L116 |
4,691 | ssalentin/plip | plip/plipcmd.py | remove_duplicates | def remove_duplicates(slist):
"""Checks input lists for duplicates and returns
a list with unique entries"""
unique = list(set(slist))
difference = len(slist) - len(unique)
if difference == 1:
write_message("Removed one duplicate entry from input list.\n")
if difference > 1:
write_message("Removed %i duplicate entries from input list.\n" % difference)
return unique | python | def remove_duplicates(slist):
unique = list(set(slist))
difference = len(slist) - len(unique)
if difference == 1:
write_message("Removed one duplicate entry from input list.\n")
if difference > 1:
write_message("Removed %i duplicate entries from input list.\n" % difference)
return unique | [
"def",
"remove_duplicates",
"(",
"slist",
")",
":",
"unique",
"=",
"list",
"(",
"set",
"(",
"slist",
")",
")",
"difference",
"=",
"len",
"(",
"slist",
")",
"-",
"len",
"(",
"unique",
")",
"if",
"difference",
"==",
"1",
":",
"write_message",
"(",
"\"R... | Checks input lists for duplicates and returns
a list with unique entries | [
"Checks",
"input",
"lists",
"for",
"duplicates",
"and",
"returns",
"a",
"list",
"with",
"unique",
"entries"
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/plipcmd.py#L119-L128 |
4,692 | ssalentin/plip | plip/plipcmd.py | main | def main(inputstructs, inputpdbids):
"""Main function. Calls functions for processing, report generation and visualization."""
pdbid, pdbpath = None, None
# #@todo For multiprocessing, implement better stacktracing for errors
# Print title and version
title = "* Protein-Ligand Interaction Profiler v%s *" % __version__
write_message('\n' + '*' * len(title) + '\n')
write_message(title)
write_message('\n' + '*' * len(title) + '\n\n')
outputprefix = config.OUTPUTFILENAME
if inputstructs is not None: # Process PDB file(s)
num_structures = len(inputstructs)
inputstructs = remove_duplicates(inputstructs)
read_from_stdin = False
for inputstruct in inputstructs:
if inputstruct == '-':
inputstruct = sys.stdin.read()
read_from_stdin = True
if config.RAWSTRING:
if sys.version_info < (3,):
inputstruct = bytes(inputstruct).decode('unicode_escape')
else:
inputstruct = bytes(inputstruct, 'utf8').decode('unicode_escape')
else:
if os.path.getsize(inputstruct) == 0:
sysexit(2, 'Empty PDB file\n') # Exit if input file is empty
if num_structures > 1:
basename = inputstruct.split('.')[-2].split('/')[-1]
config.OUTPATH = '/'.join([config.BASEPATH, basename])
outputprefix = 'report'
process_pdb(inputstruct, config.OUTPATH, as_string=read_from_stdin, outputprefix=outputprefix)
else: # Try to fetch the current PDB structure(s) directly from the RCBS server
num_pdbids = len(inputpdbids)
inputpdbids = remove_duplicates(inputpdbids)
for inputpdbid in inputpdbids:
pdbpath, pdbid = download_structure(inputpdbid)
if num_pdbids > 1:
config.OUTPATH = '/'.join([config.BASEPATH, pdbid[1:3].upper(), pdbid.upper()])
outputprefix = 'report'
process_pdb(pdbpath, config.OUTPATH, outputprefix=outputprefix)
if (pdbid is not None or inputstructs is not None) and config.BASEPATH is not None:
if config.BASEPATH in ['.', './']:
write_message('\nFinished analysis. Find the result files in the working directory.\n\n')
else:
write_message('\nFinished analysis. Find the result files in %s\n\n' % config.BASEPATH) | python | def main(inputstructs, inputpdbids):
pdbid, pdbpath = None, None
# #@todo For multiprocessing, implement better stacktracing for errors
# Print title and version
title = "* Protein-Ligand Interaction Profiler v%s *" % __version__
write_message('\n' + '*' * len(title) + '\n')
write_message(title)
write_message('\n' + '*' * len(title) + '\n\n')
outputprefix = config.OUTPUTFILENAME
if inputstructs is not None: # Process PDB file(s)
num_structures = len(inputstructs)
inputstructs = remove_duplicates(inputstructs)
read_from_stdin = False
for inputstruct in inputstructs:
if inputstruct == '-':
inputstruct = sys.stdin.read()
read_from_stdin = True
if config.RAWSTRING:
if sys.version_info < (3,):
inputstruct = bytes(inputstruct).decode('unicode_escape')
else:
inputstruct = bytes(inputstruct, 'utf8').decode('unicode_escape')
else:
if os.path.getsize(inputstruct) == 0:
sysexit(2, 'Empty PDB file\n') # Exit if input file is empty
if num_structures > 1:
basename = inputstruct.split('.')[-2].split('/')[-1]
config.OUTPATH = '/'.join([config.BASEPATH, basename])
outputprefix = 'report'
process_pdb(inputstruct, config.OUTPATH, as_string=read_from_stdin, outputprefix=outputprefix)
else: # Try to fetch the current PDB structure(s) directly from the RCBS server
num_pdbids = len(inputpdbids)
inputpdbids = remove_duplicates(inputpdbids)
for inputpdbid in inputpdbids:
pdbpath, pdbid = download_structure(inputpdbid)
if num_pdbids > 1:
config.OUTPATH = '/'.join([config.BASEPATH, pdbid[1:3].upper(), pdbid.upper()])
outputprefix = 'report'
process_pdb(pdbpath, config.OUTPATH, outputprefix=outputprefix)
if (pdbid is not None or inputstructs is not None) and config.BASEPATH is not None:
if config.BASEPATH in ['.', './']:
write_message('\nFinished analysis. Find the result files in the working directory.\n\n')
else:
write_message('\nFinished analysis. Find the result files in %s\n\n' % config.BASEPATH) | [
"def",
"main",
"(",
"inputstructs",
",",
"inputpdbids",
")",
":",
"pdbid",
",",
"pdbpath",
"=",
"None",
",",
"None",
"# #@todo For multiprocessing, implement better stacktracing for errors",
"# Print title and version",
"title",
"=",
"\"* Protein-Ligand Interaction Profiler v%s... | Main function. Calls functions for processing, report generation and visualization. | [
"Main",
"function",
".",
"Calls",
"functions",
"for",
"processing",
"report",
"generation",
"and",
"visualization",
"."
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/plipcmd.py#L131-L177 |
4,693 | ella/ella | ella/photos/admin.py | FormatedPhotoForm.clean | def clean(self):
"""
Validation function that checks the dimensions of the crop whether it fits into the original and the format.
"""
data = self.cleaned_data
photo = data['photo']
if (
(data['crop_left'] > photo.width) or
(data['crop_top'] > photo.height) or
((data['crop_left'] + data['crop_width']) > photo.width) or
((data['crop_top'] + data['crop_height']) > photo.height)
):
# raise forms.ValidationError, ugettext("The specified crop coordinates do not fit into the source photo.")
raise ValidationError(ugettext("The specified crop coordinates do not fit into the source photo."))
return data | python | def clean(self):
data = self.cleaned_data
photo = data['photo']
if (
(data['crop_left'] > photo.width) or
(data['crop_top'] > photo.height) or
((data['crop_left'] + data['crop_width']) > photo.width) or
((data['crop_top'] + data['crop_height']) > photo.height)
):
# raise forms.ValidationError, ugettext("The specified crop coordinates do not fit into the source photo.")
raise ValidationError(ugettext("The specified crop coordinates do not fit into the source photo."))
return data | [
"def",
"clean",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"cleaned_data",
"photo",
"=",
"data",
"[",
"'photo'",
"]",
"if",
"(",
"(",
"data",
"[",
"'crop_left'",
"]",
">",
"photo",
".",
"width",
")",
"or",
"(",
"data",
"[",
"'crop_top'",
"]",... | Validation function that checks the dimensions of the crop whether it fits into the original and the format. | [
"Validation",
"function",
"that",
"checks",
"the",
"dimensions",
"of",
"the",
"crop",
"whether",
"it",
"fits",
"into",
"the",
"original",
"and",
"the",
"format",
"."
] | 4a1414991f649dc21c4b777dc6b41a922a13faa7 | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/admin.py#L16-L30 |
4,694 | ella/ella | ella/photos/admin.py | FormatForm.clean | def clean(self):
"""
Check format name uniqueness for sites
:return: cleaned_data
"""
data = self.cleaned_data
formats = Format.objects.filter(name=data['name'])
if self.instance:
formats = formats.exclude(pk=self.instance.pk)
exists_sites = []
for f in formats:
for s in f.sites.all():
if s in data['sites']:
exists_sites.append(s.__unicode__())
if len(exists_sites):
raise ValidationError(ugettext("Format with this name exists for site(s): %s" % ", ".join(exists_sites)))
return data | python | def clean(self):
data = self.cleaned_data
formats = Format.objects.filter(name=data['name'])
if self.instance:
formats = formats.exclude(pk=self.instance.pk)
exists_sites = []
for f in formats:
for s in f.sites.all():
if s in data['sites']:
exists_sites.append(s.__unicode__())
if len(exists_sites):
raise ValidationError(ugettext("Format with this name exists for site(s): %s" % ", ".join(exists_sites)))
return data | [
"def",
"clean",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"cleaned_data",
"formats",
"=",
"Format",
".",
"objects",
".",
"filter",
"(",
"name",
"=",
"data",
"[",
"'name'",
"]",
")",
"if",
"self",
".",
"instance",
":",
"formats",
"=",
"formats"... | Check format name uniqueness for sites
:return: cleaned_data | [
"Check",
"format",
"name",
"uniqueness",
"for",
"sites"
] | 4a1414991f649dc21c4b777dc6b41a922a13faa7 | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/admin.py#L37-L58 |
4,695 | ella/ella | ella/photos/admin.py | PhotoOptions.format_photo_json | def format_photo_json(self, request, photo, format):
"Used in admin image 'crop tool'."
try:
photo = get_cached_object(Photo, pk=photo)
format = get_cached_object(Format, pk=format)
content = {
'error': False,
'image':settings.MEDIA_URL + photo.image,
'width':photo.width,
'height': photo.height,
'format_width':format.max_width,
'format_height':format.max_height
}
except (Photo.DoesNotExist, Format.DoesNotExist):
content = {'error':True}
return HttpResponse(simplejson.dumps(content)) | python | def format_photo_json(self, request, photo, format):
"Used in admin image 'crop tool'."
try:
photo = get_cached_object(Photo, pk=photo)
format = get_cached_object(Format, pk=format)
content = {
'error': False,
'image':settings.MEDIA_URL + photo.image,
'width':photo.width,
'height': photo.height,
'format_width':format.max_width,
'format_height':format.max_height
}
except (Photo.DoesNotExist, Format.DoesNotExist):
content = {'error':True}
return HttpResponse(simplejson.dumps(content)) | [
"def",
"format_photo_json",
"(",
"self",
",",
"request",
",",
"photo",
",",
"format",
")",
":",
"try",
":",
"photo",
"=",
"get_cached_object",
"(",
"Photo",
",",
"pk",
"=",
"photo",
")",
"format",
"=",
"get_cached_object",
"(",
"Format",
",",
"pk",
"=",
... | Used in admin image 'crop tool'. | [
"Used",
"in",
"admin",
"image",
"crop",
"tool",
"."
] | 4a1414991f649dc21c4b777dc6b41a922a13faa7 | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/admin.py#L114-L129 |
4,696 | ssalentin/plip | plip/modules/chimeraplip.py | ChimeraVisualizer.set_initial_representations | def set_initial_representations(self):
"""Set the initial representations"""
self.update_model_dict()
self.rc("background solid white")
self.rc("setattr g display 0") # Hide all pseudobonds
self.rc("~display #%i & :/isHet & ~:%s" % (self.model_dict[self.plipname], self.hetid)) | python | def set_initial_representations(self):
self.update_model_dict()
self.rc("background solid white")
self.rc("setattr g display 0") # Hide all pseudobonds
self.rc("~display #%i & :/isHet & ~:%s" % (self.model_dict[self.plipname], self.hetid)) | [
"def",
"set_initial_representations",
"(",
"self",
")",
":",
"self",
".",
"update_model_dict",
"(",
")",
"self",
".",
"rc",
"(",
"\"background solid white\"",
")",
"self",
".",
"rc",
"(",
"\"setattr g display 0\"",
")",
"# Hide all pseudobonds",
"self",
".",
"rc",... | Set the initial representations | [
"Set",
"the",
"initial",
"representations"
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L36-L41 |
4,697 | ssalentin/plip | plip/modules/chimeraplip.py | ChimeraVisualizer.update_model_dict | def update_model_dict(self):
"""Updates the model dictionary"""
dct = {}
models = self.chimera.openModels
for md in models.list():
dct[md.name] = md.id
self.model_dict = dct | python | def update_model_dict(self):
dct = {}
models = self.chimera.openModels
for md in models.list():
dct[md.name] = md.id
self.model_dict = dct | [
"def",
"update_model_dict",
"(",
"self",
")",
":",
"dct",
"=",
"{",
"}",
"models",
"=",
"self",
".",
"chimera",
".",
"openModels",
"for",
"md",
"in",
"models",
".",
"list",
"(",
")",
":",
"dct",
"[",
"md",
".",
"name",
"]",
"=",
"md",
".",
"id",
... | Updates the model dictionary | [
"Updates",
"the",
"model",
"dictionary"
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L43-L49 |
4,698 | ssalentin/plip | plip/modules/chimeraplip.py | ChimeraVisualizer.atom_by_serialnumber | def atom_by_serialnumber(self):
"""Provides a dictionary mapping serial numbers to their atom objects."""
atm_by_snum = {}
for atom in self.model.atoms:
atm_by_snum[atom.serialNumber] = atom
return atm_by_snum | python | def atom_by_serialnumber(self):
atm_by_snum = {}
for atom in self.model.atoms:
atm_by_snum[atom.serialNumber] = atom
return atm_by_snum | [
"def",
"atom_by_serialnumber",
"(",
"self",
")",
":",
"atm_by_snum",
"=",
"{",
"}",
"for",
"atom",
"in",
"self",
".",
"model",
".",
"atoms",
":",
"atm_by_snum",
"[",
"atom",
".",
"serialNumber",
"]",
"=",
"atom",
"return",
"atm_by_snum"
] | Provides a dictionary mapping serial numbers to their atom objects. | [
"Provides",
"a",
"dictionary",
"mapping",
"serial",
"numbers",
"to",
"their",
"atom",
"objects",
"."
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L51-L56 |
4,699 | ssalentin/plip | plip/modules/chimeraplip.py | ChimeraVisualizer.show_halogen | def show_halogen(self):
"""Visualizes halogen bonds."""
grp = self.getPseudoBondGroup("HalogenBonds-%i" % self.tid, associateWith=[self.model])
grp.lineWidth = 3
for i in self.plcomplex.halogen_bonds:
b = grp.newPseudoBond(self.atoms[i[0]], self.atoms[i[1]])
b.color = self.colorbyname('turquoise')
self.bs_res_ids.append(i.acc_id) | python | def show_halogen(self):
grp = self.getPseudoBondGroup("HalogenBonds-%i" % self.tid, associateWith=[self.model])
grp.lineWidth = 3
for i in self.plcomplex.halogen_bonds:
b = grp.newPseudoBond(self.atoms[i[0]], self.atoms[i[1]])
b.color = self.colorbyname('turquoise')
self.bs_res_ids.append(i.acc_id) | [
"def",
"show_halogen",
"(",
"self",
")",
":",
"grp",
"=",
"self",
".",
"getPseudoBondGroup",
"(",
"\"HalogenBonds-%i\"",
"%",
"self",
".",
"tid",
",",
"associateWith",
"=",
"[",
"self",
".",
"model",
"]",
")",
"grp",
".",
"lineWidth",
"=",
"3",
"for",
... | Visualizes halogen bonds. | [
"Visualizes",
"halogen",
"bonds",
"."
] | 906c8d36463689779b403f6c2c9ed06174acaf9a | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L80-L88 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.