repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
liip/taxi | taxi/timesheet/entry.py | Entry.hash | def hash(self):
"""
Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the
same hash.
"""
return u''.join([
self.alias,
self.description,
str(self.ignored),
str(self.flags),
]) | python | def hash(self):
"""
Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the
same hash.
"""
return u''.join([
self.alias,
self.description,
str(self.ignored),
str(self.flags),
]) | [
"def",
"hash",
"(",
"self",
")",
":",
"return",
"u''",
".",
"join",
"(",
"[",
"self",
".",
"alias",
",",
"self",
".",
"description",
",",
"str",
"(",
"self",
".",
"ignored",
")",
",",
"str",
"(",
"self",
".",
"flags",
")",
",",
"]",
")"
] | Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the
same hash. | [
"Return",
"a",
"value",
"that",
"s",
"used",
"to",
"uniquely",
"identify",
"an",
"entry",
"in",
"a",
"date",
"so",
"we",
"can",
"regroup",
"all",
"entries",
"that",
"share",
"the",
"same",
"hash",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L147-L157 | train | 43,900 |
liip/taxi | taxi/timesheet/entry.py | Entry.add_flag | def add_flag(self, flag):
"""
Add flag to the flags and memorize this attribute has changed so we can
regenerate it when outputting text.
"""
super(Entry, self).add_flag(flag)
self._changed_attrs.add('flags') | python | def add_flag(self, flag):
"""
Add flag to the flags and memorize this attribute has changed so we can
regenerate it when outputting text.
"""
super(Entry, self).add_flag(flag)
self._changed_attrs.add('flags') | [
"def",
"add_flag",
"(",
"self",
",",
"flag",
")",
":",
"super",
"(",
"Entry",
",",
"self",
")",
".",
"add_flag",
"(",
"flag",
")",
"self",
".",
"_changed_attrs",
".",
"add",
"(",
"'flags'",
")"
] | Add flag to the flags and memorize this attribute has changed so we can
regenerate it when outputting text. | [
"Add",
"flag",
"to",
"the",
"flags",
"and",
"memorize",
"this",
"attribute",
"has",
"changed",
"so",
"we",
"can",
"regenerate",
"it",
"when",
"outputting",
"text",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L159-L165 | train | 43,901 |
liip/taxi | taxi/timesheet/entry.py | Entry.remove_flag | def remove_flag(self, flag):
"""
Remove flag to the flags and memorize this attribute has changed so we
can regenerate it when outputting text.
"""
super(Entry, self).remove_flag(flag)
self._changed_attrs.add('flags') | python | def remove_flag(self, flag):
"""
Remove flag to the flags and memorize this attribute has changed so we
can regenerate it when outputting text.
"""
super(Entry, self).remove_flag(flag)
self._changed_attrs.add('flags') | [
"def",
"remove_flag",
"(",
"self",
",",
"flag",
")",
":",
"super",
"(",
"Entry",
",",
"self",
")",
".",
"remove_flag",
"(",
"flag",
")",
"self",
".",
"_changed_attrs",
".",
"add",
"(",
"'flags'",
")"
] | Remove flag to the flags and memorize this attribute has changed so we
can regenerate it when outputting text. | [
"Remove",
"flag",
"to",
"the",
"flags",
"and",
"memorize",
"this",
"attribute",
"has",
"changed",
"so",
"we",
"can",
"regenerate",
"it",
"when",
"outputting",
"text",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L167-L173 | train | 43,902 |
liip/taxi | taxi/timesheet/entry.py | EntriesCollection.add_entry | def add_entry(self, date, entry):
"""
Add the given entry to the textual representation.
"""
in_date = False
insert_at = 0
for (lineno, line) in enumerate(self.lines):
# Search for the date of the entry
if isinstance(line, DateLine) and line.date == date:
in_date = True
# Insert here if there is no existing Entry for this date
insert_at = lineno
continue
if in_date:
if isinstance(line, Entry):
insert_at = lineno
elif isinstance(line, DateLine):
break
self.lines.insert(insert_at + 1, entry)
# If there's no other Entry in the current date, add a blank line
# between the date and the entry
if not isinstance(self.lines[insert_at], Entry):
self.lines.insert(insert_at + 1, TextLine('')) | python | def add_entry(self, date, entry):
"""
Add the given entry to the textual representation.
"""
in_date = False
insert_at = 0
for (lineno, line) in enumerate(self.lines):
# Search for the date of the entry
if isinstance(line, DateLine) and line.date == date:
in_date = True
# Insert here if there is no existing Entry for this date
insert_at = lineno
continue
if in_date:
if isinstance(line, Entry):
insert_at = lineno
elif isinstance(line, DateLine):
break
self.lines.insert(insert_at + 1, entry)
# If there's no other Entry in the current date, add a blank line
# between the date and the entry
if not isinstance(self.lines[insert_at], Entry):
self.lines.insert(insert_at + 1, TextLine('')) | [
"def",
"add_entry",
"(",
"self",
",",
"date",
",",
"entry",
")",
":",
"in_date",
"=",
"False",
"insert_at",
"=",
"0",
"for",
"(",
"lineno",
",",
"line",
")",
"in",
"enumerate",
"(",
"self",
".",
"lines",
")",
":",
"# Search for the date of the entry",
"i... | Add the given entry to the textual representation. | [
"Add",
"the",
"given",
"entry",
"to",
"the",
"textual",
"representation",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L317-L343 | train | 43,903 |
liip/taxi | taxi/timesheet/entry.py | EntriesCollection.delete_entries | def delete_entries(self, entries):
"""
Remove the given entries from the textual representation.
"""
self.lines = trim([
line for line in self.lines
if not isinstance(line, Entry) or line not in entries
]) | python | def delete_entries(self, entries):
"""
Remove the given entries from the textual representation.
"""
self.lines = trim([
line for line in self.lines
if not isinstance(line, Entry) or line not in entries
]) | [
"def",
"delete_entries",
"(",
"self",
",",
"entries",
")",
":",
"self",
".",
"lines",
"=",
"trim",
"(",
"[",
"line",
"for",
"line",
"in",
"self",
".",
"lines",
"if",
"not",
"isinstance",
"(",
"line",
",",
"Entry",
")",
"or",
"line",
"not",
"in",
"e... | Remove the given entries from the textual representation. | [
"Remove",
"the",
"given",
"entries",
"from",
"the",
"textual",
"representation",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L352-L359 | train | 43,904 |
liip/taxi | taxi/timesheet/entry.py | EntriesCollection.delete_date | def delete_date(self, date):
"""
Remove the date line from the textual representation. This doesn't
remove any entry line.
"""
self.lines = [
line for line in self.lines
if not isinstance(line, DateLine) or line.date != date
]
self.lines = trim(self.lines) | python | def delete_date(self, date):
"""
Remove the date line from the textual representation. This doesn't
remove any entry line.
"""
self.lines = [
line for line in self.lines
if not isinstance(line, DateLine) or line.date != date
]
self.lines = trim(self.lines) | [
"def",
"delete_date",
"(",
"self",
",",
"date",
")",
":",
"self",
".",
"lines",
"=",
"[",
"line",
"for",
"line",
"in",
"self",
".",
"lines",
"if",
"not",
"isinstance",
"(",
"line",
",",
"DateLine",
")",
"or",
"line",
".",
"date",
"!=",
"date",
"]",... | Remove the date line from the textual representation. This doesn't
remove any entry line. | [
"Remove",
"the",
"date",
"line",
"from",
"the",
"textual",
"representation",
".",
"This",
"doesn",
"t",
"remove",
"any",
"entry",
"line",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L365-L375 | train | 43,905 |
liip/taxi | taxi/timesheet/entry.py | EntriesCollection.add_date | def add_date(self, date):
"""
Add the given date to the textual representation.
"""
self.lines = self.parser.add_date(date, self.lines) | python | def add_date(self, date):
"""
Add the given date to the textual representation.
"""
self.lines = self.parser.add_date(date, self.lines) | [
"def",
"add_date",
"(",
"self",
",",
"date",
")",
":",
"self",
".",
"lines",
"=",
"self",
".",
"parser",
".",
"add_date",
"(",
"date",
",",
"self",
".",
"lines",
")"
] | Add the given date to the textual representation. | [
"Add",
"the",
"given",
"date",
"to",
"the",
"textual",
"representation",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L378-L382 | train | 43,906 |
liip/taxi | taxi/timesheet/entry.py | EntriesList.append | def append(self, x):
"""
Append the given element to the list and synchronize the textual
representation.
"""
super(EntriesList, self).append(x)
if self.entries_collection is not None:
self.entries_collection.add_entry(self.date, x) | python | def append(self, x):
"""
Append the given element to the list and synchronize the textual
representation.
"""
super(EntriesList, self).append(x)
if self.entries_collection is not None:
self.entries_collection.add_entry(self.date, x) | [
"def",
"append",
"(",
"self",
",",
"x",
")",
":",
"super",
"(",
"EntriesList",
",",
"self",
")",
".",
"append",
"(",
"x",
")",
"if",
"self",
".",
"entries_collection",
"is",
"not",
"None",
":",
"self",
".",
"entries_collection",
".",
"add_entry",
"(",
... | Append the given element to the list and synchronize the textual
representation. | [
"Append",
"the",
"given",
"element",
"to",
"the",
"list",
"and",
"synchronize",
"the",
"textual",
"representation",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/entry.py#L540-L548 | train | 43,907 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam._request | async def _request(self, path):
"""Make the actual request and return the parsed response."""
url = '{}{}'.format(self.base_url, path)
data = None
try:
async with self.websession.get(url, auth=self._auth, timeout=self._timeout) as response:
if response.status == 200:
if response.headers['content-type'] == 'application/json':
data = await response.json()
else:
data = await response.text()
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error('Failed to communicate with IP Webcam: %s', error)
self._available = False
return
self._available = True
if isinstance(data, str):
return data.find("Ok") != -1
return data | python | async def _request(self, path):
"""Make the actual request and return the parsed response."""
url = '{}{}'.format(self.base_url, path)
data = None
try:
async with self.websession.get(url, auth=self._auth, timeout=self._timeout) as response:
if response.status == 200:
if response.headers['content-type'] == 'application/json':
data = await response.json()
else:
data = await response.text()
except (asyncio.TimeoutError, aiohttp.ClientError) as error:
_LOGGER.error('Failed to communicate with IP Webcam: %s', error)
self._available = False
return
self._available = True
if isinstance(data, str):
return data.find("Ok") != -1
return data | [
"async",
"def",
"_request",
"(",
"self",
",",
"path",
")",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"path",
")",
"data",
"=",
"None",
"try",
":",
"async",
"with",
"self",
".",
"websession",
".",
"get",
"(",
"url"... | Make the actual request and return the parsed response. | [
"Make",
"the",
"actual",
"request",
"and",
"return",
"the",
"parsed",
"response",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L54-L75 | train | 43,908 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam.update | async def update(self):
"""Fetch the latest data from IP Webcam."""
status_data = await self._request('/status.json?show_avail=1')
if status_data:
self.status_data = status_data
sensor_data = await self._request('/sensors.json')
if sensor_data:
self.sensor_data = sensor_data | python | async def update(self):
"""Fetch the latest data from IP Webcam."""
status_data = await self._request('/status.json?show_avail=1')
if status_data:
self.status_data = status_data
sensor_data = await self._request('/sensors.json')
if sensor_data:
self.sensor_data = sensor_data | [
"async",
"def",
"update",
"(",
"self",
")",
":",
"status_data",
"=",
"await",
"self",
".",
"_request",
"(",
"'/status.json?show_avail=1'",
")",
"if",
"status_data",
":",
"self",
".",
"status_data",
"=",
"status_data",
"sensor_data",
"=",
"await",
"self",
".",
... | Fetch the latest data from IP Webcam. | [
"Fetch",
"the",
"latest",
"data",
"from",
"IP",
"Webcam",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L77-L86 | train | 43,909 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam.current_settings | def current_settings(self):
"""Return dict with all config include."""
settings = {}
if not self.status_data:
return settings
for (key, val) in self.status_data.get('curvals', {}).items():
try:
val = float(val)
except ValueError:
val = val
if val in ('on', 'off'):
val = (val == 'on')
settings[key] = val
return settings | python | def current_settings(self):
"""Return dict with all config include."""
settings = {}
if not self.status_data:
return settings
for (key, val) in self.status_data.get('curvals', {}).items():
try:
val = float(val)
except ValueError:
val = val
if val in ('on', 'off'):
val = (val == 'on')
settings[key] = val
return settings | [
"def",
"current_settings",
"(",
"self",
")",
":",
"settings",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"status_data",
":",
"return",
"settings",
"for",
"(",
"key",
",",
"val",
")",
"in",
"self",
".",
"status_data",
".",
"get",
"(",
"'curvals'",
",",
... | Return dict with all config include. | [
"Return",
"dict",
"with",
"all",
"config",
"include",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L89-L106 | train | 43,910 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam.available_settings | def available_settings(self):
"""Return dict of lists with all available config settings."""
available = {}
if not self.status_data:
return available
for (key, val) in self.status_data.get('avail', {}).items():
available[key] = []
for subval in val:
try:
subval = float(subval)
except ValueError:
subval = subval
if val in ('on', 'off'):
subval = (subval == 'on')
available[key].append(subval)
return available | python | def available_settings(self):
"""Return dict of lists with all available config settings."""
available = {}
if not self.status_data:
return available
for (key, val) in self.status_data.get('avail', {}).items():
available[key] = []
for subval in val:
try:
subval = float(subval)
except ValueError:
subval = subval
if val in ('on', 'off'):
subval = (subval == 'on')
available[key].append(subval)
return available | [
"def",
"available_settings",
"(",
"self",
")",
":",
"available",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"status_data",
":",
"return",
"available",
"for",
"(",
"key",
",",
"val",
")",
"in",
"self",
".",
"status_data",
".",
"get",
"(",
"'avail'",
",",
... | Return dict of lists with all available config settings. | [
"Return",
"dict",
"of",
"lists",
"with",
"all",
"available",
"config",
"settings",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L123-L142 | train | 43,911 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam.change_setting | def change_setting(self, key, val):
"""Change a setting.
Return a coroutine.
"""
if isinstance(val, bool):
payload = 'on' if val else 'off'
else:
payload = val
return self._request('/settings/{}?set={}'.format(key, payload)) | python | def change_setting(self, key, val):
"""Change a setting.
Return a coroutine.
"""
if isinstance(val, bool):
payload = 'on' if val else 'off'
else:
payload = val
return self._request('/settings/{}?set={}'.format(key, payload)) | [
"def",
"change_setting",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"bool",
")",
":",
"payload",
"=",
"'on'",
"if",
"val",
"else",
"'off'",
"else",
":",
"payload",
"=",
"val",
"return",
"self",
".",
"_request"... | Change a setting.
Return a coroutine. | [
"Change",
"a",
"setting",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L159-L168 | train | 43,912 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam.set_orientation | def set_orientation(self, orientation='landscape'):
"""Set the video orientation.
Return a coroutine.
"""
if orientation not in ALLOWED_ORIENTATIONS:
_LOGGER.debug('%s is not a valid orientation', orientation)
return False
return self.change_setting('orientation', orientation) | python | def set_orientation(self, orientation='landscape'):
"""Set the video orientation.
Return a coroutine.
"""
if orientation not in ALLOWED_ORIENTATIONS:
_LOGGER.debug('%s is not a valid orientation', orientation)
return False
return self.change_setting('orientation', orientation) | [
"def",
"set_orientation",
"(",
"self",
",",
"orientation",
"=",
"'landscape'",
")",
":",
"if",
"orientation",
"not",
"in",
"ALLOWED_ORIENTATIONS",
":",
"_LOGGER",
".",
"debug",
"(",
"'%s is not a valid orientation'",
",",
"orientation",
")",
"return",
"False",
"re... | Set the video orientation.
Return a coroutine. | [
"Set",
"the",
"video",
"orientation",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L238-L246 | train | 43,913 |
pvizeli/pydroid-ipcam | pydroid_ipcam.py | PyDroidIPCam.set_scenemode | def set_scenemode(self, scenemode='auto'):
"""Set the video scene mode.
Return a coroutine.
"""
if scenemode not in self.available_settings['scenemode']:
_LOGGER.debug('%s is not a valid scenemode', scenemode)
return False
return self.change_setting('scenemode', scenemode) | python | def set_scenemode(self, scenemode='auto'):
"""Set the video scene mode.
Return a coroutine.
"""
if scenemode not in self.available_settings['scenemode']:
_LOGGER.debug('%s is not a valid scenemode', scenemode)
return False
return self.change_setting('scenemode', scenemode) | [
"def",
"set_scenemode",
"(",
"self",
",",
"scenemode",
"=",
"'auto'",
")",
":",
"if",
"scenemode",
"not",
"in",
"self",
".",
"available_settings",
"[",
"'scenemode'",
"]",
":",
"_LOGGER",
".",
"debug",
"(",
"'%s is not a valid scenemode'",
",",
"scenemode",
")... | Set the video scene mode.
Return a coroutine. | [
"Set",
"the",
"video",
"scene",
"mode",
"."
] | 42275a77fafa01e027d0752664f382b813a6f9b0 | https://github.com/pvizeli/pydroid-ipcam/blob/42275a77fafa01e027d0752664f382b813a6f9b0/pydroid_ipcam.py#L255-L263 | train | 43,914 |
liip/taxi | taxi/utils/date.py | months_ago | def months_ago(date, nb_months=1):
"""
Return the given `date` with `nb_months` substracted from it.
"""
nb_years = nb_months // 12
nb_months = nb_months % 12
month_diff = date.month - nb_months
if month_diff > 0:
new_month = month_diff
else:
new_month = 12 + month_diff
nb_years += 1
return date.replace(day=1, month=new_month, year=date.year - nb_years) | python | def months_ago(date, nb_months=1):
"""
Return the given `date` with `nb_months` substracted from it.
"""
nb_years = nb_months // 12
nb_months = nb_months % 12
month_diff = date.month - nb_months
if month_diff > 0:
new_month = month_diff
else:
new_month = 12 + month_diff
nb_years += 1
return date.replace(day=1, month=new_month, year=date.year - nb_years) | [
"def",
"months_ago",
"(",
"date",
",",
"nb_months",
"=",
"1",
")",
":",
"nb_years",
"=",
"nb_months",
"//",
"12",
"nb_months",
"=",
"nb_months",
"%",
"12",
"month_diff",
"=",
"date",
".",
"month",
"-",
"nb_months",
"if",
"month_diff",
">",
"0",
":",
"n... | Return the given `date` with `nb_months` substracted from it. | [
"Return",
"the",
"given",
"date",
"with",
"nb_months",
"substracted",
"from",
"it",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/utils/date.py#L34-L49 | train | 43,915 |
liip/taxi | taxi/commands/alias.py | list_ | def list_(ctx, search_string, reverse, backend, used, inactive):
"""
List configured aliases. Aliases in red belong to inactive projects and trying to push entries to these aliases
will probably result in an error.
"""
if not reverse:
list_aliases(ctx, search_string, backend, used, inactive=inactive)
else:
show_mapping(ctx, search_string, backend) | python | def list_(ctx, search_string, reverse, backend, used, inactive):
"""
List configured aliases. Aliases in red belong to inactive projects and trying to push entries to these aliases
will probably result in an error.
"""
if not reverse:
list_aliases(ctx, search_string, backend, used, inactive=inactive)
else:
show_mapping(ctx, search_string, backend) | [
"def",
"list_",
"(",
"ctx",
",",
"search_string",
",",
"reverse",
",",
"backend",
",",
"used",
",",
"inactive",
")",
":",
"if",
"not",
"reverse",
":",
"list_aliases",
"(",
"ctx",
",",
"search_string",
",",
"backend",
",",
"used",
",",
"inactive",
"=",
... | List configured aliases. Aliases in red belong to inactive projects and trying to push entries to these aliases
will probably result in an error. | [
"List",
"configured",
"aliases",
".",
"Aliases",
"in",
"red",
"belong",
"to",
"inactive",
"projects",
"and",
"trying",
"to",
"push",
"entries",
"to",
"these",
"aliases",
"will",
"probably",
"result",
"in",
"an",
"error",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/alias.py#L34-L42 | train | 43,916 |
liip/taxi | taxi/commands/alias.py | add | def add(ctx, alias, mapping, backend):
"""
Add a new alias to your configuration file.
"""
if not backend:
backends_list = ctx.obj['settings'].get_backends()
if len(backends_list) > 1:
raise click.UsageError(
"You're using more than 1 backend. Please set the backend to "
"add the alias to with the --backend option (choices are %s)" %
", ".join(dict(backends_list).keys())
)
add_mapping(ctx, alias, mapping, backend) | python | def add(ctx, alias, mapping, backend):
"""
Add a new alias to your configuration file.
"""
if not backend:
backends_list = ctx.obj['settings'].get_backends()
if len(backends_list) > 1:
raise click.UsageError(
"You're using more than 1 backend. Please set the backend to "
"add the alias to with the --backend option (choices are %s)" %
", ".join(dict(backends_list).keys())
)
add_mapping(ctx, alias, mapping, backend) | [
"def",
"add",
"(",
"ctx",
",",
"alias",
",",
"mapping",
",",
"backend",
")",
":",
"if",
"not",
"backend",
":",
"backends_list",
"=",
"ctx",
".",
"obj",
"[",
"'settings'",
"]",
".",
"get_backends",
"(",
")",
"if",
"len",
"(",
"backends_list",
")",
">"... | Add a new alias to your configuration file. | [
"Add",
"a",
"new",
"alias",
"to",
"your",
"configuration",
"file",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/alias.py#L50-L63 | train | 43,917 |
liip/taxi | taxi/settings.py | Settings.convert_to_4 | def convert_to_4(self):
"""
Convert a pre-4.0 configuration file to a 4.0 configuration file.
"""
from six.moves.urllib import parse
if not self.config.has_section('backends'):
self.config.add_section('backends')
site = parse.urlparse(self.get('site', default_value=''))
backend_uri = 'zebra://{username}:{password}@{hostname}'.format(
username=self.get('username', default_value=''),
password=parse.quote(self.get('password', default_value=''),
safe=''),
hostname=site.hostname
)
self.config.set('backends', 'default', backend_uri)
self.config.remove_option('default', 'username')
self.config.remove_option('default', 'password')
self.config.remove_option('default', 'site')
if not self.config.has_section('default_aliases'):
self.config.add_section('default_aliases')
if not self.config.has_section('default_shared_aliases'):
self.config.add_section('default_shared_aliases')
if self.config.has_section('wrmap'):
for alias, mapping in self.config.items('wrmap'):
self.config.set('default_aliases', alias, mapping)
self.config.remove_section('wrmap')
if self.config.has_section('shared_wrmap'):
for alias, mapping in self.config.items('shared_wrmap'):
self.config.set('default_shared_aliases', alias, mapping)
self.config.remove_section('shared_wrmap') | python | def convert_to_4(self):
"""
Convert a pre-4.0 configuration file to a 4.0 configuration file.
"""
from six.moves.urllib import parse
if not self.config.has_section('backends'):
self.config.add_section('backends')
site = parse.urlparse(self.get('site', default_value=''))
backend_uri = 'zebra://{username}:{password}@{hostname}'.format(
username=self.get('username', default_value=''),
password=parse.quote(self.get('password', default_value=''),
safe=''),
hostname=site.hostname
)
self.config.set('backends', 'default', backend_uri)
self.config.remove_option('default', 'username')
self.config.remove_option('default', 'password')
self.config.remove_option('default', 'site')
if not self.config.has_section('default_aliases'):
self.config.add_section('default_aliases')
if not self.config.has_section('default_shared_aliases'):
self.config.add_section('default_shared_aliases')
if self.config.has_section('wrmap'):
for alias, mapping in self.config.items('wrmap'):
self.config.set('default_aliases', alias, mapping)
self.config.remove_section('wrmap')
if self.config.has_section('shared_wrmap'):
for alias, mapping in self.config.items('shared_wrmap'):
self.config.set('default_shared_aliases', alias, mapping)
self.config.remove_section('shared_wrmap') | [
"def",
"convert_to_4",
"(",
"self",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
"import",
"parse",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"'backends'",
")",
":",
"self",
".",
"config",
".",
"add_section",
"(",
"'backends'"... | Convert a pre-4.0 configuration file to a 4.0 configuration file. | [
"Convert",
"a",
"pre",
"-",
"4",
".",
"0",
"configuration",
"file",
"to",
"a",
"4",
".",
"0",
"configuration",
"file",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/settings.py#L195-L233 | train | 43,918 |
liip/taxi | taxi/commands/autofill.py | autofill | def autofill(ctx, f):
"""
Fills your timesheet up to today, for the defined auto_fill_days.
"""
auto_fill_days = ctx.obj['settings']['auto_fill_days']
if not auto_fill_days:
ctx.obj['view'].view.err("The parameter `auto_fill_days` must be set "
"to use this command.")
return
today = datetime.date.today()
last_day = calendar.monthrange(today.year, today.month)
last_date = datetime.date(today.year, today.month, last_day[1])
timesheet_collection = get_timesheet_collection_for_context(
ctx, f
)
t = timesheet_collection.latest()
t.prefill(auto_fill_days, last_date)
t.save()
ctx.obj['view'].msg("Your entries file has been filled.") | python | def autofill(ctx, f):
"""
Fills your timesheet up to today, for the defined auto_fill_days.
"""
auto_fill_days = ctx.obj['settings']['auto_fill_days']
if not auto_fill_days:
ctx.obj['view'].view.err("The parameter `auto_fill_days` must be set "
"to use this command.")
return
today = datetime.date.today()
last_day = calendar.monthrange(today.year, today.month)
last_date = datetime.date(today.year, today.month, last_day[1])
timesheet_collection = get_timesheet_collection_for_context(
ctx, f
)
t = timesheet_collection.latest()
t.prefill(auto_fill_days, last_date)
t.save()
ctx.obj['view'].msg("Your entries file has been filled.") | [
"def",
"autofill",
"(",
"ctx",
",",
"f",
")",
":",
"auto_fill_days",
"=",
"ctx",
".",
"obj",
"[",
"'settings'",
"]",
"[",
"'auto_fill_days'",
"]",
"if",
"not",
"auto_fill_days",
":",
"ctx",
".",
"obj",
"[",
"'view'",
"]",
".",
"view",
".",
"err",
"("... | Fills your timesheet up to today, for the defined auto_fill_days. | [
"Fills",
"your",
"timesheet",
"up",
"to",
"today",
"for",
"the",
"defined",
"auto_fill_days",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/autofill.py#L15-L37 | train | 43,919 |
liip/taxi | taxi/commands/project.py | alias | def alias(ctx, search, backend):
"""
Searches for the given project and interactively add an alias for it.
"""
projects = ctx.obj['projects_db'].search(search, active_only=True)
projects = sorted(projects, key=lambda project: project.name)
if len(projects) == 0:
ctx.obj['view'].msg(
"No active project matches your search string '%s'." %
''.join(search)
)
return
ctx.obj['view'].projects_list(projects, True)
try:
number = ctx.obj['view'].select_project(projects)
except CancelException:
return
project = projects[number]
ctx.obj['view'].project_with_activities(project, numbered_activities=True)
try:
number = ctx.obj['view'].select_activity(project.activities)
except CancelException:
return
retry = True
while retry:
try:
alias = ctx.obj['view'].select_alias()
except CancelException:
return
if alias in aliases_database:
mapping = aliases_database[alias]
overwrite = ctx.obj['view'].overwrite_alias(alias, mapping)
if not overwrite:
return
elif overwrite:
retry = False
# User chose "retry"
else:
retry = True
else:
retry = False
activity = project.activities[number]
mapping = Mapping(mapping=(project.id, activity.id),
backend=project.backend)
ctx.obj['settings'].add_alias(alias, mapping)
ctx.obj['settings'].write_config()
ctx.obj['view'].alias_added(alias, (project.id, activity.id)) | python | def alias(ctx, search, backend):
"""
Searches for the given project and interactively add an alias for it.
"""
projects = ctx.obj['projects_db'].search(search, active_only=True)
projects = sorted(projects, key=lambda project: project.name)
if len(projects) == 0:
ctx.obj['view'].msg(
"No active project matches your search string '%s'." %
''.join(search)
)
return
ctx.obj['view'].projects_list(projects, True)
try:
number = ctx.obj['view'].select_project(projects)
except CancelException:
return
project = projects[number]
ctx.obj['view'].project_with_activities(project, numbered_activities=True)
try:
number = ctx.obj['view'].select_activity(project.activities)
except CancelException:
return
retry = True
while retry:
try:
alias = ctx.obj['view'].select_alias()
except CancelException:
return
if alias in aliases_database:
mapping = aliases_database[alias]
overwrite = ctx.obj['view'].overwrite_alias(alias, mapping)
if not overwrite:
return
elif overwrite:
retry = False
# User chose "retry"
else:
retry = True
else:
retry = False
activity = project.activities[number]
mapping = Mapping(mapping=(project.id, activity.id),
backend=project.backend)
ctx.obj['settings'].add_alias(alias, mapping)
ctx.obj['settings'].write_config()
ctx.obj['view'].alias_added(alias, (project.id, activity.id)) | [
"def",
"alias",
"(",
"ctx",
",",
"search",
",",
"backend",
")",
":",
"projects",
"=",
"ctx",
".",
"obj",
"[",
"'projects_db'",
"]",
".",
"search",
"(",
"search",
",",
"active_only",
"=",
"True",
")",
"projects",
"=",
"sorted",
"(",
"projects",
",",
"... | Searches for the given project and interactively add an alias for it. | [
"Searches",
"for",
"the",
"given",
"project",
"and",
"interactively",
"add",
"an",
"alias",
"for",
"it",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/project.py#L39-L95 | train | 43,920 |
liip/taxi | taxi/commands/project.py | show | def show(ctx, project_id, backend):
"""
Shows the details of the given project id.
"""
try:
project = ctx.obj['projects_db'].get(project_id, backend)
except IOError:
raise Exception("Error: the projects database file doesn't exist. "
"Please run `taxi update` to create it")
if project is None:
ctx.obj['view'].err(
"Could not find project `%s`" % (project_id)
)
else:
ctx.obj['view'].project_with_activities(project) | python | def show(ctx, project_id, backend):
"""
Shows the details of the given project id.
"""
try:
project = ctx.obj['projects_db'].get(project_id, backend)
except IOError:
raise Exception("Error: the projects database file doesn't exist. "
"Please run `taxi update` to create it")
if project is None:
ctx.obj['view'].err(
"Could not find project `%s`" % (project_id)
)
else:
ctx.obj['view'].project_with_activities(project) | [
"def",
"show",
"(",
"ctx",
",",
"project_id",
",",
"backend",
")",
":",
"try",
":",
"project",
"=",
"ctx",
".",
"obj",
"[",
"'projects_db'",
"]",
".",
"get",
"(",
"project_id",
",",
"backend",
")",
"except",
"IOError",
":",
"raise",
"Exception",
"(",
... | Shows the details of the given project id. | [
"Shows",
"the",
"details",
"of",
"the",
"given",
"project",
"id",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/project.py#L103-L118 | train | 43,921 |
liip/taxi | taxi/commands/stop.py | stop | def stop(ctx, description, f):
"""
Use it when you stop working on the current task. You can add a description
to what you've done.
"""
description = ' '.join(description)
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
current_timesheet = timesheet_collection.latest()
current_timesheet.continue_entry(
datetime.date.today(),
datetime.datetime.now().time(),
description
)
except ParseError as e:
ctx.obj['view'].err(e)
except NoActivityInProgressError as e:
ctx.obj['view'].err(e)
except StopInThePastError as e:
ctx.obj['view'].err(e)
else:
current_timesheet.save() | python | def stop(ctx, description, f):
"""
Use it when you stop working on the current task. You can add a description
to what you've done.
"""
description = ' '.join(description)
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
current_timesheet = timesheet_collection.latest()
current_timesheet.continue_entry(
datetime.date.today(),
datetime.datetime.now().time(),
description
)
except ParseError as e:
ctx.obj['view'].err(e)
except NoActivityInProgressError as e:
ctx.obj['view'].err(e)
except StopInThePastError as e:
ctx.obj['view'].err(e)
else:
current_timesheet.save() | [
"def",
"stop",
"(",
"ctx",
",",
"description",
",",
"f",
")",
":",
"description",
"=",
"' '",
".",
"join",
"(",
"description",
")",
"try",
":",
"timesheet_collection",
"=",
"get_timesheet_collection_for_context",
"(",
"ctx",
",",
"f",
")",
"current_timesheet",... | Use it when you stop working on the current task. You can add a description
to what you've done. | [
"Use",
"it",
"when",
"you",
"stop",
"working",
"on",
"the",
"current",
"task",
".",
"You",
"can",
"add",
"a",
"description",
"to",
"what",
"you",
"ve",
"done",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/stop.py#L16-L37 | train | 43,922 |
liip/taxi | taxi/commands/start.py | start | def start(ctx, alias, description, f):
"""
Use it when you start working on the given activity. This will add the
activity and the current time to your entries file. When you're finished,
use the stop command.
"""
today = datetime.date.today()
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
except ParseError as e:
ctx.obj['view'].err(e)
return
t = timesheet_collection.latest()
# If there's a previous entry on the same date, check if we can use its
# end time as a start time for the newly started entry
today_entries = t.entries.filter(date=today)
if(today in today_entries and today_entries[today]
and isinstance(today_entries[today][-1].duration, tuple)
and today_entries[today][-1].duration[1] is not None):
new_entry_start_time = today_entries[today][-1].duration[1]
else:
new_entry_start_time = datetime.datetime.now()
description = ' '.join(description) if description else '?'
duration = (new_entry_start_time, None)
e = Entry(alias, duration, description)
t.entries[today].append(e)
t.save() | python | def start(ctx, alias, description, f):
"""
Use it when you start working on the given activity. This will add the
activity and the current time to your entries file. When you're finished,
use the stop command.
"""
today = datetime.date.today()
try:
timesheet_collection = get_timesheet_collection_for_context(ctx, f)
except ParseError as e:
ctx.obj['view'].err(e)
return
t = timesheet_collection.latest()
# If there's a previous entry on the same date, check if we can use its
# end time as a start time for the newly started entry
today_entries = t.entries.filter(date=today)
if(today in today_entries and today_entries[today]
and isinstance(today_entries[today][-1].duration, tuple)
and today_entries[today][-1].duration[1] is not None):
new_entry_start_time = today_entries[today][-1].duration[1]
else:
new_entry_start_time = datetime.datetime.now()
description = ' '.join(description) if description else '?'
duration = (new_entry_start_time, None)
e = Entry(alias, duration, description)
t.entries[today].append(e)
t.save() | [
"def",
"start",
"(",
"ctx",
",",
"alias",
",",
"description",
",",
"f",
")",
":",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"try",
":",
"timesheet_collection",
"=",
"get_timesheet_collection_for_context",
"(",
"ctx",
",",
"f",
")",
"... | Use it when you start working on the given activity. This will add the
activity and the current time to your entries file. When you're finished,
use the stop command. | [
"Use",
"it",
"when",
"you",
"start",
"working",
"on",
"the",
"given",
"activity",
".",
"This",
"will",
"add",
"the",
"activity",
"and",
"the",
"current",
"time",
"to",
"your",
"entries",
"file",
".",
"When",
"you",
"re",
"finished",
"use",
"the",
"stop",... | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/start.py#L18-L49 | train | 43,923 |
liip/taxi | taxi/timesheet/parser.py | TimesheetParser.to_text | def to_text(self, line):
"""
Return the textual representation of the given `line`.
"""
return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line) | python | def to_text(self, line):
"""
Return the textual representation of the given `line`.
"""
return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line) | [
"def",
"to_text",
"(",
"self",
",",
"line",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"self",
".",
"ENTRY_TRANSFORMERS",
"[",
"line",
".",
"__class__",
"]",
")",
"(",
"line",
")"
] | Return the textual representation of the given `line`. | [
"Return",
"the",
"textual",
"representation",
"of",
"the",
"given",
"line",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/parser.py#L122-L126 | train | 43,924 |
liip/taxi | taxi/commands/update.py | update | def update(ctx):
"""
Synchronizes your project database with the server and updates the shared
aliases.
"""
ctx.obj['view'].updating_projects_database()
projects = []
for backend_name, backend_uri in ctx.obj['settings'].get_backends():
backend = plugins_registry.get_backend(backend_name)
backend_projects = backend.get_projects()
for project in backend_projects:
project.backend = backend_name
projects += backend_projects
ctx.obj['projects_db'].update(projects)
# Put the shared aliases in the config file
shared_aliases = {}
backends_to_clear = set()
for project in projects:
for alias, activity_id in six.iteritems(project.aliases):
mapping = Mapping(mapping=(project.id, activity_id),
backend=project.backend)
shared_aliases[alias] = mapping
backends_to_clear.add(project.backend)
for backend in backends_to_clear:
ctx.obj['settings'].clear_shared_aliases(backend)
# The user can have local aliases with additional information (eg. role definition). If these aliases also exist on
# the remote, then they probably need to be cleared out locally to make sure they don't unintentionally use an
# alias with a wrong role
current_aliases = ctx.obj['settings'].get_aliases()
removed_aliases = [
(alias, mapping)
for alias, mapping in current_aliases.items()
if (alias in shared_aliases and shared_aliases[alias].backend == mapping.backend
and mapping.mapping[:2] != shared_aliases[alias].mapping[:2])
]
if removed_aliases:
ctx.obj['settings'].remove_aliases(removed_aliases)
for alias, mapping in shared_aliases.items():
ctx.obj['settings'].add_shared_alias(alias, mapping)
aliases_after_update = ctx.obj['settings'].get_aliases()
ctx.obj['settings'].write_config()
ctx.obj['view'].projects_database_update_success(
aliases_after_update, ctx.obj['projects_db']
) | python | def update(ctx):
"""
Synchronizes your project database with the server and updates the shared
aliases.
"""
ctx.obj['view'].updating_projects_database()
projects = []
for backend_name, backend_uri in ctx.obj['settings'].get_backends():
backend = plugins_registry.get_backend(backend_name)
backend_projects = backend.get_projects()
for project in backend_projects:
project.backend = backend_name
projects += backend_projects
ctx.obj['projects_db'].update(projects)
# Put the shared aliases in the config file
shared_aliases = {}
backends_to_clear = set()
for project in projects:
for alias, activity_id in six.iteritems(project.aliases):
mapping = Mapping(mapping=(project.id, activity_id),
backend=project.backend)
shared_aliases[alias] = mapping
backends_to_clear.add(project.backend)
for backend in backends_to_clear:
ctx.obj['settings'].clear_shared_aliases(backend)
# The user can have local aliases with additional information (eg. role definition). If these aliases also exist on
# the remote, then they probably need to be cleared out locally to make sure they don't unintentionally use an
# alias with a wrong role
current_aliases = ctx.obj['settings'].get_aliases()
removed_aliases = [
(alias, mapping)
for alias, mapping in current_aliases.items()
if (alias in shared_aliases and shared_aliases[alias].backend == mapping.backend
and mapping.mapping[:2] != shared_aliases[alias].mapping[:2])
]
if removed_aliases:
ctx.obj['settings'].remove_aliases(removed_aliases)
for alias, mapping in shared_aliases.items():
ctx.obj['settings'].add_shared_alias(alias, mapping)
aliases_after_update = ctx.obj['settings'].get_aliases()
ctx.obj['settings'].write_config()
ctx.obj['view'].projects_database_update_success(
aliases_after_update, ctx.obj['projects_db']
) | [
"def",
"update",
"(",
"ctx",
")",
":",
"ctx",
".",
"obj",
"[",
"'view'",
"]",
".",
"updating_projects_database",
"(",
")",
"projects",
"=",
"[",
"]",
"for",
"backend_name",
",",
"backend_uri",
"in",
"ctx",
".",
"obj",
"[",
"'settings'",
"]",
".",
"get_... | Synchronizes your project database with the server and updates the shared
aliases. | [
"Synchronizes",
"your",
"project",
"database",
"with",
"the",
"server",
"and",
"updates",
"the",
"shared",
"aliases",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/commands/update.py#L13-L69 | train | 43,925 |
sebriois/biomart | biomart/dataset.py | BiomartDataset.attributes | def attributes(self):
"""
A dictionary mapping names of attributes to BiomartAttribute instances.
This causes overwriting errors if there are diffferent pages which use
the same attribute names, but is kept for backward compatibility.
"""
if not self._attribute_pages:
self.fetch_attributes()
result = {}
for page in self._attribute_pages.values():
result.update(page.attributes)
return result | python | def attributes(self):
"""
A dictionary mapping names of attributes to BiomartAttribute instances.
This causes overwriting errors if there are diffferent pages which use
the same attribute names, but is kept for backward compatibility.
"""
if not self._attribute_pages:
self.fetch_attributes()
result = {}
for page in self._attribute_pages.values():
result.update(page.attributes)
return result | [
"def",
"attributes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_attribute_pages",
":",
"self",
".",
"fetch_attributes",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"page",
"in",
"self",
".",
"_attribute_pages",
".",
"values",
"(",
")",
":",
"resu... | A dictionary mapping names of attributes to BiomartAttribute instances.
This causes overwriting errors if there are diffferent pages which use
the same attribute names, but is kept for backward compatibility. | [
"A",
"dictionary",
"mapping",
"names",
"of",
"attributes",
"to",
"BiomartAttribute",
"instances",
"."
] | 96d16abba314d8752d7014ee5f4761a0ad763fdf | https://github.com/sebriois/biomart/blob/96d16abba314d8752d7014ee5f4761a0ad763fdf/biomart/dataset.py#L34-L46 | train | 43,926 |
liip/taxi | taxi/plugins.py | PluginsRegistry.get_backends_by_class | def get_backends_by_class(self, backend_class):
"""
Return a list of backends that are instances of the given `backend_class`.
"""
return [backend for backend in self._backends_registry.values() if isinstance(backend, backend_class)] | python | def get_backends_by_class(self, backend_class):
"""
Return a list of backends that are instances of the given `backend_class`.
"""
return [backend for backend in self._backends_registry.values() if isinstance(backend, backend_class)] | [
"def",
"get_backends_by_class",
"(",
"self",
",",
"backend_class",
")",
":",
"return",
"[",
"backend",
"for",
"backend",
"in",
"self",
".",
"_backends_registry",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"backend",
",",
"backend_class",
")",
"]"
] | Return a list of backends that are instances of the given `backend_class`. | [
"Return",
"a",
"list",
"of",
"backends",
"that",
"are",
"instances",
"of",
"the",
"given",
"backend_class",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/plugins.py#L68-L72 | train | 43,927 |
liip/taxi | taxi/plugins.py | PluginsRegistry._load_backend | def _load_backend(self, backend_uri, context):
"""
Return the instantiated backend object identified by the given
`backend_uri`.
The entry point that is used to create the backend object is determined
by the protocol part of the given URI.
"""
parsed = parse.urlparse(backend_uri)
options = dict(parse.parse_qsl(parsed.query))
try:
backend = self._entry_points[self.BACKENDS_ENTRY_POINT][parsed.scheme].load()
except KeyError:
raise BackendNotFoundError(
"The requested backend `%s` could not be found in the "
"registered entry points. Perhaps you forgot to install the "
"corresponding backend package?" % parsed.scheme
)
password = (parse.unquote(parsed.password)
if parsed.password
else parsed.password)
return backend(
username=parsed.username, password=password,
hostname=parsed.hostname, port=parsed.port,
path=parsed.path, options=options, context=context,
) | python | def _load_backend(self, backend_uri, context):
"""
Return the instantiated backend object identified by the given
`backend_uri`.
The entry point that is used to create the backend object is determined
by the protocol part of the given URI.
"""
parsed = parse.urlparse(backend_uri)
options = dict(parse.parse_qsl(parsed.query))
try:
backend = self._entry_points[self.BACKENDS_ENTRY_POINT][parsed.scheme].load()
except KeyError:
raise BackendNotFoundError(
"The requested backend `%s` could not be found in the "
"registered entry points. Perhaps you forgot to install the "
"corresponding backend package?" % parsed.scheme
)
password = (parse.unquote(parsed.password)
if parsed.password
else parsed.password)
return backend(
username=parsed.username, password=password,
hostname=parsed.hostname, port=parsed.port,
path=parsed.path, options=options, context=context,
) | [
"def",
"_load_backend",
"(",
"self",
",",
"backend_uri",
",",
"context",
")",
":",
"parsed",
"=",
"parse",
".",
"urlparse",
"(",
"backend_uri",
")",
"options",
"=",
"dict",
"(",
"parse",
".",
"parse_qsl",
"(",
"parsed",
".",
"query",
")",
")",
"try",
"... | Return the instantiated backend object identified by the given
`backend_uri`.
The entry point that is used to create the backend object is determined
by the protocol part of the given URI. | [
"Return",
"the",
"instantiated",
"backend",
"object",
"identified",
"by",
"the",
"given",
"backend_uri",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/plugins.py#L86-L114 | train | 43,928 |
liip/taxi | taxi/plugins.py | PluginsRegistry.register_commands | def register_commands(self):
"""
Load entry points for custom commands.
"""
for command in self._entry_points[self.COMMANDS_ENTRY_POINT].values():
command.load() | python | def register_commands(self):
"""
Load entry points for custom commands.
"""
for command in self._entry_points[self.COMMANDS_ENTRY_POINT].values():
command.load() | [
"def",
"register_commands",
"(",
"self",
")",
":",
"for",
"command",
"in",
"self",
".",
"_entry_points",
"[",
"self",
".",
"COMMANDS_ENTRY_POINT",
"]",
".",
"values",
"(",
")",
":",
"command",
".",
"load",
"(",
")"
] | Load entry points for custom commands. | [
"Load",
"entry",
"points",
"for",
"custom",
"commands",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/plugins.py#L116-L121 | train | 43,929 |
liip/taxi | taxi/timesheet/flags.py | FlaggableMixin._add_or_remove_flag | def _add_or_remove_flag(self, flag, add):
"""
Add the given `flag` if `add` is True, remove it otherwise.
"""
meth = self.add_flag if add else self.remove_flag
meth(flag) | python | def _add_or_remove_flag(self, flag, add):
"""
Add the given `flag` if `add` is True, remove it otherwise.
"""
meth = self.add_flag if add else self.remove_flag
meth(flag) | [
"def",
"_add_or_remove_flag",
"(",
"self",
",",
"flag",
",",
"add",
")",
":",
"meth",
"=",
"self",
".",
"add_flag",
"if",
"add",
"else",
"self",
".",
"remove_flag",
"meth",
"(",
"flag",
")"
] | Add the given `flag` if `add` is True, remove it otherwise. | [
"Add",
"the",
"given",
"flag",
"if",
"add",
"is",
"True",
"remove",
"it",
"otherwise",
"."
] | 269423c1f1ab571bd01a522819afe3e325bfbff6 | https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/timesheet/flags.py#L33-L38 | train | 43,930 |
IBMStreams/pypi.streamsx | streamsx/ec.py | get_application_configuration | def get_application_configuration(name):
"""Get a named application configuration.
An application configuration is a named set of securely stored properties
where each key and its value in the property set is a string.
An application configuration object is used to store information that
IBM Streams applications require, such as:
* Database connection data
* Credentials that your applications need to use to access external systems
* Other data, such as the port numbers or URLs of external systems
Arguments:
name(str): Name of the application configuration.
Returns:
dict: Dictionary containing the property names and values for the application configuration.
Raises:
ValueError: Application configuration does not exist.
"""
_check()
rc = _ec.get_application_configuration(name)
if rc is False:
raise ValueError("Application configuration {0} not found.".format(name))
return rc | python | def get_application_configuration(name):
"""Get a named application configuration.
An application configuration is a named set of securely stored properties
where each key and its value in the property set is a string.
An application configuration object is used to store information that
IBM Streams applications require, such as:
* Database connection data
* Credentials that your applications need to use to access external systems
* Other data, such as the port numbers or URLs of external systems
Arguments:
name(str): Name of the application configuration.
Returns:
dict: Dictionary containing the property names and values for the application configuration.
Raises:
ValueError: Application configuration does not exist.
"""
_check()
rc = _ec.get_application_configuration(name)
if rc is False:
raise ValueError("Application configuration {0} not found.".format(name))
return rc | [
"def",
"get_application_configuration",
"(",
"name",
")",
":",
"_check",
"(",
")",
"rc",
"=",
"_ec",
".",
"get_application_configuration",
"(",
"name",
")",
"if",
"rc",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"\"Application configuration {0} not found.\"",
... | Get a named application configuration.
An application configuration is a named set of securely stored properties
where each key and its value in the property set is a string.
An application configuration object is used to store information that
IBM Streams applications require, such as:
* Database connection data
* Credentials that your applications need to use to access external systems
* Other data, such as the port numbers or URLs of external systems
Arguments:
name(str): Name of the application configuration.
Returns:
dict: Dictionary containing the property names and values for the application configuration.
Raises:
ValueError: Application configuration does not exist. | [
"Get",
"a",
"named",
"application",
"configuration",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/ec.py#L238-L264 | train | 43,931 |
IBMStreams/pypi.streamsx | streamsx/ec.py | _submit | def _submit(primitive, port_index, tuple_):
"""Internal method to submit a tuple"""
args = (_get_opc(primitive), port_index, tuple_)
_ec._submit(args) | python | def _submit(primitive, port_index, tuple_):
"""Internal method to submit a tuple"""
args = (_get_opc(primitive), port_index, tuple_)
_ec._submit(args) | [
"def",
"_submit",
"(",
"primitive",
",",
"port_index",
",",
"tuple_",
")",
":",
"args",
"=",
"(",
"_get_opc",
"(",
"primitive",
")",
",",
"port_index",
",",
"tuple_",
")",
"_ec",
".",
"_submit",
"(",
"args",
")"
] | Internal method to submit a tuple | [
"Internal",
"method",
"to",
"submit",
"a",
"tuple"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/ec.py#L489-L492 | train | 43,932 |
IBMStreams/pypi.streamsx | streamsx/ec.py | CustomMetric.value | def value(self, value):
"""
Set the current value of the metric.
"""
args = (self.__ptr, int(value))
_ec.metric_set(args) | python | def value(self, value):
"""
Set the current value of the metric.
"""
args = (self.__ptr, int(value))
_ec.metric_set(args) | [
"def",
"value",
"(",
"self",
",",
"value",
")",
":",
"args",
"=",
"(",
"self",
".",
"__ptr",
",",
"int",
"(",
"value",
")",
")",
"_ec",
".",
"metric_set",
"(",
"args",
")"
] | Set the current value of the metric. | [
"Set",
"the",
"current",
"value",
"of",
"the",
"metric",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/ec.py#L444-L449 | train | 43,933 |
IBMStreams/pypi.streamsx | streamsx/_streams/_placement.py | _Placement.resource_tags | def resource_tags(self):
"""Resource tags for this processing logic.
Tags are a mechanism for differentiating and identifying resources that have different physical characteristics or logical uses. For example a resource (host) that has external connectivity for public data sources may be tagged `ingest`.
Processing logic can be associated with one or more tags to require
running on suitably tagged resources. For example
adding tags `ingest` and `db` requires that the processing element
containing the callable that created the stream runs on a host
tagged with both `ingest` and `db`.
A :py:class:`~streamsx.topology.topology.Stream` that was not created directly with a Python callable
cannot have tags associated with it. For example a stream that
is a :py:meth:`~streamsx.topology.topology.Stream.union` of multiple streams cannot be tagged.
In this case this method returns an empty `frozenset` which
cannot be modified.
See https://www.ibm.com/support/knowledgecenter/en/SSCRJU_4.2.1/com.ibm.streams.admin.doc/doc/tags.html for more details of tags within IBM Streams.
Returns:
set: Set of resource tags, initially empty.
.. warning:: If no resources exist with the required tags then job submission will fail.
.. versionadded:: 1.7
.. versionadded:: 1.9 Support for :py:class:`Sink` and :py:class:`~streamsx.spl.op.Invoke`.
"""
try:
plc = self._op()._placement
if not 'resourceTags' in plc:
plc['resourceTags'] = set()
return plc['resourceTags']
except TypeError:
return frozenset() | python | def resource_tags(self):
"""Resource tags for this processing logic.
Tags are a mechanism for differentiating and identifying resources that have different physical characteristics or logical uses. For example a resource (host) that has external connectivity for public data sources may be tagged `ingest`.
Processing logic can be associated with one or more tags to require
running on suitably tagged resources. For example
adding tags `ingest` and `db` requires that the processing element
containing the callable that created the stream runs on a host
tagged with both `ingest` and `db`.
A :py:class:`~streamsx.topology.topology.Stream` that was not created directly with a Python callable
cannot have tags associated with it. For example a stream that
is a :py:meth:`~streamsx.topology.topology.Stream.union` of multiple streams cannot be tagged.
In this case this method returns an empty `frozenset` which
cannot be modified.
See https://www.ibm.com/support/knowledgecenter/en/SSCRJU_4.2.1/com.ibm.streams.admin.doc/doc/tags.html for more details of tags within IBM Streams.
Returns:
set: Set of resource tags, initially empty.
.. warning:: If no resources exist with the required tags then job submission will fail.
.. versionadded:: 1.7
.. versionadded:: 1.9 Support for :py:class:`Sink` and :py:class:`~streamsx.spl.op.Invoke`.
"""
try:
plc = self._op()._placement
if not 'resourceTags' in plc:
plc['resourceTags'] = set()
return plc['resourceTags']
except TypeError:
return frozenset() | [
"def",
"resource_tags",
"(",
"self",
")",
":",
"try",
":",
"plc",
"=",
"self",
".",
"_op",
"(",
")",
".",
"_placement",
"if",
"not",
"'resourceTags'",
"in",
"plc",
":",
"plc",
"[",
"'resourceTags'",
"]",
"=",
"set",
"(",
")",
"return",
"plc",
"[",
... | Resource tags for this processing logic.
Tags are a mechanism for differentiating and identifying resources that have different physical characteristics or logical uses. For example a resource (host) that has external connectivity for public data sources may be tagged `ingest`.
Processing logic can be associated with one or more tags to require
running on suitably tagged resources. For example
adding tags `ingest` and `db` requires that the processing element
containing the callable that created the stream runs on a host
tagged with both `ingest` and `db`.
A :py:class:`~streamsx.topology.topology.Stream` that was not created directly with a Python callable
cannot have tags associated with it. For example a stream that
is a :py:meth:`~streamsx.topology.topology.Stream.union` of multiple streams cannot be tagged.
In this case this method returns an empty `frozenset` which
cannot be modified.
See https://www.ibm.com/support/knowledgecenter/en/SSCRJU_4.2.1/com.ibm.streams.admin.doc/doc/tags.html for more details of tags within IBM Streams.
Returns:
set: Set of resource tags, initially empty.
.. warning:: If no resources exist with the required tags then job submission will fail.
.. versionadded:: 1.7
.. versionadded:: 1.9 Support for :py:class:`Sink` and :py:class:`~streamsx.spl.op.Invoke`. | [
"Resource",
"tags",
"for",
"this",
"processing",
"logic",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/_streams/_placement.py#L41-L75 | train | 43,934 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | _vcap_from_service_definition | def _vcap_from_service_definition(service_def):
"""Turn a service definition into a vcap services
containing a single service.
"""
if 'credentials' in service_def:
credentials = service_def['credentials']
else:
credentials = service_def
service = {}
service['credentials'] = credentials
service['name'] = _name_from_service_definition(service_def)
vcap = {'streaming-analytics': [service]}
return vcap | python | def _vcap_from_service_definition(service_def):
"""Turn a service definition into a vcap services
containing a single service.
"""
if 'credentials' in service_def:
credentials = service_def['credentials']
else:
credentials = service_def
service = {}
service['credentials'] = credentials
service['name'] = _name_from_service_definition(service_def)
vcap = {'streaming-analytics': [service]}
return vcap | [
"def",
"_vcap_from_service_definition",
"(",
"service_def",
")",
":",
"if",
"'credentials'",
"in",
"service_def",
":",
"credentials",
"=",
"service_def",
"[",
"'credentials'",
"]",
"else",
":",
"credentials",
"=",
"service_def",
"service",
"=",
"{",
"}",
"service"... | Turn a service definition into a vcap services
containing a single service. | [
"Turn",
"a",
"service",
"definition",
"into",
"a",
"vcap",
"services",
"containing",
"a",
"single",
"service",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L1341-L1354 | train | 43,935 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | _StreamingAnalyticsSubmitter._get_java_env | def _get_java_env(self):
"Pass the VCAP through the environment to the java submission"
env = super(_StreamingAnalyticsSubmitter, self)._get_java_env()
vcap = streamsx.rest._get_vcap_services(self._vcap_services)
env['VCAP_SERVICES'] = json.dumps(vcap)
return env | python | def _get_java_env(self):
"Pass the VCAP through the environment to the java submission"
env = super(_StreamingAnalyticsSubmitter, self)._get_java_env()
vcap = streamsx.rest._get_vcap_services(self._vcap_services)
env['VCAP_SERVICES'] = json.dumps(vcap)
return env | [
"def",
"_get_java_env",
"(",
"self",
")",
":",
"env",
"=",
"super",
"(",
"_StreamingAnalyticsSubmitter",
",",
"self",
")",
".",
"_get_java_env",
"(",
")",
"vcap",
"=",
"streamsx",
".",
"rest",
".",
"_get_vcap_services",
"(",
"self",
".",
"_vcap_services",
")... | Pass the VCAP through the environment to the java submission | [
"Pass",
"the",
"VCAP",
"through",
"the",
"environment",
"to",
"the",
"java",
"submission"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L409-L414 | train | 43,936 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | _DistributedSubmitter._get_java_env | def _get_java_env(self):
"Set env vars from connection if set"
env = super(_DistributedSubmitter, self)._get_java_env()
if self._streams_connection is not None:
# Need to sure the environment matches the connection.
sc = self._streams_connection
if isinstance(sc._delegator, streamsx.rest_primitives._StreamsRestDelegator):
env.pop('STREAMS_DOMAIN_ID', None)
env.pop('STREAMS_INSTANCE_ID', None)
else:
env['STREAMS_DOMAIN_ID'] = sc.get_domains()[0].id
if not ConfigParams.SERVICE_DEFINITION in self._config():
env['STREAMS_REST_URL'] = sc.resource_url
env['STREAMS_USERNAME'] = sc.session.auth[0]
env['STREAMS_PASSWORD'] = sc.session.auth[1]
return env | python | def _get_java_env(self):
"Set env vars from connection if set"
env = super(_DistributedSubmitter, self)._get_java_env()
if self._streams_connection is not None:
# Need to sure the environment matches the connection.
sc = self._streams_connection
if isinstance(sc._delegator, streamsx.rest_primitives._StreamsRestDelegator):
env.pop('STREAMS_DOMAIN_ID', None)
env.pop('STREAMS_INSTANCE_ID', None)
else:
env['STREAMS_DOMAIN_ID'] = sc.get_domains()[0].id
if not ConfigParams.SERVICE_DEFINITION in self._config():
env['STREAMS_REST_URL'] = sc.resource_url
env['STREAMS_USERNAME'] = sc.session.auth[0]
env['STREAMS_PASSWORD'] = sc.session.auth[1]
return env | [
"def",
"_get_java_env",
"(",
"self",
")",
":",
"env",
"=",
"super",
"(",
"_DistributedSubmitter",
",",
"self",
")",
".",
"_get_java_env",
"(",
")",
"if",
"self",
".",
"_streams_connection",
"is",
"not",
"None",
":",
"# Need to sure the environment matches the conn... | Set env vars from connection if set | [
"Set",
"env",
"vars",
"from",
"connection",
"if",
"set"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L485-L500 | train | 43,937 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | JobConfig.from_overlays | def from_overlays(overlays):
"""Create a `JobConfig` instance from a full job configuration
overlays object.
All logical items, such as ``comment`` and ``job_name``, are
extracted from `overlays`. The remaining information in the
single job config overlay in ``overlays`` is set as ``raw_overlay``.
Args:
overlays(dict): Full job configuration overlays object.
Returns:
JobConfig: Instance representing logical view of `overlays`.
.. versionadded:: 1.9
"""
jc = JobConfig()
jc.comment = overlays.get('comment')
if 'jobConfigOverlays' in overlays:
if len(overlays['jobConfigOverlays']) >= 1:
jco = copy.deepcopy(overlays['jobConfigOverlays'][0])
# Now extract the logical information
if 'jobConfig' in jco:
_jc = jco['jobConfig']
jc.job_name = _jc.pop('jobName', None)
jc.job_group = _jc.pop('jobGroup', None)
jc.preload = _jc.pop('preloadApplicationBundles', False)
jc.data_directory = _jc.pop('dataDirectory', None)
jc.tracing = _jc.pop('tracing', None)
for sp in _jc.pop('submissionParameters', []):
jc.submission_parameters[sp['name']] = sp['value']
if not _jc:
del jco['jobConfig']
if 'deploymentConfig' in jco:
_dc = jco['deploymentConfig']
if 'manual' == _dc.get('fusionScheme'):
if 'fusionTargetPeCount' in _dc:
jc.target_pe_count = _dc.pop('fusionTargetPeCount')
if len(_dc) == 1:
del jco['deploymentConfig']
if jco:
jc.raw_overlay = jco
return jc | python | def from_overlays(overlays):
"""Create a `JobConfig` instance from a full job configuration
overlays object.
All logical items, such as ``comment`` and ``job_name``, are
extracted from `overlays`. The remaining information in the
single job config overlay in ``overlays`` is set as ``raw_overlay``.
Args:
overlays(dict): Full job configuration overlays object.
Returns:
JobConfig: Instance representing logical view of `overlays`.
.. versionadded:: 1.9
"""
jc = JobConfig()
jc.comment = overlays.get('comment')
if 'jobConfigOverlays' in overlays:
if len(overlays['jobConfigOverlays']) >= 1:
jco = copy.deepcopy(overlays['jobConfigOverlays'][0])
# Now extract the logical information
if 'jobConfig' in jco:
_jc = jco['jobConfig']
jc.job_name = _jc.pop('jobName', None)
jc.job_group = _jc.pop('jobGroup', None)
jc.preload = _jc.pop('preloadApplicationBundles', False)
jc.data_directory = _jc.pop('dataDirectory', None)
jc.tracing = _jc.pop('tracing', None)
for sp in _jc.pop('submissionParameters', []):
jc.submission_parameters[sp['name']] = sp['value']
if not _jc:
del jco['jobConfig']
if 'deploymentConfig' in jco:
_dc = jco['deploymentConfig']
if 'manual' == _dc.get('fusionScheme'):
if 'fusionTargetPeCount' in _dc:
jc.target_pe_count = _dc.pop('fusionTargetPeCount')
if len(_dc) == 1:
del jco['deploymentConfig']
if jco:
jc.raw_overlay = jco
return jc | [
"def",
"from_overlays",
"(",
"overlays",
")",
":",
"jc",
"=",
"JobConfig",
"(",
")",
"jc",
".",
"comment",
"=",
"overlays",
".",
"get",
"(",
"'comment'",
")",
"if",
"'jobConfigOverlays'",
"in",
"overlays",
":",
"if",
"len",
"(",
"overlays",
"[",
"'jobCon... | Create a `JobConfig` instance from a full job configuration
overlays object.
All logical items, such as ``comment`` and ``job_name``, are
extracted from `overlays`. The remaining information in the
single job config overlay in ``overlays`` is set as ``raw_overlay``.
Args:
overlays(dict): Full job configuration overlays object.
Returns:
JobConfig: Instance representing logical view of `overlays`.
.. versionadded:: 1.9 | [
"Create",
"a",
"JobConfig",
"instance",
"from",
"a",
"full",
"job",
"configuration",
"overlays",
"object",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L946-L992 | train | 43,938 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | JobConfig._add_overlays | def _add_overlays(self, config):
"""
Add this as a jobConfigOverlays JSON to config.
"""
if self._comment:
config['comment'] = self._comment
jco = {}
config["jobConfigOverlays"] = [jco]
if self._raw_overlay:
jco.update(self._raw_overlay)
jc = jco.get('jobConfig', {})
if self.job_name is not None:
jc["jobName"] = self.job_name
if self.job_group is not None:
jc["jobGroup"] = self.job_group
if self.data_directory is not None:
jc["dataDirectory"] = self.data_directory
if self.preload:
jc['preloadApplicationBundles'] = True
if self.tracing is not None:
jc['tracing'] = self.tracing
if self.submission_parameters:
sp = jc.get('submissionParameters', [])
for name in self.submission_parameters:
sp.append({'name': str(name), 'value': self.submission_parameters[name]})
jc['submissionParameters'] = sp
if jc:
jco["jobConfig"] = jc
if self.target_pe_count is not None and self.target_pe_count >= 1:
deployment = jco.get('deploymentConfig', {})
deployment.update({'fusionScheme' : 'manual', 'fusionTargetPeCount' : self.target_pe_count})
jco["deploymentConfig"] = deployment
return config | python | def _add_overlays(self, config):
"""
Add this as a jobConfigOverlays JSON to config.
"""
if self._comment:
config['comment'] = self._comment
jco = {}
config["jobConfigOverlays"] = [jco]
if self._raw_overlay:
jco.update(self._raw_overlay)
jc = jco.get('jobConfig', {})
if self.job_name is not None:
jc["jobName"] = self.job_name
if self.job_group is not None:
jc["jobGroup"] = self.job_group
if self.data_directory is not None:
jc["dataDirectory"] = self.data_directory
if self.preload:
jc['preloadApplicationBundles'] = True
if self.tracing is not None:
jc['tracing'] = self.tracing
if self.submission_parameters:
sp = jc.get('submissionParameters', [])
for name in self.submission_parameters:
sp.append({'name': str(name), 'value': self.submission_parameters[name]})
jc['submissionParameters'] = sp
if jc:
jco["jobConfig"] = jc
if self.target_pe_count is not None and self.target_pe_count >= 1:
deployment = jco.get('deploymentConfig', {})
deployment.update({'fusionScheme' : 'manual', 'fusionTargetPeCount' : self.target_pe_count})
jco["deploymentConfig"] = deployment
return config | [
"def",
"_add_overlays",
"(",
"self",
",",
"config",
")",
":",
"if",
"self",
".",
"_comment",
":",
"config",
"[",
"'comment'",
"]",
"=",
"self",
".",
"_comment",
"jco",
"=",
"{",
"}",
"config",
"[",
"\"jobConfigOverlays\"",
"]",
"=",
"[",
"jco",
"]",
... | Add this as a jobConfigOverlays JSON to config. | [
"Add",
"this",
"as",
"a",
"jobConfigOverlays",
"JSON",
"to",
"config",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L1191-L1230 | train | 43,939 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | SubmissionResult.job | def job(self):
"""REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.
"""
if self._submitter and hasattr(self._submitter, '_job_access'):
return self._submitter._job_access()
return None | python | def job(self):
"""REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.
"""
if self._submitter and hasattr(self._submitter, '_job_access'):
return self._submitter._job_access()
return None | [
"def",
"job",
"(",
"self",
")",
":",
"if",
"self",
".",
"_submitter",
"and",
"hasattr",
"(",
"self",
".",
"_submitter",
",",
"'_job_access'",
")",
":",
"return",
"self",
".",
"_submitter",
".",
"_job_access",
"(",
")",
"return",
"None"
] | REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted. | [
"REST",
"binding",
"for",
"the",
"job",
"associated",
"with",
"the",
"submitted",
"build",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L1241-L1249 | train | 43,940 |
IBMStreams/pypi.streamsx | streamsx/topology/context.py | SubmissionResult.cancel_job_button | def cancel_job_button(self, description=None):
"""Display a button that will cancel the submitted job.
Used in a Jupyter IPython notebook to provide an interactive
mechanism to cancel a job submitted from the notebook.
Once clicked the button is disabled unless the cancel fails.
A job may be cancelled directly using::
submission_result = submit(ctx_type, topology, config)
submission_result.job.cancel()
Args:
description(str): Text used as the button description, defaults to value based upon the job name.
.. warning::
Behavior when called outside a notebook is undefined.
.. versionadded:: 1.12
"""
if not hasattr(self, 'jobId'):
return
try:
import ipywidgets as widgets
if not description:
description = 'Cancel job: '
description += self.name if hasattr(self, 'name') else self.job.name
button = widgets.Button(description=description,
button_style='danger',
layout=widgets.Layout(width='40%'))
out = widgets.Output()
vb = widgets.VBox([button, out])
@out.capture(clear_output=True)
def _cancel_job_click(b):
b.disabled=True
print('Cancelling job: id=' + str(self.job.id) + ' ...\n', flush=True)
try:
rc = self.job.cancel()
out.clear_output()
if rc:
print('Cancelled job: id=' + str(self.job.id) + ' : ' + self.job.name + '\n', flush=True)
else:
print('Job already cancelled: id=' + str(self.job.id) + ' : ' + self.job.name + '\n', flush=True)
except:
b.disabled=False
out.clear_output()
raise
button.on_click(_cancel_job_click)
display(vb)
except:
pass | python | def cancel_job_button(self, description=None):
"""Display a button that will cancel the submitted job.
Used in a Jupyter IPython notebook to provide an interactive
mechanism to cancel a job submitted from the notebook.
Once clicked the button is disabled unless the cancel fails.
A job may be cancelled directly using::
submission_result = submit(ctx_type, topology, config)
submission_result.job.cancel()
Args:
description(str): Text used as the button description, defaults to value based upon the job name.
.. warning::
Behavior when called outside a notebook is undefined.
.. versionadded:: 1.12
"""
if not hasattr(self, 'jobId'):
return
try:
import ipywidgets as widgets
if not description:
description = 'Cancel job: '
description += self.name if hasattr(self, 'name') else self.job.name
button = widgets.Button(description=description,
button_style='danger',
layout=widgets.Layout(width='40%'))
out = widgets.Output()
vb = widgets.VBox([button, out])
@out.capture(clear_output=True)
def _cancel_job_click(b):
b.disabled=True
print('Cancelling job: id=' + str(self.job.id) + ' ...\n', flush=True)
try:
rc = self.job.cancel()
out.clear_output()
if rc:
print('Cancelled job: id=' + str(self.job.id) + ' : ' + self.job.name + '\n', flush=True)
else:
print('Job already cancelled: id=' + str(self.job.id) + ' : ' + self.job.name + '\n', flush=True)
except:
b.disabled=False
out.clear_output()
raise
button.on_click(_cancel_job_click)
display(vb)
except:
pass | [
"def",
"cancel_job_button",
"(",
"self",
",",
"description",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'jobId'",
")",
":",
"return",
"try",
":",
"import",
"ipywidgets",
"as",
"widgets",
"if",
"not",
"description",
":",
"description"... | Display a button that will cancel the submitted job.
Used in a Jupyter IPython notebook to provide an interactive
mechanism to cancel a job submitted from the notebook.
Once clicked the button is disabled unless the cancel fails.
A job may be cancelled directly using::
submission_result = submit(ctx_type, topology, config)
submission_result.job.cancel()
Args:
description(str): Text used as the button description, defaults to value based upon the job name.
.. warning::
Behavior when called outside a notebook is undefined.
.. versionadded:: 1.12 | [
"Display",
"a",
"button",
"that",
"will",
"cancel",
"the",
"submitted",
"job",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/context.py#L1251-L1305 | train | 43,941 |
raphaelm/django-hierarkey | hierarkey/models.py | Hierarkey.add_default | def add_default(self, key: str, value: Optional[str], default_type: type = str) -> None:
"""
Adds a default value and a default type for a key.
:param key: Key
:param value: *Serialized* default value, i.e. a string or ``None``.
:param default_type: The type to unserialize values for this key to, defaults to ``str``.
"""
self.defaults[key] = HierarkeyDefault(value, default_type) | python | def add_default(self, key: str, value: Optional[str], default_type: type = str) -> None:
"""
Adds a default value and a default type for a key.
:param key: Key
:param value: *Serialized* default value, i.e. a string or ``None``.
:param default_type: The type to unserialize values for this key to, defaults to ``str``.
"""
self.defaults[key] = HierarkeyDefault(value, default_type) | [
"def",
"add_default",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"Optional",
"[",
"str",
"]",
",",
"default_type",
":",
"type",
"=",
"str",
")",
"->",
"None",
":",
"self",
".",
"defaults",
"[",
"key",
"]",
"=",
"HierarkeyDefault",
"(",
... | Adds a default value and a default type for a key.
:param key: Key
:param value: *Serialized* default value, i.e. a string or ``None``.
:param default_type: The type to unserialize values for this key to, defaults to ``str``. | [
"Adds",
"a",
"default",
"value",
"and",
"a",
"default",
"type",
"for",
"a",
"key",
"."
] | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/models.py#L49-L57 | train | 43,942 |
raphaelm/django-hierarkey | hierarkey/models.py | Hierarkey.add_type | def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None:
"""
Adds serialization support for a new type.
:param type: The type to add support for.
:param serialize: A callable that takes an object of type ``type`` and returns a string.
:param unserialize: A callable that takes a string and returns an object of type ``type``.
"""
self.types.append(HierarkeyType(type=type, serialize=serialize, unserialize=unserialize)) | python | def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None:
"""
Adds serialization support for a new type.
:param type: The type to add support for.
:param serialize: A callable that takes an object of type ``type`` and returns a string.
:param unserialize: A callable that takes a string and returns an object of type ``type``.
"""
self.types.append(HierarkeyType(type=type, serialize=serialize, unserialize=unserialize)) | [
"def",
"add_type",
"(",
"self",
",",
"type",
":",
"type",
",",
"serialize",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"str",
"]",
",",
"unserialize",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"Any",
"]",
")",
"->",
"None",
":",
"self",
".",
... | Adds serialization support for a new type.
:param type: The type to add support for.
:param serialize: A callable that takes an object of type ``type`` and returns a string.
:param unserialize: A callable that takes a string and returns an object of type ``type``. | [
"Adds",
"serialization",
"support",
"for",
"a",
"new",
"type",
"."
] | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/models.py#L59-L67 | train | 43,943 |
raphaelm/django-hierarkey | hierarkey/models.py | Hierarkey.set_global | def set_global(self, cache_namespace: str = None) -> type:
"""
Decorator. Attaches the global key-value store of this hierarchy to an object.
:param cache_namespace: Optional. A custom namespace used for caching. By default this is
constructed from the name of the class this is applied to and
the ``attribute_name`` of this ``Hierarkey`` object.
"""
if isinstance(cache_namespace, type):
raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add_global() '
'instead of .add_global')
def wrapper(wrapped_class):
if issubclass(wrapped_class, models.Model):
raise ImproperlyConfigured('Hierarkey.add_global() can only be invoked on a normal class, '
'not on a Django model.')
if not issubclass(wrapped_class, GlobalSettingsBase):
raise ImproperlyConfigured('You should use .add_global() on a class that inherits from '
'GlobalSettingsBase.')
_cache_namespace = cache_namespace or ('%s_%s' % (wrapped_class.__name__, self.attribute_name))
attrs = self._create_attrs(wrapped_class)
model_name = '%s_%sStore' % (wrapped_class.__name__, self.attribute_name.title())
if getattr(sys.modules[wrapped_class.__module__], model_name, None):
# Already wrapped
return wrapped_class
kv_model = self._create_model(model_name, attrs)
def init(self, *args, object=None, **kwargs):
super(kv_model, self).__init__(*args, **kwargs)
setattr(kv_model, '__init__', init)
hierarkey = self
def prop(iself):
from .proxy import HierarkeyProxy
attrname = '_hierarkey_proxy_{}_{}'.format(_cache_namespace, self.attribute_name)
cached = getattr(iself, attrname, None)
if not cached:
cached = HierarkeyProxy._new(iself, type=kv_model, hierarkey=hierarkey,
cache_namespace=_cache_namespace)
setattr(iself, attrname, cached)
return cached
setattr(sys.modules[wrapped_class.__module__], model_name, kv_model)
setattr(wrapped_class, '_%s_objects' % self.attribute_name, kv_model.objects)
setattr(wrapped_class, self.attribute_name, property(prop))
self.global_class = wrapped_class
return wrapped_class
return wrapper | python | def set_global(self, cache_namespace: str = None) -> type:
"""
Decorator. Attaches the global key-value store of this hierarchy to an object.
:param cache_namespace: Optional. A custom namespace used for caching. By default this is
constructed from the name of the class this is applied to and
the ``attribute_name`` of this ``Hierarkey`` object.
"""
if isinstance(cache_namespace, type):
raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add_global() '
'instead of .add_global')
def wrapper(wrapped_class):
if issubclass(wrapped_class, models.Model):
raise ImproperlyConfigured('Hierarkey.add_global() can only be invoked on a normal class, '
'not on a Django model.')
if not issubclass(wrapped_class, GlobalSettingsBase):
raise ImproperlyConfigured('You should use .add_global() on a class that inherits from '
'GlobalSettingsBase.')
_cache_namespace = cache_namespace or ('%s_%s' % (wrapped_class.__name__, self.attribute_name))
attrs = self._create_attrs(wrapped_class)
model_name = '%s_%sStore' % (wrapped_class.__name__, self.attribute_name.title())
if getattr(sys.modules[wrapped_class.__module__], model_name, None):
# Already wrapped
return wrapped_class
kv_model = self._create_model(model_name, attrs)
def init(self, *args, object=None, **kwargs):
super(kv_model, self).__init__(*args, **kwargs)
setattr(kv_model, '__init__', init)
hierarkey = self
def prop(iself):
from .proxy import HierarkeyProxy
attrname = '_hierarkey_proxy_{}_{}'.format(_cache_namespace, self.attribute_name)
cached = getattr(iself, attrname, None)
if not cached:
cached = HierarkeyProxy._new(iself, type=kv_model, hierarkey=hierarkey,
cache_namespace=_cache_namespace)
setattr(iself, attrname, cached)
return cached
setattr(sys.modules[wrapped_class.__module__], model_name, kv_model)
setattr(wrapped_class, '_%s_objects' % self.attribute_name, kv_model.objects)
setattr(wrapped_class, self.attribute_name, property(prop))
self.global_class = wrapped_class
return wrapped_class
return wrapper | [
"def",
"set_global",
"(",
"self",
",",
"cache_namespace",
":",
"str",
"=",
"None",
")",
"->",
"type",
":",
"if",
"isinstance",
"(",
"cache_namespace",
",",
"type",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Incorrect decorator usage, you need to use .add_glob... | Decorator. Attaches the global key-value store of this hierarchy to an object.
:param cache_namespace: Optional. A custom namespace used for caching. By default this is
constructed from the name of the class this is applied to and
the ``attribute_name`` of this ``Hierarkey`` object. | [
"Decorator",
".",
"Attaches",
"the",
"global",
"key",
"-",
"value",
"store",
"of",
"this",
"hierarchy",
"to",
"an",
"object",
"."
] | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/models.py#L69-L125 | train | 43,944 |
raphaelm/django-hierarkey | hierarkey/models.py | Hierarkey.add | def add(self, cache_namespace: str = None, parent_field: str = None) -> type:
"""
Decorator. Attaches a global key-value store to a Django model.
:param cache_namespace: Optional. A custom namespace used for caching. By default this is
constructed from the name of the class this is applied to and
the ``attribute_name`` of this ``Hierarkey`` object.
:param parent_field: Optional. The name of a field of this model that refers to the parent
in the hierarchy. This must be a ``ForeignKey`` field.
"""
if isinstance(cache_namespace, type):
raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add() instead of .add')
def wrapper(model):
if not issubclass(model, models.Model):
raise ImproperlyConfigured('Hierarkey.add() can only be invoked on a Django model')
_cache_namespace = cache_namespace or ('%s_%s' % (model.__name__, self.attribute_name))
attrs = self._create_attrs(model)
attrs['object'] = models.ForeignKey(model, related_name='_%s_objects' % self.attribute_name,
on_delete=models.CASCADE)
model_name = '%s_%sStore' % (model.__name__, self.attribute_name.title())
kv_model = self._create_model(model_name, attrs)
setattr(sys.modules[model.__module__], model_name, kv_model)
hierarkey = self
def prop(iself):
from .proxy import HierarkeyProxy
attrname = '_hierarkey_proxy_{}_{}'.format(_cache_namespace, self.attribute_name)
cached = getattr(iself, attrname, None)
if not cached:
try:
parent = getattr(iself, parent_field) if parent_field else None
except models.ObjectDoesNotExist: # pragma: no cover
parent = None
if not parent and hierarkey.global_class:
parent = hierarkey.global_class()
cached = HierarkeyProxy._new(
iself,
type=kv_model,
hierarkey=hierarkey,
parent=parent,
cache_namespace=_cache_namespace
)
setattr(iself, attrname, cached)
return cached
setattr(model, self.attribute_name, property(prop))
return model
return wrapper | python | def add(self, cache_namespace: str = None, parent_field: str = None) -> type:
"""
Decorator. Attaches a global key-value store to a Django model.
:param cache_namespace: Optional. A custom namespace used for caching. By default this is
constructed from the name of the class this is applied to and
the ``attribute_name`` of this ``Hierarkey`` object.
:param parent_field: Optional. The name of a field of this model that refers to the parent
in the hierarchy. This must be a ``ForeignKey`` field.
"""
if isinstance(cache_namespace, type):
raise ImproperlyConfigured('Incorrect decorator usage, you need to use .add() instead of .add')
def wrapper(model):
if not issubclass(model, models.Model):
raise ImproperlyConfigured('Hierarkey.add() can only be invoked on a Django model')
_cache_namespace = cache_namespace or ('%s_%s' % (model.__name__, self.attribute_name))
attrs = self._create_attrs(model)
attrs['object'] = models.ForeignKey(model, related_name='_%s_objects' % self.attribute_name,
on_delete=models.CASCADE)
model_name = '%s_%sStore' % (model.__name__, self.attribute_name.title())
kv_model = self._create_model(model_name, attrs)
setattr(sys.modules[model.__module__], model_name, kv_model)
hierarkey = self
def prop(iself):
from .proxy import HierarkeyProxy
attrname = '_hierarkey_proxy_{}_{}'.format(_cache_namespace, self.attribute_name)
cached = getattr(iself, attrname, None)
if not cached:
try:
parent = getattr(iself, parent_field) if parent_field else None
except models.ObjectDoesNotExist: # pragma: no cover
parent = None
if not parent and hierarkey.global_class:
parent = hierarkey.global_class()
cached = HierarkeyProxy._new(
iself,
type=kv_model,
hierarkey=hierarkey,
parent=parent,
cache_namespace=_cache_namespace
)
setattr(iself, attrname, cached)
return cached
setattr(model, self.attribute_name, property(prop))
return model
return wrapper | [
"def",
"add",
"(",
"self",
",",
"cache_namespace",
":",
"str",
"=",
"None",
",",
"parent_field",
":",
"str",
"=",
"None",
")",
"->",
"type",
":",
"if",
"isinstance",
"(",
"cache_namespace",
",",
"type",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'I... | Decorator. Attaches a global key-value store to a Django model.
:param cache_namespace: Optional. A custom namespace used for caching. By default this is
constructed from the name of the class this is applied to and
the ``attribute_name`` of this ``Hierarkey`` object.
:param parent_field: Optional. The name of a field of this model that refers to the parent
in the hierarchy. This must be a ``ForeignKey`` field. | [
"Decorator",
".",
"Attaches",
"a",
"global",
"key",
"-",
"value",
"store",
"to",
"a",
"Django",
"model",
"."
] | 3ca822f94fa633c9a6d5abe9c80cb1551299ae46 | https://github.com/raphaelm/django-hierarkey/blob/3ca822f94fa633c9a6d5abe9c80cb1551299ae46/hierarkey/models.py#L127-L185 | train | 43,945 |
IBMStreams/pypi.streamsx | streamsx/topology/graph.py | _as_spl_expr | def _as_spl_expr(value):
""" Return value converted to an SPL expression if
needed other otherwise value.
"""
import streamsx._streams._numpy
if hasattr(value, 'spl_json'):
return value
if isinstance(value, Enum):
value = streamsx.spl.op.Expression.expression(value.name)
npcnv = streamsx._streams._numpy.as_spl_expr(value)
if npcnv is not None:
return npcnv
return value | python | def _as_spl_expr(value):
""" Return value converted to an SPL expression if
needed other otherwise value.
"""
import streamsx._streams._numpy
if hasattr(value, 'spl_json'):
return value
if isinstance(value, Enum):
value = streamsx.spl.op.Expression.expression(value.name)
npcnv = streamsx._streams._numpy.as_spl_expr(value)
if npcnv is not None:
return npcnv
return value | [
"def",
"_as_spl_expr",
"(",
"value",
")",
":",
"import",
"streamsx",
".",
"_streams",
".",
"_numpy",
"if",
"hasattr",
"(",
"value",
",",
"'spl_json'",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"Enum",
")",
":",
"value",
"=",
"... | Return value converted to an SPL expression if
needed other otherwise value. | [
"Return",
"value",
"converted",
"to",
"an",
"SPL",
"expression",
"if",
"needed",
"other",
"otherwise",
"value",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/graph.py#L45-L61 | train | 43,946 |
IBMStreams/pypi.streamsx | streamsx/topology/graph.py | SPLGraph._requested_name | def _requested_name(self, name, action=None, func=None):
"""Create a unique name for an operator or a stream.
"""
if name is not None:
if name in self._used_names:
# start at 2 for the "second" one of this name
n = 2
while True:
pn = name + '_' + str(n)
if pn not in self._used_names:
self._used_names.add(pn)
return pn
n += 1
else:
self._used_names.add(name)
return name
if func is not None:
if hasattr(func, '__name__'):
name = func.__name__
if name == '<lambda>':
# Avoid use of <> characters in name
# as they are converted to unicode
# escapes in SPL identifier
name = action + '_lambda'
elif hasattr(func, '__class__'):
name = func.__class__.__name__
if name is None:
if action is not None:
name = action
else:
name = self.name
# Recurse once to get unique version of name
return self._requested_name(name) | python | def _requested_name(self, name, action=None, func=None):
"""Create a unique name for an operator or a stream.
"""
if name is not None:
if name in self._used_names:
# start at 2 for the "second" one of this name
n = 2
while True:
pn = name + '_' + str(n)
if pn not in self._used_names:
self._used_names.add(pn)
return pn
n += 1
else:
self._used_names.add(name)
return name
if func is not None:
if hasattr(func, '__name__'):
name = func.__name__
if name == '<lambda>':
# Avoid use of <> characters in name
# as they are converted to unicode
# escapes in SPL identifier
name = action + '_lambda'
elif hasattr(func, '__class__'):
name = func.__class__.__name__
if name is None:
if action is not None:
name = action
else:
name = self.name
# Recurse once to get unique version of name
return self._requested_name(name) | [
"def",
"_requested_name",
"(",
"self",
",",
"name",
",",
"action",
"=",
"None",
",",
"func",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"if",
"name",
"in",
"self",
".",
"_used_names",
":",
"# start at 2 for the \"second\" one of this name... | Create a unique name for an operator or a stream. | [
"Create",
"a",
"unique",
"name",
"for",
"an",
"operator",
"or",
"a",
"stream",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/graph.py#L106-L141 | train | 43,947 |
IBMStreams/pypi.streamsx | streamsx/topology/graph.py | _SPLInvocation.colocate | def colocate(self, others, why):
"""
Colocate this operator with another.
"""
if isinstance(self, Marker):
return
colocate_tag = '__spl_' + why + '$' + str(self.index)
self._colocate_tag(colocate_tag)
for op in others:
op._colocate_tag(colocate_tag) | python | def colocate(self, others, why):
"""
Colocate this operator with another.
"""
if isinstance(self, Marker):
return
colocate_tag = '__spl_' + why + '$' + str(self.index)
self._colocate_tag(colocate_tag)
for op in others:
op._colocate_tag(colocate_tag) | [
"def",
"colocate",
"(",
"self",
",",
"others",
",",
"why",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"Marker",
")",
":",
"return",
"colocate_tag",
"=",
"'__spl_'",
"+",
"why",
"+",
"'$'",
"+",
"str",
"(",
"self",
".",
"index",
")",
"self",
".... | Colocate this operator with another. | [
"Colocate",
"this",
"operator",
"with",
"another",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/graph.py#L501-L510 | train | 43,948 |
IBMStreams/pypi.streamsx | streamsx/spl/op.py | Expression.expression | def expression(value):
"""Create an SPL expression.
Args:
value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value.
Returns:
Expression: SPL expression from `value`.
"""
if isinstance(value, Expression):
# Clone the expression to allow it to
# be used in multiple contexts
return Expression(value._type, value._value)
if hasattr(value, 'spl_json'):
sj = value.spl_json()
return Expression(sj['type'], sj['value'])
return Expression('splexpr', value) | python | def expression(value):
"""Create an SPL expression.
Args:
value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value.
Returns:
Expression: SPL expression from `value`.
"""
if isinstance(value, Expression):
# Clone the expression to allow it to
# be used in multiple contexts
return Expression(value._type, value._value)
if hasattr(value, 'spl_json'):
sj = value.spl_json()
return Expression(sj['type'], sj['value'])
return Expression('splexpr', value) | [
"def",
"expression",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Expression",
")",
":",
"# Clone the expression to allow it to",
"# be used in multiple contexts",
"return",
"Expression",
"(",
"value",
".",
"_type",
",",
"value",
".",
"_value",
... | Create an SPL expression.
Args:
value: Expression as a string or another `Expression`. If value is an instance of `Expression` then a new instance is returned containing the same type and value.
Returns:
Expression: SPL expression from `value`. | [
"Create",
"an",
"SPL",
"expression",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/op.py#L410-L426 | train | 43,949 |
IBMStreams/pypi.streamsx | streamsx/spl/op.py | Expression.spl_json | def spl_json(self):
"""Private method. May be removed at any time."""
_splj = {}
_splj["type"] = self._type
_splj["value"] = self._value
return _splj | python | def spl_json(self):
"""Private method. May be removed at any time."""
_splj = {}
_splj["type"] = self._type
_splj["value"] = self._value
return _splj | [
"def",
"spl_json",
"(",
"self",
")",
":",
"_splj",
"=",
"{",
"}",
"_splj",
"[",
"\"type\"",
"]",
"=",
"self",
".",
"_type",
"_splj",
"[",
"\"value\"",
"]",
"=",
"self",
".",
"_value",
"return",
"_splj"
] | Private method. May be removed at any time. | [
"Private",
"method",
".",
"May",
"be",
"removed",
"at",
"any",
"time",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/op.py#L428-L433 | train | 43,950 |
IBMStreams/pypi.streamsx | streamsx/scripts/extract.py | _Extractor._setup_info_xml | def _setup_info_xml(self, languageList):
'''Setup the info.xml file
This function prepares or checks the info.xml file in the project directory
- if the info.xml does not exist in the project directory, it copies the template info.xml into the project directory.
The project name is obtained from the project directory name
- If there is a info.xml file, the resource section is inspected. If the resource section has no valid message set
description for the TopologySplpy Resource a warning message is printed'''
infoXmlFile = os.path.join(self._tk_dir, 'info.xml')
print('Check info.xml:', infoXmlFile)
try:
TopologySplpyResourceMessageSetFound = False
TopologySplpyResourceLanguages = []
tree = ET.parse(infoXmlFile)
root = tree.getroot()
for resources in root.findall('{http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo}resources'):
if self._cmd_args.verbose:
print('Resource: ', resources.tag)
for messageSet in resources.findall('{http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo}messageSet'):
if self._cmd_args.verbose:
print('Message set:', messageSet.tag, messageSet.attrib)
if 'name' in messageSet.attrib:
if messageSet.attrib['name'] == 'TopologySplpyResource':
TopologySplpyResourceMessageSetFound = True
for lang in messageSet.findall('{http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo}lang'):
language = os.path.dirname(lang.text)
TopologySplpyResourceLanguages.append(language)
if TopologySplpyResourceMessageSetFound:
TopologySplpyResourceLanguages.sort()
languageList.sort()
copiedLanguagesSet = set(languageList)
resourceLanguageSet = set(TopologySplpyResourceLanguages)
if self._cmd_args.verbose:
print('copied language resources:\n', languageList)
print('TopologySplpyResource from info.xml:\n', TopologySplpyResourceLanguages)
if copiedLanguagesSet == resourceLanguageSet:
print('Resource section of info.xml verified')
else:
errstr = """"ERROR: Message set for the "TopologySplpyResource" is incomplete or invalid. Correct the resource section in info.xml file.
Sample info xml:\n""" + _INFO_XML_TEMPLATE
sys.exit(errstr)
else:
errstr = """"ERROR: Message set for the "TopologySplpyResource" is missing. Correct the resource section in info.xml file.
Sample info xml:\n""" + _INFO_XML_TEMPLATE
sys.exit(errstr)
except FileNotFoundError as e:
print("WARNING: File info.xml not found. Creating info.xml from template")
#Get default project name from project directory
projectRootDir = os.path.abspath(self._tk_dir) #os.path.abspath returns the path without trailing /
projectName = os.path.basename(projectRootDir)
infoXml=_INFO_XML_TEMPLATE.replace('__SPLPY_TOOLKIT_NAME__', projectName)
f = open(infoXmlFile, 'w')
f.write(infoXml)
f.close()
except SystemExit as e:
raise e
except:
errstr = """ERROR: File info.xml is invalid or not accessible
Sample info xml:\n""" + _INFO_XML_TEMPLATE
sys.exit(errstr) | python | def _setup_info_xml(self, languageList):
'''Setup the info.xml file
This function prepares or checks the info.xml file in the project directory
- if the info.xml does not exist in the project directory, it copies the template info.xml into the project directory.
The project name is obtained from the project directory name
- If there is a info.xml file, the resource section is inspected. If the resource section has no valid message set
description for the TopologySplpy Resource a warning message is printed'''
infoXmlFile = os.path.join(self._tk_dir, 'info.xml')
print('Check info.xml:', infoXmlFile)
try:
TopologySplpyResourceMessageSetFound = False
TopologySplpyResourceLanguages = []
tree = ET.parse(infoXmlFile)
root = tree.getroot()
for resources in root.findall('{http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo}resources'):
if self._cmd_args.verbose:
print('Resource: ', resources.tag)
for messageSet in resources.findall('{http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo}messageSet'):
if self._cmd_args.verbose:
print('Message set:', messageSet.tag, messageSet.attrib)
if 'name' in messageSet.attrib:
if messageSet.attrib['name'] == 'TopologySplpyResource':
TopologySplpyResourceMessageSetFound = True
for lang in messageSet.findall('{http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo}lang'):
language = os.path.dirname(lang.text)
TopologySplpyResourceLanguages.append(language)
if TopologySplpyResourceMessageSetFound:
TopologySplpyResourceLanguages.sort()
languageList.sort()
copiedLanguagesSet = set(languageList)
resourceLanguageSet = set(TopologySplpyResourceLanguages)
if self._cmd_args.verbose:
print('copied language resources:\n', languageList)
print('TopologySplpyResource from info.xml:\n', TopologySplpyResourceLanguages)
if copiedLanguagesSet == resourceLanguageSet:
print('Resource section of info.xml verified')
else:
errstr = """"ERROR: Message set for the "TopologySplpyResource" is incomplete or invalid. Correct the resource section in info.xml file.
Sample info xml:\n""" + _INFO_XML_TEMPLATE
sys.exit(errstr)
else:
errstr = """"ERROR: Message set for the "TopologySplpyResource" is missing. Correct the resource section in info.xml file.
Sample info xml:\n""" + _INFO_XML_TEMPLATE
sys.exit(errstr)
except FileNotFoundError as e:
print("WARNING: File info.xml not found. Creating info.xml from template")
#Get default project name from project directory
projectRootDir = os.path.abspath(self._tk_dir) #os.path.abspath returns the path without trailing /
projectName = os.path.basename(projectRootDir)
infoXml=_INFO_XML_TEMPLATE.replace('__SPLPY_TOOLKIT_NAME__', projectName)
f = open(infoXmlFile, 'w')
f.write(infoXml)
f.close()
except SystemExit as e:
raise e
except:
errstr = """ERROR: File info.xml is invalid or not accessible
Sample info xml:\n""" + _INFO_XML_TEMPLATE
sys.exit(errstr) | [
"def",
"_setup_info_xml",
"(",
"self",
",",
"languageList",
")",
":",
"infoXmlFile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_tk_dir",
",",
"'info.xml'",
")",
"print",
"(",
"'Check info.xml:'",
",",
"infoXmlFile",
")",
"try",
":",
"Topology... | Setup the info.xml file
This function prepares or checks the info.xml file in the project directory
- if the info.xml does not exist in the project directory, it copies the template info.xml into the project directory.
The project name is obtained from the project directory name
- If there is a info.xml file, the resource section is inspected. If the resource section has no valid message set
description for the TopologySplpy Resource a warning message is printed | [
"Setup",
"the",
"info",
".",
"xml",
"file",
"This",
"function",
"prepares",
"or",
"checks",
"the",
"info",
".",
"xml",
"file",
"in",
"the",
"project",
"directory",
"-",
"if",
"the",
"info",
".",
"xml",
"does",
"not",
"exist",
"in",
"the",
"project",
"d... | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/extract.py#L442-L504 | train | 43,951 |
IBMStreams/pypi.streamsx | streamsx/scripts/info.py | main | def main(args=None):
""" Output information about `streamsx` and the environment.
Useful for support to get key information for use of `streamsx`
and Python in IBM Streams.
"""
_parse_args(args)
streamsx._streams._version._mismatch_check('streamsx.topology.context')
srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse('streamsx'))
if srp is not None:
srv = srp.parsed_version
location = srp.location
spkg = 'package'
else:
srv = streamsx._streams._version.__version__
location = os.path.dirname(streamsx._streams._version.__file__)
location = os.path.dirname(location)
location = os.path.dirname(location)
tk_path = (os.path.join('com.ibm.streamsx.topology', 'opt', 'python', 'packages'))
spkg = 'toolkit' if location.endswith(tk_path) else 'unknown'
print('streamsx==' + str(srv) + ' (' + spkg + ')')
print(' location: ' + str(location))
print('Python version:' + str(sys.version))
print('PYTHONHOME=' + str(os.environ.get('PYTHONHOME', 'unset')))
print('PYTHONPATH=' + str(os.environ.get('PYTHONPATH', 'unset')))
print('PYTHONWARNINGS=' + str(os.environ.get('PYTHONWARNINGS', 'unset')))
print('STREAMS_INSTALL=' + str(os.environ.get('STREAMS_INSTALL', 'unset')))
print('JAVA_HOME=' + str(os.environ.get('JAVA_HOME', 'unset')))
return 0 | python | def main(args=None):
""" Output information about `streamsx` and the environment.
Useful for support to get key information for use of `streamsx`
and Python in IBM Streams.
"""
_parse_args(args)
streamsx._streams._version._mismatch_check('streamsx.topology.context')
srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse('streamsx'))
if srp is not None:
srv = srp.parsed_version
location = srp.location
spkg = 'package'
else:
srv = streamsx._streams._version.__version__
location = os.path.dirname(streamsx._streams._version.__file__)
location = os.path.dirname(location)
location = os.path.dirname(location)
tk_path = (os.path.join('com.ibm.streamsx.topology', 'opt', 'python', 'packages'))
spkg = 'toolkit' if location.endswith(tk_path) else 'unknown'
print('streamsx==' + str(srv) + ' (' + spkg + ')')
print(' location: ' + str(location))
print('Python version:' + str(sys.version))
print('PYTHONHOME=' + str(os.environ.get('PYTHONHOME', 'unset')))
print('PYTHONPATH=' + str(os.environ.get('PYTHONPATH', 'unset')))
print('PYTHONWARNINGS=' + str(os.environ.get('PYTHONWARNINGS', 'unset')))
print('STREAMS_INSTALL=' + str(os.environ.get('STREAMS_INSTALL', 'unset')))
print('JAVA_HOME=' + str(os.environ.get('JAVA_HOME', 'unset')))
return 0 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"_parse_args",
"(",
"args",
")",
"streamsx",
".",
"_streams",
".",
"_version",
".",
"_mismatch_check",
"(",
"'streamsx.topology.context'",
")",
"srp",
"=",
"pkg_resources",
".",
"working_set",
".",
"find",
"... | Output information about `streamsx` and the environment.
Useful for support to get key information for use of `streamsx`
and Python in IBM Streams. | [
"Output",
"information",
"about",
"streamsx",
"and",
"the",
"environment",
".",
"Useful",
"for",
"support",
"to",
"get",
"key",
"information",
"for",
"use",
"of",
"streamsx",
"and",
"Python",
"in",
"IBM",
"Streams",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/info.py#L15-L44 | train | 43,952 |
IBMStreams/pypi.streamsx | streamsx/topology/state.py | ConsistentRegionConfig.operator_driven | def operator_driven(drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS):
"""Define an operator-driven consistent region configuration.
The source operator triggers drain and checkpoint cycles for the region.
Args:
drain_timeout: The drain timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default value is 180 seconds.
reset_timeout: The reset timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default value is 180 seconds.
max_consecutive_attempts(int): The maximum number of consecutive attempts to reset the region. This must be an integer value between 1 and 2147483647, inclusive. If not specified, the default value is 5.
Returns:
ConsistentRegionConfig: the configuration.
"""
return ConsistentRegionConfig(trigger=ConsistentRegionConfig.Trigger.OPERATOR_DRIVEN, drain_timeout=drain_timeout, reset_timeout=reset_timeout, max_consecutive_attempts=max_consecutive_attempts) | python | def operator_driven(drain_timeout=_DEFAULT_DRAIN, reset_timeout=_DEFAULT_RESET, max_consecutive_attempts=_DEFAULT_ATTEMPTS):
"""Define an operator-driven consistent region configuration.
The source operator triggers drain and checkpoint cycles for the region.
Args:
drain_timeout: The drain timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default value is 180 seconds.
reset_timeout: The reset timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default value is 180 seconds.
max_consecutive_attempts(int): The maximum number of consecutive attempts to reset the region. This must be an integer value between 1 and 2147483647, inclusive. If not specified, the default value is 5.
Returns:
ConsistentRegionConfig: the configuration.
"""
return ConsistentRegionConfig(trigger=ConsistentRegionConfig.Trigger.OPERATOR_DRIVEN, drain_timeout=drain_timeout, reset_timeout=reset_timeout, max_consecutive_attempts=max_consecutive_attempts) | [
"def",
"operator_driven",
"(",
"drain_timeout",
"=",
"_DEFAULT_DRAIN",
",",
"reset_timeout",
"=",
"_DEFAULT_RESET",
",",
"max_consecutive_attempts",
"=",
"_DEFAULT_ATTEMPTS",
")",
":",
"return",
"ConsistentRegionConfig",
"(",
"trigger",
"=",
"ConsistentRegionConfig",
".",... | Define an operator-driven consistent region configuration.
The source operator triggers drain and checkpoint cycles for the region.
Args:
drain_timeout: The drain timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default value is 180 seconds.
reset_timeout: The reset timeout, as either a :py:class:`datetime.timedelta` value or the number of seconds as a `float`. If not specified, the default value is 180 seconds.
max_consecutive_attempts(int): The maximum number of consecutive attempts to reset the region. This must be an integer value between 1 and 2147483647, inclusive. If not specified, the default value is 5.
Returns:
ConsistentRegionConfig: the configuration. | [
"Define",
"an",
"operator",
"-",
"driven",
"consistent",
"region",
"configuration",
".",
"The",
"source",
"operator",
"triggers",
"drain",
"and",
"checkpoint",
"cycles",
"for",
"the",
"region",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/topology/state.py#L177-L190 | train | 43,953 |
IBMStreams/pypi.streamsx | streamsx/spl/types.py | _get_timestamp_tuple | def _get_timestamp_tuple(ts):
"""
Internal method to get a timestamp tuple from a value.
Handles input being a datetime or a Timestamp.
"""
if isinstance(ts, datetime.datetime):
return Timestamp.from_datetime(ts).tuple()
elif isinstance(ts, Timestamp):
return ts
raise TypeError('Timestamp or datetime.datetime required') | python | def _get_timestamp_tuple(ts):
"""
Internal method to get a timestamp tuple from a value.
Handles input being a datetime or a Timestamp.
"""
if isinstance(ts, datetime.datetime):
return Timestamp.from_datetime(ts).tuple()
elif isinstance(ts, Timestamp):
return ts
raise TypeError('Timestamp or datetime.datetime required') | [
"def",
"_get_timestamp_tuple",
"(",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"Timestamp",
".",
"from_datetime",
"(",
"ts",
")",
".",
"tuple",
"(",
")",
"elif",
"isinstance",
"(",
"ts",
",",
"T... | Internal method to get a timestamp tuple from a value.
Handles input being a datetime or a Timestamp. | [
"Internal",
"method",
"to",
"get",
"a",
"timestamp",
"tuple",
"from",
"a",
"value",
".",
"Handles",
"input",
"being",
"a",
"datetime",
"or",
"a",
"Timestamp",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/types.py#L155-L164 | train | 43,954 |
IBMStreams/pypi.streamsx | streamsx/spl/toolkit.py | add_toolkit | def add_toolkit(topology, location):
"""Add an SPL toolkit to a topology.
Args:
topology(Topology): Topology to include toolkit in.
location(str): Location of the toolkit directory.
"""
import streamsx.topology.topology
assert isinstance(topology, streamsx.topology.topology.Topology)
tkinfo = dict()
tkinfo['root'] = os.path.abspath(location)
topology.graph._spl_toolkits.append(tkinfo) | python | def add_toolkit(topology, location):
"""Add an SPL toolkit to a topology.
Args:
topology(Topology): Topology to include toolkit in.
location(str): Location of the toolkit directory.
"""
import streamsx.topology.topology
assert isinstance(topology, streamsx.topology.topology.Topology)
tkinfo = dict()
tkinfo['root'] = os.path.abspath(location)
topology.graph._spl_toolkits.append(tkinfo) | [
"def",
"add_toolkit",
"(",
"topology",
",",
"location",
")",
":",
"import",
"streamsx",
".",
"topology",
".",
"topology",
"assert",
"isinstance",
"(",
"topology",
",",
"streamsx",
".",
"topology",
".",
"topology",
".",
"Topology",
")",
"tkinfo",
"=",
"dict",... | Add an SPL toolkit to a topology.
Args:
topology(Topology): Topology to include toolkit in.
location(str): Location of the toolkit directory. | [
"Add",
"an",
"SPL",
"toolkit",
"to",
"a",
"topology",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/toolkit.py#L25-L36 | train | 43,955 |
IBMStreams/pypi.streamsx | streamsx/spl/toolkit.py | add_toolkit_dependency | def add_toolkit_dependency(topology, name, version):
"""Add a version dependency on an SPL toolkit to a topology.
To specify a range of versions for the dependent toolkits,
use brackets (``[]``) or parentheses. Use brackets to represent an
inclusive range and parentheses to represent an exclusive range.
The following examples describe how to specify a dependency on a range of toolkit versions:
* ``[1.0.0, 2.0.0]`` represents a dependency on toolkit versions 1.0.0 - 2.0.0, both inclusive.
* ``[1.0.0, 2.0.0)`` represents a dependency on toolkit versions 1.0.0 or later, but not including 2.0.0.
* ``(1.0.0, 2.0.0]`` represents a dependency on toolkits versions later than 1.0.0 and less than or equal to 2.0.0.
* ``(1.0.0, 2.0.0)`` represents a dependency on toolkit versions 1.0.0 - 2.0.0, both exclusive.
Args:
topology(Topology): Topology to include toolkit in.
name(str): Toolkit name.
version(str): Toolkit version dependency.
.. seealso::
`Toolkit information model file <https://www.ibm.com/support/knowledgecenter/SSCRJU_4.3.0/com.ibm.streams.dev.doc/doc/toolkitinformationmodelfile.html>`_
.. versionadded:: 1.12
"""
import streamsx.topology.topology
assert isinstance(topology, streamsx.topology.topology.Topology)
tkinfo = dict()
tkinfo['name'] = name
tkinfo['version'] = version
topology.graph._spl_toolkits.append(tkinfo) | python | def add_toolkit_dependency(topology, name, version):
"""Add a version dependency on an SPL toolkit to a topology.
To specify a range of versions for the dependent toolkits,
use brackets (``[]``) or parentheses. Use brackets to represent an
inclusive range and parentheses to represent an exclusive range.
The following examples describe how to specify a dependency on a range of toolkit versions:
* ``[1.0.0, 2.0.0]`` represents a dependency on toolkit versions 1.0.0 - 2.0.0, both inclusive.
* ``[1.0.0, 2.0.0)`` represents a dependency on toolkit versions 1.0.0 or later, but not including 2.0.0.
* ``(1.0.0, 2.0.0]`` represents a dependency on toolkits versions later than 1.0.0 and less than or equal to 2.0.0.
* ``(1.0.0, 2.0.0)`` represents a dependency on toolkit versions 1.0.0 - 2.0.0, both exclusive.
Args:
topology(Topology): Topology to include toolkit in.
name(str): Toolkit name.
version(str): Toolkit version dependency.
.. seealso::
`Toolkit information model file <https://www.ibm.com/support/knowledgecenter/SSCRJU_4.3.0/com.ibm.streams.dev.doc/doc/toolkitinformationmodelfile.html>`_
.. versionadded:: 1.12
"""
import streamsx.topology.topology
assert isinstance(topology, streamsx.topology.topology.Topology)
tkinfo = dict()
tkinfo['name'] = name
tkinfo['version'] = version
topology.graph._spl_toolkits.append(tkinfo) | [
"def",
"add_toolkit_dependency",
"(",
"topology",
",",
"name",
",",
"version",
")",
":",
"import",
"streamsx",
".",
"topology",
".",
"topology",
"assert",
"isinstance",
"(",
"topology",
",",
"streamsx",
".",
"topology",
".",
"topology",
".",
"Topology",
")",
... | Add a version dependency on an SPL toolkit to a topology.
To specify a range of versions for the dependent toolkits,
use brackets (``[]``) or parentheses. Use brackets to represent an
inclusive range and parentheses to represent an exclusive range.
The following examples describe how to specify a dependency on a range of toolkit versions:
* ``[1.0.0, 2.0.0]`` represents a dependency on toolkit versions 1.0.0 - 2.0.0, both inclusive.
* ``[1.0.0, 2.0.0)`` represents a dependency on toolkit versions 1.0.0 or later, but not including 2.0.0.
* ``(1.0.0, 2.0.0]`` represents a dependency on toolkits versions later than 1.0.0 and less than or equal to 2.0.0.
* ``(1.0.0, 2.0.0)`` represents a dependency on toolkit versions 1.0.0 - 2.0.0, both exclusive.
Args:
topology(Topology): Topology to include toolkit in.
name(str): Toolkit name.
version(str): Toolkit version dependency.
.. seealso::
`Toolkit information model file <https://www.ibm.com/support/knowledgecenter/SSCRJU_4.3.0/com.ibm.streams.dev.doc/doc/toolkitinformationmodelfile.html>`_
.. versionadded:: 1.12 | [
"Add",
"a",
"version",
"dependency",
"on",
"an",
"SPL",
"toolkit",
"to",
"a",
"topology",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/toolkit.py#L38-L67 | train | 43,956 |
IBMStreams/pypi.streamsx | streamsx/scripts/runner.py | submit | def submit(args=None):
""" Performs the submit according to arguments and
returns an object describing the result.
"""
streamsx._streams._version._mismatch_check('streamsx.topology.context')
cmd_args = _parse_args(args)
if cmd_args.topology is not None:
app = _get_topology_app(cmd_args)
elif cmd_args.main_composite is not None:
app = _get_spl_app(cmd_args)
elif cmd_args.bundle is not None:
app = _get_bundle(cmd_args)
_job_config_args(cmd_args, app)
sr = _submit(cmd_args, app)
if 'return_code' not in sr:
sr['return_code'] = 1;
print(sr)
return sr | python | def submit(args=None):
""" Performs the submit according to arguments and
returns an object describing the result.
"""
streamsx._streams._version._mismatch_check('streamsx.topology.context')
cmd_args = _parse_args(args)
if cmd_args.topology is not None:
app = _get_topology_app(cmd_args)
elif cmd_args.main_composite is not None:
app = _get_spl_app(cmd_args)
elif cmd_args.bundle is not None:
app = _get_bundle(cmd_args)
_job_config_args(cmd_args, app)
sr = _submit(cmd_args, app)
if 'return_code' not in sr:
sr['return_code'] = 1;
print(sr)
return sr | [
"def",
"submit",
"(",
"args",
"=",
"None",
")",
":",
"streamsx",
".",
"_streams",
".",
"_version",
".",
"_mismatch_check",
"(",
"'streamsx.topology.context'",
")",
"cmd_args",
"=",
"_parse_args",
"(",
"args",
")",
"if",
"cmd_args",
".",
"topology",
"is",
"no... | Performs the submit according to arguments and
returns an object describing the result. | [
"Performs",
"the",
"submit",
"according",
"to",
"arguments",
"and",
"returns",
"an",
"object",
"describing",
"the",
"result",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/runner.py#L44-L61 | train | 43,957 |
IBMStreams/pypi.streamsx | streamsx/scripts/runner.py | _define_jco_args | def _define_jco_args(cmd_parser):
"""
Define job configuration arguments.
Returns groups defined, currently one.
"""
jo_group = cmd_parser.add_argument_group('Job options', 'Job configuration options')
jo_group.add_argument('--job-name', help='Job name')
jo_group.add_argument('--preload', action='store_true', help='Preload job onto all resources in the instance')
jo_group.add_argument('--trace', choices=['error', 'warn', 'info', 'debug', 'trace'], help='Application trace level')
jo_group.add_argument('--submission-parameters', '-p', nargs='+', action=_SubmitParamArg, help="Submission parameters as name=value pairs")
jo_group.add_argument('--job-config-overlays', help="Path to file containing job configuration overlays JSON. Overrides any job configuration set by the application." , metavar='file')
return jo_group, | python | def _define_jco_args(cmd_parser):
"""
Define job configuration arguments.
Returns groups defined, currently one.
"""
jo_group = cmd_parser.add_argument_group('Job options', 'Job configuration options')
jo_group.add_argument('--job-name', help='Job name')
jo_group.add_argument('--preload', action='store_true', help='Preload job onto all resources in the instance')
jo_group.add_argument('--trace', choices=['error', 'warn', 'info', 'debug', 'trace'], help='Application trace level')
jo_group.add_argument('--submission-parameters', '-p', nargs='+', action=_SubmitParamArg, help="Submission parameters as name=value pairs")
jo_group.add_argument('--job-config-overlays', help="Path to file containing job configuration overlays JSON. Overrides any job configuration set by the application." , metavar='file')
return jo_group, | [
"def",
"_define_jco_args",
"(",
"cmd_parser",
")",
":",
"jo_group",
"=",
"cmd_parser",
".",
"add_argument_group",
"(",
"'Job options'",
",",
"'Job configuration options'",
")",
"jo_group",
".",
"add_argument",
"(",
"'--job-name'",
",",
"help",
"=",
"'Job name'",
")"... | Define job configuration arguments.
Returns groups defined, currently one. | [
"Define",
"job",
"configuration",
"arguments",
".",
"Returns",
"groups",
"defined",
"currently",
"one",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/runner.py#L92-L107 | train | 43,958 |
IBMStreams/pypi.streamsx | streamsx/scripts/runner.py | _submit_topology | def _submit_topology(cmd_args, app):
"""Submit a Python topology to the service.
This includes an SPL main composite wrapped in a Python topology.
"""
cfg = app.cfg
if cmd_args.create_bundle:
ctxtype = ctx.ContextTypes.BUNDLE
elif cmd_args.service_name:
cfg[ctx.ConfigParams.FORCE_REMOTE_BUILD] = True
cfg[ctx.ConfigParams.SERVICE_NAME] = cmd_args.service_name
ctxtype = ctx.ContextTypes.STREAMING_ANALYTICS_SERVICE
sr = ctx.submit(ctxtype, app.app, cfg)
return sr | python | def _submit_topology(cmd_args, app):
"""Submit a Python topology to the service.
This includes an SPL main composite wrapped in a Python topology.
"""
cfg = app.cfg
if cmd_args.create_bundle:
ctxtype = ctx.ContextTypes.BUNDLE
elif cmd_args.service_name:
cfg[ctx.ConfigParams.FORCE_REMOTE_BUILD] = True
cfg[ctx.ConfigParams.SERVICE_NAME] = cmd_args.service_name
ctxtype = ctx.ContextTypes.STREAMING_ANALYTICS_SERVICE
sr = ctx.submit(ctxtype, app.app, cfg)
return sr | [
"def",
"_submit_topology",
"(",
"cmd_args",
",",
"app",
")",
":",
"cfg",
"=",
"app",
".",
"cfg",
"if",
"cmd_args",
".",
"create_bundle",
":",
"ctxtype",
"=",
"ctx",
".",
"ContextTypes",
".",
"BUNDLE",
"elif",
"cmd_args",
".",
"service_name",
":",
"cfg",
... | Submit a Python topology to the service.
This includes an SPL main composite wrapped in a Python topology. | [
"Submit",
"a",
"Python",
"topology",
"to",
"the",
"service",
".",
"This",
"includes",
"an",
"SPL",
"main",
"composite",
"wrapped",
"in",
"a",
"Python",
"topology",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/runner.py#L155-L167 | train | 43,959 |
IBMStreams/pypi.streamsx | streamsx/scripts/runner.py | _submit_bundle | def _submit_bundle(cmd_args, app):
"""Submit an existing bundle to the service"""
sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name)
sas = sac.get_streaming_analytics()
sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG])
if 'exception' in sr:
rc = 1
elif 'status_code' in sr:
try:
rc = 0 if int(sr['status_code'] == 200) else 1
except:
rc = 1
elif 'id' in sr or 'jobId' in sr:
rc = 0
sr['return_code'] = rc
return sr | python | def _submit_bundle(cmd_args, app):
"""Submit an existing bundle to the service"""
sac = streamsx.rest.StreamingAnalyticsConnection(service_name=cmd_args.service_name)
sas = sac.get_streaming_analytics()
sr = sas.submit_job(bundle=app.app, job_config=app.cfg[ctx.ConfigParams.JOB_CONFIG])
if 'exception' in sr:
rc = 1
elif 'status_code' in sr:
try:
rc = 0 if int(sr['status_code'] == 200) else 1
except:
rc = 1
elif 'id' in sr or 'jobId' in sr:
rc = 0
sr['return_code'] = rc
return sr | [
"def",
"_submit_bundle",
"(",
"cmd_args",
",",
"app",
")",
":",
"sac",
"=",
"streamsx",
".",
"rest",
".",
"StreamingAnalyticsConnection",
"(",
"service_name",
"=",
"cmd_args",
".",
"service_name",
")",
"sas",
"=",
"sac",
".",
"get_streaming_analytics",
"(",
")... | Submit an existing bundle to the service | [
"Submit",
"an",
"existing",
"bundle",
"to",
"the",
"service"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/scripts/runner.py#L169-L184 | train | 43,960 |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | pipe | def pipe(wrapped):
"""
Decorator to create an SPL operator from a function.
A pipe SPL operator with a single input port and a single
output port. For each tuple on the input port the
function is called passing the contents of the tuple.
SPL attributes from the tuple are passed by position.
The value returned from the function results in
zero or more tuples being submitted to the operator output
port, see :ref:`submit-from-python`.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.map <map>` instead.
"""
if not inspect.isfunction(wrapped):
raise TypeError('A function is required')
return _wrapforsplop(_OperatorType.Pipe, wrapped, 'position', False) | python | def pipe(wrapped):
"""
Decorator to create an SPL operator from a function.
A pipe SPL operator with a single input port and a single
output port. For each tuple on the input port the
function is called passing the contents of the tuple.
SPL attributes from the tuple are passed by position.
The value returned from the function results in
zero or more tuples being submitted to the operator output
port, see :ref:`submit-from-python`.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.map <map>` instead.
"""
if not inspect.isfunction(wrapped):
raise TypeError('A function is required')
return _wrapforsplop(_OperatorType.Pipe, wrapped, 'position', False) | [
"def",
"pipe",
"(",
"wrapped",
")",
":",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"wrapped",
")",
":",
"raise",
"TypeError",
"(",
"'A function is required'",
")",
"return",
"_wrapforsplop",
"(",
"_OperatorType",
".",
"Pipe",
",",
"wrapped",
",",
"'pos... | Decorator to create an SPL operator from a function.
A pipe SPL operator with a single input port and a single
output port. For each tuple on the input port the
function is called passing the contents of the tuple.
SPL attributes from the tuple are passed by position.
The value returned from the function results in
zero or more tuples being submitted to the operator output
port, see :ref:`submit-from-python`.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.map <map>` instead. | [
"Decorator",
"to",
"create",
"an",
"SPL",
"operator",
"from",
"a",
"function",
".",
"A",
"pipe",
"SPL",
"operator",
"with",
"a",
"single",
"input",
"port",
"and",
"a",
"single",
"output",
"port",
".",
"For",
"each",
"tuple",
"on",
"the",
"input",
"port",... | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L663-L683 | train | 43,961 |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | _define_fixed | def _define_fixed(wrapped, callable_):
"""For the callable see how many positional parameters are required"""
is_class = inspect.isclass(wrapped)
style = callable_._splpy_style if hasattr(callable_, '_splpy_style') else wrapped._splpy_style
if style == 'dictionary':
return -1
fixed_count = 0
if style == 'tuple':
sig = _inspect.signature(callable_)
pmds = sig.parameters
itpmds = iter(pmds)
# Skip 'self' for classes
if is_class:
next(itpmds)
for pn in itpmds:
param = pmds[pn]
if param.kind == _inspect.Parameter.POSITIONAL_OR_KEYWORD:
fixed_count += 1
if param.kind == _inspect.Parameter.VAR_POSITIONAL: # *args
fixed_count = -1
break
if param.kind == _inspect.Parameter.VAR_KEYWORD:
break
return fixed_count | python | def _define_fixed(wrapped, callable_):
"""For the callable see how many positional parameters are required"""
is_class = inspect.isclass(wrapped)
style = callable_._splpy_style if hasattr(callable_, '_splpy_style') else wrapped._splpy_style
if style == 'dictionary':
return -1
fixed_count = 0
if style == 'tuple':
sig = _inspect.signature(callable_)
pmds = sig.parameters
itpmds = iter(pmds)
# Skip 'self' for classes
if is_class:
next(itpmds)
for pn in itpmds:
param = pmds[pn]
if param.kind == _inspect.Parameter.POSITIONAL_OR_KEYWORD:
fixed_count += 1
if param.kind == _inspect.Parameter.VAR_POSITIONAL: # *args
fixed_count = -1
break
if param.kind == _inspect.Parameter.VAR_KEYWORD:
break
return fixed_count | [
"def",
"_define_fixed",
"(",
"wrapped",
",",
"callable_",
")",
":",
"is_class",
"=",
"inspect",
".",
"isclass",
"(",
"wrapped",
")",
"style",
"=",
"callable_",
".",
"_splpy_style",
"if",
"hasattr",
"(",
"callable_",
",",
"'_splpy_style'",
")",
"else",
"wrapp... | For the callable see how many positional parameters are required | [
"For",
"the",
"callable",
"see",
"how",
"many",
"positional",
"parameters",
"are",
"required"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L829-L855 | train | 43,962 |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | ignore | def ignore(wrapped):
"""
Decorator to ignore a Python function.
If a Python callable is decorated with ``@spl.ignore``
then function is ignored by ``spl-python-extract.py``.
Args:
wrapped: Function that will be ignored.
"""
@functools.wraps(wrapped)
def _ignore(*args, **kwargs):
return wrapped(*args, **kwargs)
_ignore._splpy_optype = _OperatorType.Ignore
_ignore._splpy_file = inspect.getsourcefile(wrapped)
return _ignore | python | def ignore(wrapped):
"""
Decorator to ignore a Python function.
If a Python callable is decorated with ``@spl.ignore``
then function is ignored by ``spl-python-extract.py``.
Args:
wrapped: Function that will be ignored.
"""
@functools.wraps(wrapped)
def _ignore(*args, **kwargs):
return wrapped(*args, **kwargs)
_ignore._splpy_optype = _OperatorType.Ignore
_ignore._splpy_file = inspect.getsourcefile(wrapped)
return _ignore | [
"def",
"ignore",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"_ignore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_ignore",
... | Decorator to ignore a Python function.
If a Python callable is decorated with ``@spl.ignore``
then function is ignored by ``spl-python-extract.py``.
Args:
wrapped: Function that will be ignored. | [
"Decorator",
"to",
"ignore",
"a",
"Python",
"function",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L1082-L1097 | train | 43,963 |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | sink | def sink(wrapped):
"""Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.for_each <for_each>` instead.
"""
if not inspect.isfunction(wrapped):
raise TypeError('A function is required')
return _wrapforsplop(_OperatorType.Sink, wrapped, 'position', False) | python | def sink(wrapped):
"""Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.for_each <for_each>` instead.
"""
if not inspect.isfunction(wrapped):
raise TypeError('A function is required')
return _wrapforsplop(_OperatorType.Sink, wrapped, 'position', False) | [
"def",
"sink",
"(",
"wrapped",
")",
":",
"if",
"not",
"inspect",
".",
"isfunction",
"(",
"wrapped",
")",
":",
"raise",
"TypeError",
"(",
"'A function is required'",
")",
"return",
"_wrapforsplop",
"(",
"_OperatorType",
".",
"Sink",
",",
"wrapped",
",",
"'pos... | Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.for_each <for_each>` instead. | [
"Creates",
"an",
"SPL",
"operator",
"with",
"a",
"single",
"input",
"port",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L1100-L1113 | train | 43,964 |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | PrimitiveOperator.submit | def submit(self, port_id, tuple_):
"""Submit a tuple to the output port.
The value to be submitted (``tuple_``) can be a ``None`` (nothing will be submitted),
``tuple``, ``dict` or ``list`` of those types. For details
on how the ``tuple_`` is mapped to an SPL tuple see :ref:`submit-from-python`.
Args:
port_id: Identifier of the port specified in the
``output_ports`` parameter of the ``@spl.primitive_operator``
decorator.
tuple_: Tuple (or tuples) to be submitted to the output port.
"""
port_index = self._splpy_output_ports[port_id]
ec._submit(self, port_index, tuple_) | python | def submit(self, port_id, tuple_):
"""Submit a tuple to the output port.
The value to be submitted (``tuple_``) can be a ``None`` (nothing will be submitted),
``tuple``, ``dict` or ``list`` of those types. For details
on how the ``tuple_`` is mapped to an SPL tuple see :ref:`submit-from-python`.
Args:
port_id: Identifier of the port specified in the
``output_ports`` parameter of the ``@spl.primitive_operator``
decorator.
tuple_: Tuple (or tuples) to be submitted to the output port.
"""
port_index = self._splpy_output_ports[port_id]
ec._submit(self, port_index, tuple_) | [
"def",
"submit",
"(",
"self",
",",
"port_id",
",",
"tuple_",
")",
":",
"port_index",
"=",
"self",
".",
"_splpy_output_ports",
"[",
"port_id",
"]",
"ec",
".",
"_submit",
"(",
"self",
",",
"port_index",
",",
"tuple_",
")"
] | Submit a tuple to the output port.
The value to be submitted (``tuple_``) can be a ``None`` (nothing will be submitted),
``tuple``, ``dict` or ``list`` of those types. For details
on how the ``tuple_`` is mapped to an SPL tuple see :ref:`submit-from-python`.
Args:
port_id: Identifier of the port specified in the
``output_ports`` parameter of the ``@spl.primitive_operator``
decorator.
tuple_: Tuple (or tuples) to be submitted to the output port. | [
"Submit",
"a",
"tuple",
"to",
"the",
"output",
"port",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L1174-L1188 | train | 43,965 |
IBMStreams/pypi.streamsx | streamsx/spl/runtime.py | _splpy_primitive_input_fns | def _splpy_primitive_input_fns(obj):
"""Convert the list of class input functions to be
instance functions against obj.
Used by @spl.primitive_operator SPL cpp template.
"""
ofns = list()
for fn in obj._splpy_input_ports:
ofns.append(getattr(obj, fn.__name__))
return ofns | python | def _splpy_primitive_input_fns(obj):
"""Convert the list of class input functions to be
instance functions against obj.
Used by @spl.primitive_operator SPL cpp template.
"""
ofns = list()
for fn in obj._splpy_input_ports:
ofns.append(getattr(obj, fn.__name__))
return ofns | [
"def",
"_splpy_primitive_input_fns",
"(",
"obj",
")",
":",
"ofns",
"=",
"list",
"(",
")",
"for",
"fn",
"in",
"obj",
".",
"_splpy_input_ports",
":",
"ofns",
".",
"append",
"(",
"getattr",
"(",
"obj",
",",
"fn",
".",
"__name__",
")",
")",
"return",
"ofns... | Convert the list of class input functions to be
instance functions against obj.
Used by @spl.primitive_operator SPL cpp template. | [
"Convert",
"the",
"list",
"of",
"class",
"input",
"functions",
"to",
"be",
"instance",
"functions",
"against",
"obj",
".",
"Used",
"by"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/runtime.py#L117-L125 | train | 43,966 |
IBMStreams/pypi.streamsx | streamsx/spl/runtime.py | _splpy_all_ports_ready | def _splpy_all_ports_ready(callable_):
"""Call all_ports_ready for a primitive operator."""
if hasattr(type(callable_), 'all_ports_ready'):
try:
return callable_.all_ports_ready()
except:
ei = sys.exc_info()
if streamsx._streams._runtime._call_exit(callable_, ei):
return None
raise e1[1]
return None | python | def _splpy_all_ports_ready(callable_):
"""Call all_ports_ready for a primitive operator."""
if hasattr(type(callable_), 'all_ports_ready'):
try:
return callable_.all_ports_ready()
except:
ei = sys.exc_info()
if streamsx._streams._runtime._call_exit(callable_, ei):
return None
raise e1[1]
return None | [
"def",
"_splpy_all_ports_ready",
"(",
"callable_",
")",
":",
"if",
"hasattr",
"(",
"type",
"(",
"callable_",
")",
",",
"'all_ports_ready'",
")",
":",
"try",
":",
"return",
"callable_",
".",
"all_ports_ready",
"(",
")",
"except",
":",
"ei",
"=",
"sys",
".",... | Call all_ports_ready for a primitive operator. | [
"Call",
"all_ports_ready",
"for",
"a",
"primitive",
"operator",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/runtime.py#L127-L137 | train | 43,967 |
cmorisse/ikp3db | ikp3db.py | IKPdbConnectionHandler.receive | def receive(self, ikpdb):
"""Waits for a message from the debugger and returns it as a dict.
"""
# with self._connection_lock:
while self._network_loop:
_logger.n_debug("Enter socket.recv(%s) with self._received_data = %s",
self.SOCKET_BUFFER_SIZE,
self._received_data)
try:
# We may land here with a full packet already in self.received_data
# In that case we must not enter recv()
if self.SOCKET_BUFFER_SIZE:
data = self._connection.recv(self.SOCKET_BUFFER_SIZE)
else:
data = b''
_logger.n_debug("Socket.recv(%s) => %s", self.SOCKET_BUFFER_SIZE, data)
except socket.timeout:
_logger.n_debug("socket.timeout witk ikpdb.status=%s", ikpdb.status)
if ikpdb.status == 'terminated':
_logger.n_debug("breaking IKPdbConnectionHandler.receive() "
"network loop as ikpdb state is 'terminated'.")
return {
'command': '_InternalQuit',
'args':{}
}
continue
except socket.error as socket_err:
if ikpdb.status == 'terminated':
return {'command': '_InternalQuit',
'args':{'socket_error_number': socket_err.errno,
'socket_error_str': socket_err.strerror}}
continue
except Exception as exc:
_logger.g_error("Unexecpected Error: '%s' in IKPdbConnectionHandler"
".command_loop.", exc)
_logger.g_error(traceback.format_exc())
print("".join(traceback.format_stack()))
return {
'command': '_InternalQuit',
'args':{
"error": exc.__class__.__name__,
"message": exc.message
}
}
# received data is utf8 encoded
self._received_data += data.decode('utf-8')
# have we received a MAGIC_CODE
try:
magic_code_idx = self._received_data.index(self.MAGIC_CODE)
except ValueError:
continue
# Have we received a 'length='
try:
length_idx = self._received_data.index(u'length=')
except ValueError:
continue
# extract length content from received data
json_length = int(self._received_data[length_idx + 7:magic_code_idx])
message_length = magic_code_idx + len(self.MAGIC_CODE) + json_length
if message_length <= len(self._received_data):
full_message = self._received_data[:message_length]
self._received_data = self._received_data[message_length:]
if len(self._received_data) > 0:
self.SOCKET_BUFFER_SIZE = 0
else:
self.SOCKET_BUFFER_SIZE = 4096
break
else:
self.SOCKET_BUFFER_SIZE = message_length - len(self._received_data)
self.log_received(full_message)
obj = self.decode(full_message)
return obj | python | def receive(self, ikpdb):
"""Waits for a message from the debugger and returns it as a dict.
"""
# with self._connection_lock:
while self._network_loop:
_logger.n_debug("Enter socket.recv(%s) with self._received_data = %s",
self.SOCKET_BUFFER_SIZE,
self._received_data)
try:
# We may land here with a full packet already in self.received_data
# In that case we must not enter recv()
if self.SOCKET_BUFFER_SIZE:
data = self._connection.recv(self.SOCKET_BUFFER_SIZE)
else:
data = b''
_logger.n_debug("Socket.recv(%s) => %s", self.SOCKET_BUFFER_SIZE, data)
except socket.timeout:
_logger.n_debug("socket.timeout witk ikpdb.status=%s", ikpdb.status)
if ikpdb.status == 'terminated':
_logger.n_debug("breaking IKPdbConnectionHandler.receive() "
"network loop as ikpdb state is 'terminated'.")
return {
'command': '_InternalQuit',
'args':{}
}
continue
except socket.error as socket_err:
if ikpdb.status == 'terminated':
return {'command': '_InternalQuit',
'args':{'socket_error_number': socket_err.errno,
'socket_error_str': socket_err.strerror}}
continue
except Exception as exc:
_logger.g_error("Unexecpected Error: '%s' in IKPdbConnectionHandler"
".command_loop.", exc)
_logger.g_error(traceback.format_exc())
print("".join(traceback.format_stack()))
return {
'command': '_InternalQuit',
'args':{
"error": exc.__class__.__name__,
"message": exc.message
}
}
# received data is utf8 encoded
self._received_data += data.decode('utf-8')
# have we received a MAGIC_CODE
try:
magic_code_idx = self._received_data.index(self.MAGIC_CODE)
except ValueError:
continue
# Have we received a 'length='
try:
length_idx = self._received_data.index(u'length=')
except ValueError:
continue
# extract length content from received data
json_length = int(self._received_data[length_idx + 7:magic_code_idx])
message_length = magic_code_idx + len(self.MAGIC_CODE) + json_length
if message_length <= len(self._received_data):
full_message = self._received_data[:message_length]
self._received_data = self._received_data[message_length:]
if len(self._received_data) > 0:
self.SOCKET_BUFFER_SIZE = 0
else:
self.SOCKET_BUFFER_SIZE = 4096
break
else:
self.SOCKET_BUFFER_SIZE = message_length - len(self._received_data)
self.log_received(full_message)
obj = self.decode(full_message)
return obj | [
"def",
"receive",
"(",
"self",
",",
"ikpdb",
")",
":",
"# with self._connection_lock:",
"while",
"self",
".",
"_network_loop",
":",
"_logger",
".",
"n_debug",
"(",
"\"Enter socket.recv(%s) with self._received_data = %s\"",
",",
"self",
".",
"SOCKET_BUFFER_SIZE",
",",
... | Waits for a message from the debugger and returns it as a dict. | [
"Waits",
"for",
"a",
"message",
"from",
"the",
"debugger",
"and",
"returns",
"it",
"as",
"a",
"dict",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L312-L391 | train | 43,968 |
cmorisse/ikp3db | ikp3db.py | IKBreakpoint.clear | def clear(self):
""" Clear a breakpoint by removing it from all lists.
"""
del IKBreakpoint.breakpoints_by_file_and_line[self.file_name, self.line_number]
IKBreakpoint.breakpoints_by_number[self.number] = None
IKBreakpoint.breakpoints_files[self.file_name].remove(self.line_number)
if len(IKBreakpoint.breakpoints_files[self.file_name]) == 0:
del IKBreakpoint.breakpoints_files[self.file_name]
IKBreakpoint.update_active_breakpoint_flag() | python | def clear(self):
""" Clear a breakpoint by removing it from all lists.
"""
del IKBreakpoint.breakpoints_by_file_and_line[self.file_name, self.line_number]
IKBreakpoint.breakpoints_by_number[self.number] = None
IKBreakpoint.breakpoints_files[self.file_name].remove(self.line_number)
if len(IKBreakpoint.breakpoints_files[self.file_name]) == 0:
del IKBreakpoint.breakpoints_files[self.file_name]
IKBreakpoint.update_active_breakpoint_flag() | [
"def",
"clear",
"(",
"self",
")",
":",
"del",
"IKBreakpoint",
".",
"breakpoints_by_file_and_line",
"[",
"self",
".",
"file_name",
",",
"self",
".",
"line_number",
"]",
"IKBreakpoint",
".",
"breakpoints_by_number",
"[",
"self",
".",
"number",
"]",
"=",
"None",
... | Clear a breakpoint by removing it from all lists. | [
"Clear",
"a",
"breakpoint",
"by",
"removing",
"it",
"from",
"all",
"lists",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L473-L481 | train | 43,969 |
cmorisse/ikp3db | ikp3db.py | IKBreakpoint.update_active_breakpoint_flag | def update_active_breakpoint_flag(cls):
""" Checks all breakpoints to find wether at least one is active and
update `any_active_breakpoint` accordingly.
"""
cls.any_active_breakpoint=any([bp.enabled for bp in cls.breakpoints_by_number if bp]) | python | def update_active_breakpoint_flag(cls):
""" Checks all breakpoints to find wether at least one is active and
update `any_active_breakpoint` accordingly.
"""
cls.any_active_breakpoint=any([bp.enabled for bp in cls.breakpoints_by_number if bp]) | [
"def",
"update_active_breakpoint_flag",
"(",
"cls",
")",
":",
"cls",
".",
"any_active_breakpoint",
"=",
"any",
"(",
"[",
"bp",
".",
"enabled",
"for",
"bp",
"in",
"cls",
".",
"breakpoints_by_number",
"if",
"bp",
"]",
")"
] | Checks all breakpoints to find wether at least one is active and
update `any_active_breakpoint` accordingly. | [
"Checks",
"all",
"breakpoints",
"to",
"find",
"wether",
"at",
"least",
"one",
"is",
"active",
"and",
"update",
"any_active_breakpoint",
"accordingly",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L484-L488 | train | 43,970 |
cmorisse/ikp3db | ikp3db.py | IKBreakpoint.disable_all_breakpoints | def disable_all_breakpoints(cls):
""" Disable all breakpoints and udate `active_breakpoint_flag`.
"""
for bp in cls.breakpoints_by_number:
if bp: # breakpoint #0 exists and is always None
bp.enabled = False
cls.update_active_breakpoint_flag()
return | python | def disable_all_breakpoints(cls):
""" Disable all breakpoints and udate `active_breakpoint_flag`.
"""
for bp in cls.breakpoints_by_number:
if bp: # breakpoint #0 exists and is always None
bp.enabled = False
cls.update_active_breakpoint_flag()
return | [
"def",
"disable_all_breakpoints",
"(",
"cls",
")",
":",
"for",
"bp",
"in",
"cls",
".",
"breakpoints_by_number",
":",
"if",
"bp",
":",
"# breakpoint #0 exists and is always None",
"bp",
".",
"enabled",
"=",
"False",
"cls",
".",
"update_active_breakpoint_flag",
"(",
... | Disable all breakpoints and udate `active_breakpoint_flag`. | [
"Disable",
"all",
"breakpoints",
"and",
"udate",
"active_breakpoint_flag",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L537-L544 | train | 43,971 |
cmorisse/ikp3db | ikp3db.py | IKBreakpoint.backup_breakpoints_state | def backup_breakpoints_state(cls):
""" Returns the state of all breakpoints in a list that can be used
later to restore all breakpoints state"""
all_breakpoints_state = []
for bp in cls.breakpoints_by_number:
if bp:
all_breakpoints_state.append((bp.number,
bp.enabled,
bp.condition,))
return all_breakpoints_state | python | def backup_breakpoints_state(cls):
""" Returns the state of all breakpoints in a list that can be used
later to restore all breakpoints state"""
all_breakpoints_state = []
for bp in cls.breakpoints_by_number:
if bp:
all_breakpoints_state.append((bp.number,
bp.enabled,
bp.condition,))
return all_breakpoints_state | [
"def",
"backup_breakpoints_state",
"(",
"cls",
")",
":",
"all_breakpoints_state",
"=",
"[",
"]",
"for",
"bp",
"in",
"cls",
".",
"breakpoints_by_number",
":",
"if",
"bp",
":",
"all_breakpoints_state",
".",
"append",
"(",
"(",
"bp",
".",
"number",
",",
"bp",
... | Returns the state of all breakpoints in a list that can be used
later to restore all breakpoints state | [
"Returns",
"the",
"state",
"of",
"all",
"breakpoints",
"in",
"a",
"list",
"that",
"can",
"be",
"used",
"later",
"to",
"restore",
"all",
"breakpoints",
"state"
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L547-L556 | train | 43,972 |
cmorisse/ikp3db | ikp3db.py | IKPdb.canonic | def canonic(self, file_name):
""" returns canonical version of a file name.
A canonical file name is an absolute, lowercase normalized path
to a given file.
"""
if file_name == "<" + file_name[1:-1] + ">":
return file_name
c_file_name = self.file_name_cache.get(file_name)
if not c_file_name:
c_file_name = os.path.abspath(file_name)
c_file_name = os.path.normcase(c_file_name)
self.file_name_cache[file_name] = c_file_name
return c_file_name | python | def canonic(self, file_name):
""" returns canonical version of a file name.
A canonical file name is an absolute, lowercase normalized path
to a given file.
"""
if file_name == "<" + file_name[1:-1] + ">":
return file_name
c_file_name = self.file_name_cache.get(file_name)
if not c_file_name:
c_file_name = os.path.abspath(file_name)
c_file_name = os.path.normcase(c_file_name)
self.file_name_cache[file_name] = c_file_name
return c_file_name | [
"def",
"canonic",
"(",
"self",
",",
"file_name",
")",
":",
"if",
"file_name",
"==",
"\"<\"",
"+",
"file_name",
"[",
"1",
":",
"-",
"1",
"]",
"+",
"\">\"",
":",
"return",
"file_name",
"c_file_name",
"=",
"self",
".",
"file_name_cache",
".",
"get",
"(",
... | returns canonical version of a file name.
A canonical file name is an absolute, lowercase normalized path
to a given file. | [
"returns",
"canonical",
"version",
"of",
"a",
"file",
"name",
".",
"A",
"canonical",
"file",
"name",
"is",
"an",
"absolute",
"lowercase",
"normalized",
"path",
"to",
"a",
"given",
"file",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L645-L657 | train | 43,973 |
cmorisse/ikp3db | ikp3db.py | IKPdb.object_properties_count | def object_properties_count(self, o):
""" returns the number of user browsable properties of an object. """
o_type = type(o)
if isinstance(o, (dict, list, tuple, set)):
return len(o)
elif isinstance(o, (type(None), bool, float,
str, int,
bytes, types.ModuleType,
types.MethodType, types.FunctionType)):
return 0
else:
# Following lines are used to debug variables members browsing
# and counting
# if False and str(o_type) == "<class 'socket._socketobject'>":
# print "@378"
# print dir(o)
# print "hasattr(o, '__dict__')=%s" % hasattr(o,'__dict__')
# count = 0
# if hasattr(o, '__dict__'):
# for m_name, m_value in o.__dict__.iteritems():
# if m_name.startswith('__'):
# print " %s=>False" % (m_name,)
# continue
# if type(m_value) in (types.ModuleType, types.MethodType, types.FunctionType,):
# print " %s=>False" % (m_name,)
# continue
# print " %s=>True" % (m_name,)
# count +=1
# print " %s => %s = %s" % (o, count, dir(o),)
# else:
try:
if hasattr(o, '__dict__'):
count = len([m_name for m_name, m_value in o.__dict__.items()
if not m_name.startswith('__')
and not type(m_value) in (types.ModuleType,
types.MethodType,
types.FunctionType,) ])
else:
count = 0
except:
# Thank you werkzeug __getattr__ overloading!
count = 0
return count | python | def object_properties_count(self, o):
""" returns the number of user browsable properties of an object. """
o_type = type(o)
if isinstance(o, (dict, list, tuple, set)):
return len(o)
elif isinstance(o, (type(None), bool, float,
str, int,
bytes, types.ModuleType,
types.MethodType, types.FunctionType)):
return 0
else:
# Following lines are used to debug variables members browsing
# and counting
# if False and str(o_type) == "<class 'socket._socketobject'>":
# print "@378"
# print dir(o)
# print "hasattr(o, '__dict__')=%s" % hasattr(o,'__dict__')
# count = 0
# if hasattr(o, '__dict__'):
# for m_name, m_value in o.__dict__.iteritems():
# if m_name.startswith('__'):
# print " %s=>False" % (m_name,)
# continue
# if type(m_value) in (types.ModuleType, types.MethodType, types.FunctionType,):
# print " %s=>False" % (m_name,)
# continue
# print " %s=>True" % (m_name,)
# count +=1
# print " %s => %s = %s" % (o, count, dir(o),)
# else:
try:
if hasattr(o, '__dict__'):
count = len([m_name for m_name, m_value in o.__dict__.items()
if not m_name.startswith('__')
and not type(m_value) in (types.ModuleType,
types.MethodType,
types.FunctionType,) ])
else:
count = 0
except:
# Thank you werkzeug __getattr__ overloading!
count = 0
return count | [
"def",
"object_properties_count",
"(",
"self",
",",
"o",
")",
":",
"o_type",
"=",
"type",
"(",
"o",
")",
"if",
"isinstance",
"(",
"o",
",",
"(",
"dict",
",",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"len",
"(",
"o",
")",
"elif",... | returns the number of user browsable properties of an object. | [
"returns",
"the",
"number",
"of",
"user",
"browsable",
"properties",
"of",
"an",
"object",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L722-L764 | train | 43,974 |
cmorisse/ikp3db | ikp3db.py | IKPdb.evaluate | def evaluate(self, frame_id, expression, global_context=False, disable_break=False):
"""Evaluates 'expression' in the context of the frame identified by
'frame_id' or globally.
Breakpoints are disabled depending on 'disable_break' value.
Returns a tuple of value and type both as str.
Note that - depending on the CGI_ESCAPE_EVALUATE_OUTPUT attribute - value is
escaped.
"""
if disable_break:
breakpoints_backup = IKBreakpoint.backup_breakpoints_state()
IKBreakpoint.disable_all_breakpoints()
if frame_id and not global_context:
eval_frame = ctypes.cast(frame_id, ctypes.py_object).value
global_vars = eval_frame.f_globals
local_vars = eval_frame.f_locals
else:
global_vars = None
local_vars = None
try:
result = eval(expression, global_vars, local_vars)
result_type = IKPdbRepr(result)
result_value = repr(result)
except SyntaxError:
# eval() failed, try with exec to handle statements
try:
result = exec(expression, global_vars, local_vars)
result_type = IKPdbRepr(result)
result_value = repr(result)
except Exception as e:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = str(t.__name__)
result_value = "%s: %s" % (result_type, result,)
except:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = t.__name__
result_value = "%s: %s" % (result_type, result,)
if disable_break:
IKBreakpoint.restore_breakpoints_state(breakpoints_backup)
_logger.e_debug("evaluate(%s) => result_value=%s, result_type=%s, result=%s",
expression,
result_value,
result_type,
result)
if self.CGI_ESCAPE_EVALUATE_OUTPUT:
result_value = cgi.escape(result_value)
# We must check that result is json.dump compatible so that it can be sent back to client.
try:
json.dumps(result_value)
except:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = t.__name__
result_value = "<plaintext>%s: IKP3db is unable to JSON encode result to send it to "\
"debugging client.\n"\
" This typically occurs if you try to print a string that cannot be"\
" decoded to 'UTF-8'.\n"\
" You should be able to evaluate result and inspect it's content"\
" by removing the print statement." % result_type
return result_value, result_type | python | def evaluate(self, frame_id, expression, global_context=False, disable_break=False):
"""Evaluates 'expression' in the context of the frame identified by
'frame_id' or globally.
Breakpoints are disabled depending on 'disable_break' value.
Returns a tuple of value and type both as str.
Note that - depending on the CGI_ESCAPE_EVALUATE_OUTPUT attribute - value is
escaped.
"""
if disable_break:
breakpoints_backup = IKBreakpoint.backup_breakpoints_state()
IKBreakpoint.disable_all_breakpoints()
if frame_id and not global_context:
eval_frame = ctypes.cast(frame_id, ctypes.py_object).value
global_vars = eval_frame.f_globals
local_vars = eval_frame.f_locals
else:
global_vars = None
local_vars = None
try:
result = eval(expression, global_vars, local_vars)
result_type = IKPdbRepr(result)
result_value = repr(result)
except SyntaxError:
# eval() failed, try with exec to handle statements
try:
result = exec(expression, global_vars, local_vars)
result_type = IKPdbRepr(result)
result_value = repr(result)
except Exception as e:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = str(t.__name__)
result_value = "%s: %s" % (result_type, result,)
except:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = t.__name__
result_value = "%s: %s" % (result_type, result,)
if disable_break:
IKBreakpoint.restore_breakpoints_state(breakpoints_backup)
_logger.e_debug("evaluate(%s) => result_value=%s, result_type=%s, result=%s",
expression,
result_value,
result_type,
result)
if self.CGI_ESCAPE_EVALUATE_OUTPUT:
result_value = cgi.escape(result_value)
# We must check that result is json.dump compatible so that it can be sent back to client.
try:
json.dumps(result_value)
except:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = t.__name__
result_value = "<plaintext>%s: IKP3db is unable to JSON encode result to send it to "\
"debugging client.\n"\
" This typically occurs if you try to print a string that cannot be"\
" decoded to 'UTF-8'.\n"\
" You should be able to evaluate result and inspect it's content"\
" by removing the print statement." % result_type
return result_value, result_type | [
"def",
"evaluate",
"(",
"self",
",",
"frame_id",
",",
"expression",
",",
"global_context",
"=",
"False",
",",
"disable_break",
"=",
"False",
")",
":",
"if",
"disable_break",
":",
"breakpoints_backup",
"=",
"IKBreakpoint",
".",
"backup_breakpoints_state",
"(",
")... | Evaluates 'expression' in the context of the frame identified by
'frame_id' or globally.
Breakpoints are disabled depending on 'disable_break' value.
Returns a tuple of value and type both as str.
Note that - depending on the CGI_ESCAPE_EVALUATE_OUTPUT attribute - value is
escaped. | [
"Evaluates",
"expression",
"in",
"the",
"context",
"of",
"the",
"frame",
"identified",
"by",
"frame_id",
"or",
"globally",
".",
"Breakpoints",
"are",
"disabled",
"depending",
"on",
"disable_break",
"value",
".",
"Returns",
"a",
"tuple",
"of",
"value",
"and",
"... | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L922-L993 | train | 43,975 |
cmorisse/ikp3db | ikp3db.py | IKPdb.let_variable | def let_variable(self, frame_id, var_name, expression_value):
""" Let a frame's var with a value by building then eval a let
expression with breakoints disabled.
"""
breakpoints_backup = IKBreakpoint.backup_breakpoints_state()
IKBreakpoint.disable_all_breakpoints()
let_expression = "%s=%s" % (var_name, expression_value,)
eval_frame = ctypes.cast(frame_id, ctypes.py_object).value
global_vars = eval_frame.f_globals
local_vars = eval_frame.f_locals
try:
exec(let_expression, global_vars, local_vars)
error_message=""
except Exception as e:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = str(t.__name__)
error_message = "%s: %s" % (result_type, result,)
IKBreakpoint.restore_breakpoints_state(breakpoints_backup)
_logger.e_debug("let_variable(%s) => %s",
let_expression,
error_message or 'succeed')
return error_message | python | def let_variable(self, frame_id, var_name, expression_value):
""" Let a frame's var with a value by building then eval a let
expression with breakoints disabled.
"""
breakpoints_backup = IKBreakpoint.backup_breakpoints_state()
IKBreakpoint.disable_all_breakpoints()
let_expression = "%s=%s" % (var_name, expression_value,)
eval_frame = ctypes.cast(frame_id, ctypes.py_object).value
global_vars = eval_frame.f_globals
local_vars = eval_frame.f_locals
try:
exec(let_expression, global_vars, local_vars)
error_message=""
except Exception as e:
t, result = sys.exc_info()[:2]
if isinstance(t, str):
result_type = t
else:
result_type = str(t.__name__)
error_message = "%s: %s" % (result_type, result,)
IKBreakpoint.restore_breakpoints_state(breakpoints_backup)
_logger.e_debug("let_variable(%s) => %s",
let_expression,
error_message or 'succeed')
return error_message | [
"def",
"let_variable",
"(",
"self",
",",
"frame_id",
",",
"var_name",
",",
"expression_value",
")",
":",
"breakpoints_backup",
"=",
"IKBreakpoint",
".",
"backup_breakpoints_state",
"(",
")",
"IKBreakpoint",
".",
"disable_all_breakpoints",
"(",
")",
"let_expression",
... | Let a frame's var with a value by building then eval a let
expression with breakoints disabled. | [
"Let",
"a",
"frame",
"s",
"var",
"with",
"a",
"value",
"by",
"building",
"then",
"eval",
"a",
"let",
"expression",
"with",
"breakoints",
"disabled",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L995-L1023 | train | 43,976 |
cmorisse/ikp3db | ikp3db.py | IKPdb.setup_step_into | def setup_step_into(self, frame, pure=False):
"""Setup debugger for a "stepInto"
"""
self.frame_calling = frame
if pure:
self.frame_stop = None
else:
self.frame_stop = frame
self.frame_return = None
self.frame_suspend = False
self.pending_stop = True
return | python | def setup_step_into(self, frame, pure=False):
"""Setup debugger for a "stepInto"
"""
self.frame_calling = frame
if pure:
self.frame_stop = None
else:
self.frame_stop = frame
self.frame_return = None
self.frame_suspend = False
self.pending_stop = True
return | [
"def",
"setup_step_into",
"(",
"self",
",",
"frame",
",",
"pure",
"=",
"False",
")",
":",
"self",
".",
"frame_calling",
"=",
"frame",
"if",
"pure",
":",
"self",
".",
"frame_stop",
"=",
"None",
"else",
":",
"self",
".",
"frame_stop",
"=",
"frame",
"self... | Setup debugger for a "stepInto" | [
"Setup",
"debugger",
"for",
"a",
"stepInto"
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1035-L1046 | train | 43,977 |
cmorisse/ikp3db | ikp3db.py | IKPdb.setup_step_out | def setup_step_out(self, frame):
"""Setup debugger for a "stepOut"
"""
self.frame_calling = None
self.frame_stop = None
self.frame_return = frame.f_back
self.frame_suspend = False
self.pending_stop = True
return | python | def setup_step_out(self, frame):
"""Setup debugger for a "stepOut"
"""
self.frame_calling = None
self.frame_stop = None
self.frame_return = frame.f_back
self.frame_suspend = False
self.pending_stop = True
return | [
"def",
"setup_step_out",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"frame_calling",
"=",
"None",
"self",
".",
"frame_stop",
"=",
"None",
"self",
".",
"frame_return",
"=",
"frame",
".",
"f_back",
"self",
".",
"frame_suspend",
"=",
"False",
"self",
... | Setup debugger for a "stepOut" | [
"Setup",
"debugger",
"for",
"a",
"stepOut"
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1048-L1056 | train | 43,978 |
cmorisse/ikp3db | ikp3db.py | IKPdb.setup_suspend | def setup_suspend(self):
"""Setup debugger to "suspend" execution
"""
self.frame_calling = None
self.frame_stop = None
self.frame_return = None
self.frame_suspend = True
self.pending_stop = True
self.enable_tracing()
return | python | def setup_suspend(self):
"""Setup debugger to "suspend" execution
"""
self.frame_calling = None
self.frame_stop = None
self.frame_return = None
self.frame_suspend = True
self.pending_stop = True
self.enable_tracing()
return | [
"def",
"setup_suspend",
"(",
"self",
")",
":",
"self",
".",
"frame_calling",
"=",
"None",
"self",
".",
"frame_stop",
"=",
"None",
"self",
".",
"frame_return",
"=",
"None",
"self",
".",
"frame_suspend",
"=",
"True",
"self",
".",
"pending_stop",
"=",
"True",... | Setup debugger to "suspend" execution | [
"Setup",
"debugger",
"to",
"suspend",
"execution"
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1058-L1067 | train | 43,979 |
cmorisse/ikp3db | ikp3db.py | IKPdb.setup_resume | def setup_resume(self):
""" Setup debugger to "resume" execution
"""
self.frame_calling = None
self.frame_stop = None
self.frame_return = None
self.frame_suspend = False
self.pending_stop = False
if not IKBreakpoint.any_active_breakpoint:
self.disable_tracing()
return | python | def setup_resume(self):
""" Setup debugger to "resume" execution
"""
self.frame_calling = None
self.frame_stop = None
self.frame_return = None
self.frame_suspend = False
self.pending_stop = False
if not IKBreakpoint.any_active_breakpoint:
self.disable_tracing()
return | [
"def",
"setup_resume",
"(",
"self",
")",
":",
"self",
".",
"frame_calling",
"=",
"None",
"self",
".",
"frame_stop",
"=",
"None",
"self",
".",
"frame_return",
"=",
"None",
"self",
".",
"frame_suspend",
"=",
"False",
"self",
".",
"pending_stop",
"=",
"False"... | Setup debugger to "resume" execution | [
"Setup",
"debugger",
"to",
"resume",
"execution"
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1069-L1079 | train | 43,980 |
cmorisse/ikp3db | ikp3db.py | IKPdb.should_stop_here | def should_stop_here(self, frame):
""" Called by dispatch function to check wether debugger must stop at
this frame.
Note that we test 'step into' first to give a chance to 'stepOver' in
case user click on 'stepInto' on a 'no call' line.
"""
# TODO: Optimization => defines a set of modules / names where _tracer
# is never registered. This will replace skip
#if self.skip and self.is_skipped_module(frame.f_globals.get('__name__')):
# return False
# step into
if self.frame_calling and self.frame_calling==frame.f_back:
return True
# step over
if frame==self.frame_stop: # frame cannot be null
return True
# step out
if frame==self.frame_return: # frame cannot be null
return True
# suspend
if self.frame_suspend:
return True
return False | python | def should_stop_here(self, frame):
""" Called by dispatch function to check wether debugger must stop at
this frame.
Note that we test 'step into' first to give a chance to 'stepOver' in
case user click on 'stepInto' on a 'no call' line.
"""
# TODO: Optimization => defines a set of modules / names where _tracer
# is never registered. This will replace skip
#if self.skip and self.is_skipped_module(frame.f_globals.get('__name__')):
# return False
# step into
if self.frame_calling and self.frame_calling==frame.f_back:
return True
# step over
if frame==self.frame_stop: # frame cannot be null
return True
# step out
if frame==self.frame_return: # frame cannot be null
return True
# suspend
if self.frame_suspend:
return True
return False | [
"def",
"should_stop_here",
"(",
"self",
",",
"frame",
")",
":",
"# TODO: Optimization => defines a set of modules / names where _tracer",
"# is never registered. This will replace skip",
"#if self.skip and self.is_skipped_module(frame.f_globals.get('__name__')):",
"# return False",
"# ste... | Called by dispatch function to check wether debugger must stop at
this frame.
Note that we test 'step into' first to give a chance to 'stepOver' in
case user click on 'stepInto' on a 'no call' line. | [
"Called",
"by",
"dispatch",
"function",
"to",
"check",
"wether",
"debugger",
"must",
"stop",
"at",
"this",
"frame",
".",
"Note",
"that",
"we",
"test",
"step",
"into",
"first",
"to",
"give",
"a",
"chance",
"to",
"stepOver",
"in",
"case",
"user",
"click",
... | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1089-L1113 | train | 43,981 |
cmorisse/ikp3db | ikp3db.py | IKPdb.should_break_here | def should_break_here(self, frame):
"""Check wether there is a breakpoint at this frame."""
# Next line commented out for performance
#_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s",
# frame.f_code.co_filename,
# frame.f_lineno,
# IKBreakpoint.breakpoints_by_number)
c_file_name = self.canonic(frame.f_code.co_filename)
if not c_file_name in IKBreakpoint.breakpoints_files:
return False
bp = IKBreakpoint.lookup_effective_breakpoint(c_file_name,
frame.f_lineno,
frame)
return True if bp else False | python | def should_break_here(self, frame):
"""Check wether there is a breakpoint at this frame."""
# Next line commented out for performance
#_logger.b_debug("should_break_here(filename=%s, lineno=%s) with breaks=%s",
# frame.f_code.co_filename,
# frame.f_lineno,
# IKBreakpoint.breakpoints_by_number)
c_file_name = self.canonic(frame.f_code.co_filename)
if not c_file_name in IKBreakpoint.breakpoints_files:
return False
bp = IKBreakpoint.lookup_effective_breakpoint(c_file_name,
frame.f_lineno,
frame)
return True if bp else False | [
"def",
"should_break_here",
"(",
"self",
",",
"frame",
")",
":",
"# Next line commented out for performance",
"#_logger.b_debug(\"should_break_here(filename=%s, lineno=%s) with breaks=%s\",",
"# frame.f_code.co_filename,",
"# frame.f_lineno,",
"# ... | Check wether there is a breakpoint at this frame. | [
"Check",
"wether",
"there",
"is",
"a",
"breakpoint",
"at",
"this",
"frame",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1115-L1129 | train | 43,982 |
cmorisse/ikp3db | ikp3db.py | IKPdb.get_threads | def get_threads(self):
"""Returns a dict of all threads and indicates thread being debugged.
key is thread ident and values thread info.
Information from this list can be used to swap thread being debugged.
"""
thread_list = {}
for thread in threading.enumerate():
thread_ident = thread.ident
thread_list[thread_ident] = {
"ident": thread_ident,
"name": thread.name,
"is_debugger": thread_ident == self.debugger_thread_ident,
"is_debugged": thread_ident == self.debugged_thread_ident
}
return thread_list | python | def get_threads(self):
"""Returns a dict of all threads and indicates thread being debugged.
key is thread ident and values thread info.
Information from this list can be used to swap thread being debugged.
"""
thread_list = {}
for thread in threading.enumerate():
thread_ident = thread.ident
thread_list[thread_ident] = {
"ident": thread_ident,
"name": thread.name,
"is_debugger": thread_ident == self.debugger_thread_ident,
"is_debugged": thread_ident == self.debugged_thread_ident
}
return thread_list | [
"def",
"get_threads",
"(",
"self",
")",
":",
"thread_list",
"=",
"{",
"}",
"for",
"thread",
"in",
"threading",
".",
"enumerate",
"(",
")",
":",
"thread_ident",
"=",
"thread",
".",
"ident",
"thread_list",
"[",
"thread_ident",
"]",
"=",
"{",
"\"ident\"",
"... | Returns a dict of all threads and indicates thread being debugged.
key is thread ident and values thread info.
Information from this list can be used to swap thread being debugged. | [
"Returns",
"a",
"dict",
"of",
"all",
"threads",
"and",
"indicates",
"thread",
"being",
"debugged",
".",
"key",
"is",
"thread",
"ident",
"and",
"values",
"thread",
"info",
".",
"Information",
"from",
"this",
"list",
"can",
"be",
"used",
"to",
"swap",
"threa... | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1131-L1145 | train | 43,983 |
cmorisse/ikp3db | ikp3db.py | IKPdb.set_debugged_thread | def set_debugged_thread(self, target_thread_ident=None):
""" Allows to reset or set the thread to debug. """
if target_thread_ident is None:
self.debugged_thread_ident = None
self.debugged_thread_name = ''
return {
"result": self.get_threads(),
"error": ""
}
thread_list = self.get_threads()
if target_thread_ident not in thread_list:
return {
"result": None,
"error": "No thread with ident:%s." % target_thread_ident
}
if thread_list[target_thread_ident]['is_debugger']:
return {
"result": None,
"error": "Cannot debug IKPdb tracer (sadly...)."
}
self.debugged_thread_ident = target_thread_ident
self.debugged_thread_name = thread_list[target_thread_ident]['name']
return {
"result": self.get_threads(),
"error": ""
} | python | def set_debugged_thread(self, target_thread_ident=None):
""" Allows to reset or set the thread to debug. """
if target_thread_ident is None:
self.debugged_thread_ident = None
self.debugged_thread_name = ''
return {
"result": self.get_threads(),
"error": ""
}
thread_list = self.get_threads()
if target_thread_ident not in thread_list:
return {
"result": None,
"error": "No thread with ident:%s." % target_thread_ident
}
if thread_list[target_thread_ident]['is_debugger']:
return {
"result": None,
"error": "Cannot debug IKPdb tracer (sadly...)."
}
self.debugged_thread_ident = target_thread_ident
self.debugged_thread_name = thread_list[target_thread_ident]['name']
return {
"result": self.get_threads(),
"error": ""
} | [
"def",
"set_debugged_thread",
"(",
"self",
",",
"target_thread_ident",
"=",
"None",
")",
":",
"if",
"target_thread_ident",
"is",
"None",
":",
"self",
".",
"debugged_thread_ident",
"=",
"None",
"self",
".",
"debugged_thread_name",
"=",
"''",
"return",
"{",
"\"res... | Allows to reset or set the thread to debug. | [
"Allows",
"to",
"reset",
"or",
"set",
"the",
"thread",
"to",
"debug",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1148-L1176 | train | 43,984 |
cmorisse/ikp3db | ikp3db.py | IKPdb.dump_tracing_state | def dump_tracing_state(self, context):
""" A debug tool to dump all threads tracing state
"""
_logger.x_debug("Dumping all threads Tracing state: (%s)" % context)
_logger.x_debug(" self.tracing_enabled=%s" % self.tracing_enabled)
_logger.x_debug(" self.execution_started=%s" % self.execution_started)
_logger.x_debug(" self.status=%s" % self.status)
_logger.x_debug(" self.frame_beginning=%s" % self.frame_beginning)
_logger.x_debug(" self.debugger_thread_ident=%s" % self.debugger_thread_ident)
if False:
for thr in threading.enumerate():
is_current_thread = thr.ident == threading.current_thread().ident
_logger.x_debug(" Thread: %s, %s %s" % (thr.name, thr.ident, "<= Current*" if is_current_thread else ''))
a_frame = sys._current_frames()[thr.ident]
while a_frame:
flags = []
if a_frame == self.frame_beginning:
flags.append("beginning")
if a_frame == inspect.currentframe():
flags.append("current")
if flags:
flags_str = "**"+",".join(flags)
else:
flags_str = ""
_logger.x_debug(" => %s, %s:%s(%s) | %s %s" % (a_frame,
a_frame.f_code.co_filename,
a_frame.f_lineno,
a_frame.f_code.co_name,
a_frame.f_trace,
flags_str))
a_frame = a_frame.f_back | python | def dump_tracing_state(self, context):
""" A debug tool to dump all threads tracing state
"""
_logger.x_debug("Dumping all threads Tracing state: (%s)" % context)
_logger.x_debug(" self.tracing_enabled=%s" % self.tracing_enabled)
_logger.x_debug(" self.execution_started=%s" % self.execution_started)
_logger.x_debug(" self.status=%s" % self.status)
_logger.x_debug(" self.frame_beginning=%s" % self.frame_beginning)
_logger.x_debug(" self.debugger_thread_ident=%s" % self.debugger_thread_ident)
if False:
for thr in threading.enumerate():
is_current_thread = thr.ident == threading.current_thread().ident
_logger.x_debug(" Thread: %s, %s %s" % (thr.name, thr.ident, "<= Current*" if is_current_thread else ''))
a_frame = sys._current_frames()[thr.ident]
while a_frame:
flags = []
if a_frame == self.frame_beginning:
flags.append("beginning")
if a_frame == inspect.currentframe():
flags.append("current")
if flags:
flags_str = "**"+",".join(flags)
else:
flags_str = ""
_logger.x_debug(" => %s, %s:%s(%s) | %s %s" % (a_frame,
a_frame.f_code.co_filename,
a_frame.f_lineno,
a_frame.f_code.co_name,
a_frame.f_trace,
flags_str))
a_frame = a_frame.f_back | [
"def",
"dump_tracing_state",
"(",
"self",
",",
"context",
")",
":",
"_logger",
".",
"x_debug",
"(",
"\"Dumping all threads Tracing state: (%s)\"",
"%",
"context",
")",
"_logger",
".",
"x_debug",
"(",
"\" self.tracing_enabled=%s\"",
"%",
"self",
".",
"tracing_enable... | A debug tool to dump all threads tracing state | [
"A",
"debug",
"tool",
"to",
"dump",
"all",
"threads",
"tracing",
"state"
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1353-L1383 | train | 43,985 |
cmorisse/ikp3db | ikp3db.py | IKPdb.disable_tracing | def disable_tracing(self):
""" Disable tracing if it is disabled and debugged program is running,
else do nothing.
:return: False if tracing has been disabled, True else.
"""
_logger.x_debug("disable_tracing()")
#self.dump_tracing_state("before disable_tracing()")
if self.tracing_enabled and self.execution_started:
threading.settrace(None) # don't trace threads to come
iksettrace3._set_trace_off()
self.tracing_enabled = False
#self.dump_tracing_state("after disable_tracing()")
return self.tracing_enabled | python | def disable_tracing(self):
""" Disable tracing if it is disabled and debugged program is running,
else do nothing.
:return: False if tracing has been disabled, True else.
"""
_logger.x_debug("disable_tracing()")
#self.dump_tracing_state("before disable_tracing()")
if self.tracing_enabled and self.execution_started:
threading.settrace(None) # don't trace threads to come
iksettrace3._set_trace_off()
self.tracing_enabled = False
#self.dump_tracing_state("after disable_tracing()")
return self.tracing_enabled | [
"def",
"disable_tracing",
"(",
"self",
")",
":",
"_logger",
".",
"x_debug",
"(",
"\"disable_tracing()\"",
")",
"#self.dump_tracing_state(\"before disable_tracing()\")",
"if",
"self",
".",
"tracing_enabled",
"and",
"self",
".",
"execution_started",
":",
"threading",
".",... | Disable tracing if it is disabled and debugged program is running,
else do nothing.
:return: False if tracing has been disabled, True else. | [
"Disable",
"tracing",
"if",
"it",
"is",
"disabled",
"and",
"debugged",
"program",
"is",
"running",
"else",
"do",
"nothing",
"."
] | a0f318d4e8494b2e6f2f07ec0f1202ca023c920f | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1411-L1424 | train | 43,986 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | _ResourceElement._get_elements | def _get_elements(self, url, key, eclass, id=None, name=None):
"""Get elements matching `id` or `name`
Args:
url(str): url of children.
key(str): key in the returned JSON.
eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of.
id(str, optional): only return resources whose `id` property matches the given `id`
name(str, optional): only return resources whose `name` property matches the given `name`
Returns:
list(_ResourceElement): List of `eclass` instances
Raises:
ValueError: both `id` and `name` are specified together
"""
if id is not None and name is not None:
raise ValueError("id and name cannot specified together")
json_elements = self.rest_client.make_request(url)[key]
return [eclass(element, self.rest_client) for element in json_elements
if _exact_resource(element, id) and _matching_resource(element, name)] | python | def _get_elements(self, url, key, eclass, id=None, name=None):
"""Get elements matching `id` or `name`
Args:
url(str): url of children.
key(str): key in the returned JSON.
eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of.
id(str, optional): only return resources whose `id` property matches the given `id`
name(str, optional): only return resources whose `name` property matches the given `name`
Returns:
list(_ResourceElement): List of `eclass` instances
Raises:
ValueError: both `id` and `name` are specified together
"""
if id is not None and name is not None:
raise ValueError("id and name cannot specified together")
json_elements = self.rest_client.make_request(url)[key]
return [eclass(element, self.rest_client) for element in json_elements
if _exact_resource(element, id) and _matching_resource(element, name)] | [
"def",
"_get_elements",
"(",
"self",
",",
"url",
",",
"key",
",",
"eclass",
",",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"id",
"is",
"not",
"None",
"and",
"name",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"id and ... | Get elements matching `id` or `name`
Args:
url(str): url of children.
key(str): key in the returned JSON.
eclass(subclass type of :py:class:`_ResourceElement`): element class to create instances of.
id(str, optional): only return resources whose `id` property matches the given `id`
name(str, optional): only return resources whose `name` property matches the given `name`
Returns:
list(_ResourceElement): List of `eclass` instances
Raises:
ValueError: both `id` and `name` are specified together | [
"Get",
"elements",
"matching",
"id",
"or",
"name"
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L113-L134 | train | 43,987 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | View.get_domain | def get_domain(self):
"""Get the Streams domain for the instance that owns this view.
Returns:
Domain: Streams domain for the instance owning this view.
"""
if hasattr(self, 'domain'):
return Domain(self.rest_client.make_request(self.domain), self.rest_client) | python | def get_domain(self):
"""Get the Streams domain for the instance that owns this view.
Returns:
Domain: Streams domain for the instance owning this view.
"""
if hasattr(self, 'domain'):
return Domain(self.rest_client.make_request(self.domain), self.rest_client) | [
"def",
"get_domain",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'domain'",
")",
":",
"return",
"Domain",
"(",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"domain",
")",
",",
"self",
".",
"rest_client",
")"
] | Get the Streams domain for the instance that owns this view.
Returns:
Domain: Streams domain for the instance owning this view. | [
"Get",
"the",
"Streams",
"domain",
"for",
"the",
"instance",
"that",
"owns",
"this",
"view",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L559-L566 | train | 43,988 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | View.get_instance | def get_instance(self):
"""Get the Streams instance that owns this view.
Returns:
Instance: Streams instance owning this view.
"""
return Instance(self.rest_client.make_request(self.instance), self.rest_client) | python | def get_instance(self):
"""Get the Streams instance that owns this view.
Returns:
Instance: Streams instance owning this view.
"""
return Instance(self.rest_client.make_request(self.instance), self.rest_client) | [
"def",
"get_instance",
"(",
"self",
")",
":",
"return",
"Instance",
"(",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"instance",
")",
",",
"self",
".",
"rest_client",
")"
] | Get the Streams instance that owns this view.
Returns:
Instance: Streams instance owning this view. | [
"Get",
"the",
"Streams",
"instance",
"that",
"owns",
"this",
"view",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L568-L574 | train | 43,989 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | View.get_job | def get_job(self):
"""Get the Streams job that owns this view.
Returns:
Job: Streams Job owning this view.
"""
return Job(self.rest_client.make_request(self.job), self.rest_client) | python | def get_job(self):
"""Get the Streams job that owns this view.
Returns:
Job: Streams Job owning this view.
"""
return Job(self.rest_client.make_request(self.job), self.rest_client) | [
"def",
"get_job",
"(",
"self",
")",
":",
"return",
"Job",
"(",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"job",
")",
",",
"self",
".",
"rest_client",
")"
] | Get the Streams job that owns this view.
Returns:
Job: Streams Job owning this view. | [
"Get",
"the",
"Streams",
"job",
"that",
"owns",
"this",
"view",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L576-L582 | train | 43,990 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | View.stop_data_fetch | def stop_data_fetch(self):
"""Stops the thread that fetches data from the Streams view server.
"""
if self._data_fetcher:
self._data_fetcher.stop.set()
self._data_fetcher = None | python | def stop_data_fetch(self):
"""Stops the thread that fetches data from the Streams view server.
"""
if self._data_fetcher:
self._data_fetcher.stop.set()
self._data_fetcher = None | [
"def",
"stop_data_fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_fetcher",
":",
"self",
".",
"_data_fetcher",
".",
"stop",
".",
"set",
"(",
")",
"self",
".",
"_data_fetcher",
"=",
"None"
] | Stops the thread that fetches data from the Streams view server. | [
"Stops",
"the",
"thread",
"that",
"fetches",
"data",
"from",
"the",
"Streams",
"view",
"server",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L584-L589 | train | 43,991 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | View.start_data_fetch | def start_data_fetch(self):
"""Starts a thread that fetches data from the Streams view server.
Each item in the returned `Queue` represents a single tuple
on the stream the view is attached to.
Returns:
queue.Queue: Queue containing view data.
.. note:: This is a queue of the tuples coverted to Python
objects, it is not a queue of :py:class:`ViewItem` objects.
"""
self.stop_data_fetch()
self._data_fetcher = _ViewDataFetcher(self, self._tuple_fn)
t = threading.Thread(target=self._data_fetcher)
t.start()
return self._data_fetcher.items | python | def start_data_fetch(self):
"""Starts a thread that fetches data from the Streams view server.
Each item in the returned `Queue` represents a single tuple
on the stream the view is attached to.
Returns:
queue.Queue: Queue containing view data.
.. note:: This is a queue of the tuples coverted to Python
objects, it is not a queue of :py:class:`ViewItem` objects.
"""
self.stop_data_fetch()
self._data_fetcher = _ViewDataFetcher(self, self._tuple_fn)
t = threading.Thread(target=self._data_fetcher)
t.start()
return self._data_fetcher.items | [
"def",
"start_data_fetch",
"(",
"self",
")",
":",
"self",
".",
"stop_data_fetch",
"(",
")",
"self",
".",
"_data_fetcher",
"=",
"_ViewDataFetcher",
"(",
"self",
",",
"self",
".",
"_tuple_fn",
")",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
... | Starts a thread that fetches data from the Streams view server.
Each item in the returned `Queue` represents a single tuple
on the stream the view is attached to.
Returns:
queue.Queue: Queue containing view data.
.. note:: This is a queue of the tuples coverted to Python
objects, it is not a queue of :py:class:`ViewItem` objects. | [
"Starts",
"a",
"thread",
"that",
"fetches",
"data",
"from",
"the",
"Streams",
"view",
"server",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L591-L607 | train | 43,992 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | View.fetch_tuples | def fetch_tuples(self, max_tuples=20, timeout=None):
"""
Fetch a number of tuples from this view.
Fetching of data must have been started with
:py:meth:`start_data_fetch` before calling this method.
If ``timeout`` is ``None`` then the returned list will
contain ``max_tuples`` tuples. Otherwise if the timeout is reached
the list may contain less than ``max_tuples`` tuples.
Args:
max_tuples(int): Maximum number of tuples to fetch.
timeout(float): Maximum time to wait for ``max_tuples`` tuples.
Returns:
list: List of fetched tuples.
.. versionadded:: 1.12
"""
tuples = list()
if timeout is None:
while len(tuples) < max_tuples:
fetcher = self._data_fetcher
if not fetcher:
break
tuples.append(fetcher.items.get())
return tuples
timeout = float(timeout)
end = time.time() + timeout
while len(tuples) < max_tuples:
qto = end - time.time()
if qto <= 0:
break
try:
fetcher = self._data_fetcher
if not fetcher:
break
tuples.append(fetcher.items.get(timeout=qto))
except queue.Empty:
break
return tuples | python | def fetch_tuples(self, max_tuples=20, timeout=None):
"""
Fetch a number of tuples from this view.
Fetching of data must have been started with
:py:meth:`start_data_fetch` before calling this method.
If ``timeout`` is ``None`` then the returned list will
contain ``max_tuples`` tuples. Otherwise if the timeout is reached
the list may contain less than ``max_tuples`` tuples.
Args:
max_tuples(int): Maximum number of tuples to fetch.
timeout(float): Maximum time to wait for ``max_tuples`` tuples.
Returns:
list: List of fetched tuples.
.. versionadded:: 1.12
"""
tuples = list()
if timeout is None:
while len(tuples) < max_tuples:
fetcher = self._data_fetcher
if not fetcher:
break
tuples.append(fetcher.items.get())
return tuples
timeout = float(timeout)
end = time.time() + timeout
while len(tuples) < max_tuples:
qto = end - time.time()
if qto <= 0:
break
try:
fetcher = self._data_fetcher
if not fetcher:
break
tuples.append(fetcher.items.get(timeout=qto))
except queue.Empty:
break
return tuples | [
"def",
"fetch_tuples",
"(",
"self",
",",
"max_tuples",
"=",
"20",
",",
"timeout",
"=",
"None",
")",
":",
"tuples",
"=",
"list",
"(",
")",
"if",
"timeout",
"is",
"None",
":",
"while",
"len",
"(",
"tuples",
")",
"<",
"max_tuples",
":",
"fetcher",
"=",
... | Fetch a number of tuples from this view.
Fetching of data must have been started with
:py:meth:`start_data_fetch` before calling this method.
If ``timeout`` is ``None`` then the returned list will
contain ``max_tuples`` tuples. Otherwise if the timeout is reached
the list may contain less than ``max_tuples`` tuples.
Args:
max_tuples(int): Maximum number of tuples to fetch.
timeout(float): Maximum time to wait for ``max_tuples`` tuples.
Returns:
list: List of fetched tuples.
.. versionadded:: 1.12 | [
"Fetch",
"a",
"number",
"of",
"tuples",
"from",
"this",
"view",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L609-L650 | train | 43,993 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Job.retrieve_log_trace | def retrieve_log_trace(self, filename=None, dir=None):
"""Retrieves the application log and trace files of the job
and saves them as a compressed tar file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created tar file. Defaults to `job_<id>_<timestamp>.tar.gz` where `id` is the job identifier and `timestamp` is the number of seconds since the Unix epoch, for example ``job_355_1511995995.tar.gz``.
dir (str): a valid directory in which to save the archive. Defaults to the current directory.
Returns:
str: the path to the created tar file, or ``None`` if retrieving a job's logs is not supported in the version of IBM Streams to which the job is submitted.
.. versionadded:: 1.8
"""
if hasattr(self, "applicationLogTrace") and self.applicationLogTrace is not None:
logger.debug("Retrieving application logs from: " + self.applicationLogTrace)
if not filename:
filename = _file_name('job', self.id, '.tar.gz')
return self.rest_client._retrieve_file(self.applicationLogTrace, filename, dir, 'application/x-compressed')
else:
return None | python | def retrieve_log_trace(self, filename=None, dir=None):
"""Retrieves the application log and trace files of the job
and saves them as a compressed tar file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created tar file. Defaults to `job_<id>_<timestamp>.tar.gz` where `id` is the job identifier and `timestamp` is the number of seconds since the Unix epoch, for example ``job_355_1511995995.tar.gz``.
dir (str): a valid directory in which to save the archive. Defaults to the current directory.
Returns:
str: the path to the created tar file, or ``None`` if retrieving a job's logs is not supported in the version of IBM Streams to which the job is submitted.
.. versionadded:: 1.8
"""
if hasattr(self, "applicationLogTrace") and self.applicationLogTrace is not None:
logger.debug("Retrieving application logs from: " + self.applicationLogTrace)
if not filename:
filename = _file_name('job', self.id, '.tar.gz')
return self.rest_client._retrieve_file(self.applicationLogTrace, filename, dir, 'application/x-compressed')
else:
return None | [
"def",
"retrieve_log_trace",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"dir",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"applicationLogTrace\"",
")",
"and",
"self",
".",
"applicationLogTrace",
"is",
"not",
"None",
":",
"logger",
"."... | Retrieves the application log and trace files of the job
and saves them as a compressed tar file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created tar file. Defaults to `job_<id>_<timestamp>.tar.gz` where `id` is the job identifier and `timestamp` is the number of seconds since the Unix epoch, for example ``job_355_1511995995.tar.gz``.
dir (str): a valid directory in which to save the archive. Defaults to the current directory.
Returns:
str: the path to the created tar file, or ``None`` if retrieving a job's logs is not supported in the version of IBM Streams to which the job is submitted.
.. versionadded:: 1.8 | [
"Retrieves",
"the",
"application",
"log",
"and",
"trace",
"files",
"of",
"the",
"job",
"and",
"saves",
"them",
"as",
"a",
"compressed",
"tar",
"file",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L815-L838 | train | 43,994 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Job.cancel | def cancel(self, force=False):
"""Cancel this job.
Args:
force (bool, optional): Forcefully cancel this job.
Returns:
bool: True if the job was cancelled, otherwise False if an error occurred.
"""
return self.rest_client._sc._delegator._cancel_job(self, force) | python | def cancel(self, force=False):
"""Cancel this job.
Args:
force (bool, optional): Forcefully cancel this job.
Returns:
bool: True if the job was cancelled, otherwise False if an error occurred.
"""
return self.rest_client._sc._delegator._cancel_job(self, force) | [
"def",
"cancel",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"return",
"self",
".",
"rest_client",
".",
"_sc",
".",
"_delegator",
".",
"_cancel_job",
"(",
"self",
",",
"force",
")"
] | Cancel this job.
Args:
force (bool, optional): Forcefully cancel this job.
Returns:
bool: True if the job was cancelled, otherwise False if an error occurred. | [
"Cancel",
"this",
"job",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L942-L951 | train | 43,995 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Operator.get_metrics | def get_metrics(self, name=None):
"""Get metrics for this operator.
Args:
name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all metrics for this operator are returned.
Returns:
list(Metric): List of matching metrics.
Retrieving a list of metrics whose name contains the string "temperatureSensor" could be performed as followed
Example:
>>> from streamsx import rest
>>> sc = rest.StreamingAnalyticsConnection()
>>> instances = sc.get_instances()
>>> operator = instances[0].get_operators()[0]
>>> metrics = op.get_metrics(name='*temperatureSensor*')
"""
return self._get_elements(self.metrics, 'metrics', Metric, name=name) | python | def get_metrics(self, name=None):
"""Get metrics for this operator.
Args:
name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all metrics for this operator are returned.
Returns:
list(Metric): List of matching metrics.
Retrieving a list of metrics whose name contains the string "temperatureSensor" could be performed as followed
Example:
>>> from streamsx import rest
>>> sc = rest.StreamingAnalyticsConnection()
>>> instances = sc.get_instances()
>>> operator = instances[0].get_operators()[0]
>>> metrics = op.get_metrics(name='*temperatureSensor*')
"""
return self._get_elements(self.metrics, 'metrics', Metric, name=name) | [
"def",
"get_metrics",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_elements",
"(",
"self",
".",
"metrics",
",",
"'metrics'",
",",
"Metric",
",",
"name",
"=",
"name",
")"
] | Get metrics for this operator.
Args:
name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If
`name` is not supplied, then all metrics for this operator are returned.
Returns:
list(Metric): List of matching metrics.
Retrieving a list of metrics whose name contains the string "temperatureSensor" could be performed as followed
Example:
>>> from streamsx import rest
>>> sc = rest.StreamingAnalyticsConnection()
>>> instances = sc.get_instances()
>>> operator = instances[0].get_operators()[0]
>>> metrics = op.get_metrics(name='*temperatureSensor*') | [
"Get",
"metrics",
"for",
"this",
"operator",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L971-L989 | train | 43,996 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Operator.get_host | def get_host(self):
"""Get resource this operator is currently executing in.
If the operator is running on an externally
managed resource ``None`` is returned.
Returns:
Host: Resource this operator is running on.
.. versionadded:: 1.9
"""
if hasattr(self, 'host') and self.host:
return Host(self.rest_client.make_request(self.host), self.rest_client) | python | def get_host(self):
"""Get resource this operator is currently executing in.
If the operator is running on an externally
managed resource ``None`` is returned.
Returns:
Host: Resource this operator is running on.
.. versionadded:: 1.9
"""
if hasattr(self, 'host') and self.host:
return Host(self.rest_client.make_request(self.host), self.rest_client) | [
"def",
"get_host",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'host'",
")",
"and",
"self",
".",
"host",
":",
"return",
"Host",
"(",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"host",
")",
",",
"self",
".",
"r... | Get resource this operator is currently executing in.
If the operator is running on an externally
managed resource ``None`` is returned.
Returns:
Host: Resource this operator is running on.
.. versionadded:: 1.9 | [
"Get",
"resource",
"this",
"operator",
"is",
"currently",
"executing",
"in",
".",
"If",
"the",
"operator",
"is",
"running",
"on",
"an",
"externally",
"managed",
"resource",
"None",
"is",
"returned",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L991-L1002 | train | 43,997 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | Operator.get_pe | def get_pe(self):
"""Get the Streams processing element this operator is executing in.
Returns:
PE: Processing element for this operator.
.. versionadded:: 1.9
"""
return PE(self.rest_client.make_request(self.pe), self.rest_client) | python | def get_pe(self):
"""Get the Streams processing element this operator is executing in.
Returns:
PE: Processing element for this operator.
.. versionadded:: 1.9
"""
return PE(self.rest_client.make_request(self.pe), self.rest_client) | [
"def",
"get_pe",
"(",
"self",
")",
":",
"return",
"PE",
"(",
"self",
".",
"rest_client",
".",
"make_request",
"(",
"self",
".",
"pe",
")",
",",
"self",
".",
"rest_client",
")"
] | Get the Streams processing element this operator is executing in.
Returns:
PE: Processing element for this operator.
.. versionadded:: 1.9 | [
"Get",
"the",
"Streams",
"processing",
"element",
"this",
"operator",
"is",
"executing",
"in",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1004-L1012 | train | 43,998 |
IBMStreams/pypi.streamsx | streamsx/rest_primitives.py | PE.retrieve_trace | def retrieve_trace(self, filename=None, dir=None):
"""Retrieves the application trace files for this PE
and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.trace` where `id` is the PE identifier and `timestamp` is the number of seconds since the Unix epoch, for example ``pe_83_1511995995.trace``.
dir (str): a valid directory in which to save the file. Defaults to the current directory.
Returns:
str: the path to the created file, or None if retrieving a job's logs is not supported in the version of streams to which the job is submitted.
.. versionadded:: 1.9
"""
if hasattr(self, "applicationTrace") and self.applicationTrace is not None:
logger.debug("Retrieving PE trace: " + self.applicationTrace)
if not filename:
filename = _file_name('pe', self.id, '.trace')
return self.rest_client._retrieve_file(self.applicationTrace, filename, dir, 'text/plain')
else:
return None | python | def retrieve_trace(self, filename=None, dir=None):
"""Retrieves the application trace files for this PE
and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.trace` where `id` is the PE identifier and `timestamp` is the number of seconds since the Unix epoch, for example ``pe_83_1511995995.trace``.
dir (str): a valid directory in which to save the file. Defaults to the current directory.
Returns:
str: the path to the created file, or None if retrieving a job's logs is not supported in the version of streams to which the job is submitted.
.. versionadded:: 1.9
"""
if hasattr(self, "applicationTrace") and self.applicationTrace is not None:
logger.debug("Retrieving PE trace: " + self.applicationTrace)
if not filename:
filename = _file_name('pe', self.id, '.trace')
return self.rest_client._retrieve_file(self.applicationTrace, filename, dir, 'text/plain')
else:
return None | [
"def",
"retrieve_trace",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"dir",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"applicationTrace\"",
")",
"and",
"self",
".",
"applicationTrace",
"is",
"not",
"None",
":",
"logger",
".",
"debug... | Retrieves the application trace files for this PE
and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.trace` where `id` is the PE identifier and `timestamp` is the number of seconds since the Unix epoch, for example ``pe_83_1511995995.trace``.
dir (str): a valid directory in which to save the file. Defaults to the current directory.
Returns:
str: the path to the created file, or None if retrieving a job's logs is not supported in the version of streams to which the job is submitted.
.. versionadded:: 1.9 | [
"Retrieves",
"the",
"application",
"trace",
"files",
"for",
"this",
"PE",
"and",
"saves",
"them",
"as",
"a",
"plain",
"text",
"file",
"."
] | abd67b4757120f6f805787fba390f53e9df9cdd8 | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/rest_primitives.py#L1199-L1221 | train | 43,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.