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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.mutex | def mutex(self, mutex, **kwargs):
"""Add Mutex data to Batch object.
Args:
mutex (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Mutex.
"""
indicator_obj = Mutex(mutex, **kwargs)
return self._indicator(indicator_obj) | python | def mutex(self, mutex, **kwargs):
"""Add Mutex data to Batch object.
Args:
mutex (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Mutex.
"""
indicator_obj = Mutex(mutex, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"mutex",
"(",
"self",
",",
"mutex",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"Mutex",
"(",
"mutex",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] | Add Mutex data to Batch object.
Args:
mutex (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Mutex. | [
"Add",
"Mutex",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L974-L989 | train | 27,500 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.poll | def poll(self, batch_id, retry_seconds=None, back_off=None, timeout=None, halt_on_error=True):
"""Poll Batch status to ThreatConnect API.
.. code-block:: javascript
{
"status": "Success",
"data": {
"batchStatus": {
"id":3505,
"status":"Completed",
"errorCount":0,
"successCount":0,
"unprocessCount":0
}
}
}
Args:
batch_id (str): The ID returned from the ThreatConnect API for the current batch job.
retry_seconds (int): The base number of seconds used for retries when job is not
completed.
back_off (float): A multiplier to use for backing off on each poll attempt when job has
not completed.
timeout (int, optional): The number of seconds before the poll should timeout.
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The batch status returned from the ThreatConnect API.
"""
# check global setting for override
if self.halt_on_poll_error is not None:
halt_on_error = self.halt_on_poll_error
# initial poll interval
if self._poll_interval is None and self._batch_data_count is not None:
# calculate poll_interval base off the number of entries in the batch data
# with a minimum value of 5 seconds.
self._poll_interval = max(math.ceil(self._batch_data_count / 300), 5)
elif self._poll_interval is None:
# if not able to calculate poll_interval default to 15 seconds
self._poll_interval = 15
# poll retry back_off factor
if back_off is None:
poll_interval_back_off = 2.5
else:
poll_interval_back_off = float(back_off)
# poll retry seconds
if retry_seconds is None:
poll_retry_seconds = 5
else:
poll_retry_seconds = int(retry_seconds)
# poll timeout
if timeout is None:
timeout = self.poll_timeout
else:
timeout = int(timeout)
params = {'includeAdditional': 'true'}
poll_count = 0
poll_time_total = 0
data = {}
while True:
poll_count += 1
poll_time_total += self._poll_interval
time.sleep(self._poll_interval)
self.tcex.log.info('Batch poll time: {} seconds'.format(poll_time_total))
try:
# retrieve job status
r = self.tcex.session.get('/v2/batch/{}'.format(batch_id), params=params)
if not r.ok or 'application/json' not in r.headers.get('content-type', ''):
self.tcex.handle_error(545, [r.status_code, r.text], halt_on_error)
return data
data = r.json()
if data.get('status') != 'Success':
self.tcex.handle_error(545, [r.status_code, r.text], halt_on_error)
except Exception as e:
self.tcex.handle_error(540, [e], halt_on_error)
if data.get('data', {}).get('batchStatus', {}).get('status') == 'Completed':
# store last 5 poll times to use in calculating average poll time
modifier = poll_time_total * 0.7
self._poll_interval_times = self._poll_interval_times[-4:] + [modifier]
weights = [1]
poll_interval_time_weighted_sum = 0
for poll_interval_time in self._poll_interval_times:
poll_interval_time_weighted_sum += poll_interval_time * weights[-1]
# weights will be [1, 1.5, 2.25, 3.375, 5.0625] for all 5 poll times depending
# on how many poll times are available.
weights.append(weights[-1] * 1.5)
# pop off the last weight so its not added in to the sum
weights.pop()
# calculate the weighted average of the last 5 poll times
self._poll_interval = math.floor(poll_interval_time_weighted_sum / sum(weights))
if poll_count == 1:
# if completed on first poll, reduce poll interval.
self._poll_interval = self._poll_interval * 0.85
self.tcex.log.debug('Batch Status: {}'.format(data))
return data
# update poll_interval for retry with max poll time of 20 seconds
self._poll_interval = min(
poll_retry_seconds + int(poll_count * poll_interval_back_off), 20
)
# time out poll to prevent App running indefinitely
if poll_time_total >= timeout:
self.tcex.handle_error(550, [timeout], True) | python | def poll(self, batch_id, retry_seconds=None, back_off=None, timeout=None, halt_on_error=True):
"""Poll Batch status to ThreatConnect API.
.. code-block:: javascript
{
"status": "Success",
"data": {
"batchStatus": {
"id":3505,
"status":"Completed",
"errorCount":0,
"successCount":0,
"unprocessCount":0
}
}
}
Args:
batch_id (str): The ID returned from the ThreatConnect API for the current batch job.
retry_seconds (int): The base number of seconds used for retries when job is not
completed.
back_off (float): A multiplier to use for backing off on each poll attempt when job has
not completed.
timeout (int, optional): The number of seconds before the poll should timeout.
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The batch status returned from the ThreatConnect API.
"""
# check global setting for override
if self.halt_on_poll_error is not None:
halt_on_error = self.halt_on_poll_error
# initial poll interval
if self._poll_interval is None and self._batch_data_count is not None:
# calculate poll_interval base off the number of entries in the batch data
# with a minimum value of 5 seconds.
self._poll_interval = max(math.ceil(self._batch_data_count / 300), 5)
elif self._poll_interval is None:
# if not able to calculate poll_interval default to 15 seconds
self._poll_interval = 15
# poll retry back_off factor
if back_off is None:
poll_interval_back_off = 2.5
else:
poll_interval_back_off = float(back_off)
# poll retry seconds
if retry_seconds is None:
poll_retry_seconds = 5
else:
poll_retry_seconds = int(retry_seconds)
# poll timeout
if timeout is None:
timeout = self.poll_timeout
else:
timeout = int(timeout)
params = {'includeAdditional': 'true'}
poll_count = 0
poll_time_total = 0
data = {}
while True:
poll_count += 1
poll_time_total += self._poll_interval
time.sleep(self._poll_interval)
self.tcex.log.info('Batch poll time: {} seconds'.format(poll_time_total))
try:
# retrieve job status
r = self.tcex.session.get('/v2/batch/{}'.format(batch_id), params=params)
if not r.ok or 'application/json' not in r.headers.get('content-type', ''):
self.tcex.handle_error(545, [r.status_code, r.text], halt_on_error)
return data
data = r.json()
if data.get('status') != 'Success':
self.tcex.handle_error(545, [r.status_code, r.text], halt_on_error)
except Exception as e:
self.tcex.handle_error(540, [e], halt_on_error)
if data.get('data', {}).get('batchStatus', {}).get('status') == 'Completed':
# store last 5 poll times to use in calculating average poll time
modifier = poll_time_total * 0.7
self._poll_interval_times = self._poll_interval_times[-4:] + [modifier]
weights = [1]
poll_interval_time_weighted_sum = 0
for poll_interval_time in self._poll_interval_times:
poll_interval_time_weighted_sum += poll_interval_time * weights[-1]
# weights will be [1, 1.5, 2.25, 3.375, 5.0625] for all 5 poll times depending
# on how many poll times are available.
weights.append(weights[-1] * 1.5)
# pop off the last weight so its not added in to the sum
weights.pop()
# calculate the weighted average of the last 5 poll times
self._poll_interval = math.floor(poll_interval_time_weighted_sum / sum(weights))
if poll_count == 1:
# if completed on first poll, reduce poll interval.
self._poll_interval = self._poll_interval * 0.85
self.tcex.log.debug('Batch Status: {}'.format(data))
return data
# update poll_interval for retry with max poll time of 20 seconds
self._poll_interval = min(
poll_retry_seconds + int(poll_count * poll_interval_back_off), 20
)
# time out poll to prevent App running indefinitely
if poll_time_total >= timeout:
self.tcex.handle_error(550, [timeout], True) | [
"def",
"poll",
"(",
"self",
",",
"batch_id",
",",
"retry_seconds",
"=",
"None",
",",
"back_off",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"halt_on_error",
"=",
"True",
")",
":",
"# check global setting for override",
"if",
"self",
".",
"halt_on_poll_erro... | Poll Batch status to ThreatConnect API.
.. code-block:: javascript
{
"status": "Success",
"data": {
"batchStatus": {
"id":3505,
"status":"Completed",
"errorCount":0,
"successCount":0,
"unprocessCount":0
}
}
}
Args:
batch_id (str): The ID returned from the ThreatConnect API for the current batch job.
retry_seconds (int): The base number of seconds used for retries when job is not
completed.
back_off (float): A multiplier to use for backing off on each poll attempt when job has
not completed.
timeout (int, optional): The number of seconds before the poll should timeout.
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The batch status returned from the ThreatConnect API. | [
"Poll",
"Batch",
"status",
"to",
"ThreatConnect",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L991-L1106 | train | 27,501 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.registry_key | def registry_key(self, key_name, value_name, value_type, **kwargs):
"""Add Registry Key data to Batch object.
Args:
key_name (str): The key_name value for this Indicator.
value_name (str): The value_name value for this Indicator.
value_type (str): The value_type value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Registry Key.
"""
indicator_obj = RegistryKey(key_name, value_name, value_type, **kwargs)
return self._indicator(indicator_obj) | python | def registry_key(self, key_name, value_name, value_type, **kwargs):
"""Add Registry Key data to Batch object.
Args:
key_name (str): The key_name value for this Indicator.
value_name (str): The value_name value for this Indicator.
value_type (str): The value_type value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Registry Key.
"""
indicator_obj = RegistryKey(key_name, value_name, value_type, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"registry_key",
"(",
"self",
",",
"key_name",
",",
"value_name",
",",
"value_type",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"RegistryKey",
"(",
"key_name",
",",
"value_name",
",",
"value_type",
",",
"*",
"*",
"kwargs",
")",
"return"... | Add Registry Key data to Batch object.
Args:
key_name (str): The key_name value for this Indicator.
value_name (str): The value_name value for this Indicator.
value_type (str): The value_type value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of Registry Key. | [
"Add",
"Registry",
"Key",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1118-L1135 | train | 27,502 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.report | def report(self, name, **kwargs):
"""Add Report data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
publish_date (str, kwargs): The publish datetime expression for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Report.
"""
group_obj = Report(name, **kwargs)
return self._group(group_obj) | python | def report(self, name, **kwargs):
"""Add Report data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
publish_date (str, kwargs): The publish datetime expression for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Report.
"""
group_obj = Report(name, **kwargs)
return self._group(group_obj) | [
"def",
"report",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Report",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Report data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
publish_date (str, kwargs): The publish datetime expression for this Group.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Report. | [
"Add",
"Report",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1137-L1153 | train | 27,503 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.save | def save(self, resource):
"""Save group|indicator dict or object to shelve.
Best effort to save group/indicator data to disk. If for any reason the save fails
the data will still be accessible from list in memory.
Args:
resource (dict|obj): The Group or Indicator dict or object.
"""
resource_type = None
xid = None
if isinstance(resource, dict):
resource_type = resource.get('type')
xid = resource.get('xid')
else:
resource_type = resource.type
xid = resource.xid
if resource_type is not None and xid is not None:
saved = True
if resource_type in self.tcex.group_types:
try:
# groups
self.groups_shelf[xid] = resource
except Exception:
saved = False
if saved:
try:
del self._groups[xid]
except KeyError:
# if group was saved twice it would already be delete
pass
elif resource_type in self.tcex.indicator_types_data.keys():
try:
# indicators
self.indicators_shelf[xid] = resource
except Exception:
saved = False
if saved:
try:
del self._indicators[xid]
except KeyError:
# if indicator was saved twice it would already be delete
pass | python | def save(self, resource):
"""Save group|indicator dict or object to shelve.
Best effort to save group/indicator data to disk. If for any reason the save fails
the data will still be accessible from list in memory.
Args:
resource (dict|obj): The Group or Indicator dict or object.
"""
resource_type = None
xid = None
if isinstance(resource, dict):
resource_type = resource.get('type')
xid = resource.get('xid')
else:
resource_type = resource.type
xid = resource.xid
if resource_type is not None and xid is not None:
saved = True
if resource_type in self.tcex.group_types:
try:
# groups
self.groups_shelf[xid] = resource
except Exception:
saved = False
if saved:
try:
del self._groups[xid]
except KeyError:
# if group was saved twice it would already be delete
pass
elif resource_type in self.tcex.indicator_types_data.keys():
try:
# indicators
self.indicators_shelf[xid] = resource
except Exception:
saved = False
if saved:
try:
del self._indicators[xid]
except KeyError:
# if indicator was saved twice it would already be delete
pass | [
"def",
"save",
"(",
"self",
",",
"resource",
")",
":",
"resource_type",
"=",
"None",
"xid",
"=",
"None",
"if",
"isinstance",
"(",
"resource",
",",
"dict",
")",
":",
"resource_type",
"=",
"resource",
".",
"get",
"(",
"'type'",
")",
"xid",
"=",
"resource... | Save group|indicator dict or object to shelve.
Best effort to save group/indicator data to disk. If for any reason the save fails
the data will still be accessible from list in memory.
Args:
resource (dict|obj): The Group or Indicator dict or object. | [
"Save",
"group|indicator",
"dict",
"or",
"object",
"to",
"shelve",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1155-L1200 | train | 27,504 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.saved_groups | def saved_groups(self):
"""Return True if saved group files exits, else False."""
if self._saved_groups is None:
self._saved_groups = False
fqfn_saved = os.path.join(self.tcex.args.tc_temp_path, 'groups-saved')
if (
self.enable_saved_file
and os.path.isfile(fqfn_saved)
and os.access(fqfn_saved, os.R_OK)
):
self._saved_groups = True
self.tcex.log.debug('groups-saved file found')
return self._saved_groups | python | def saved_groups(self):
"""Return True if saved group files exits, else False."""
if self._saved_groups is None:
self._saved_groups = False
fqfn_saved = os.path.join(self.tcex.args.tc_temp_path, 'groups-saved')
if (
self.enable_saved_file
and os.path.isfile(fqfn_saved)
and os.access(fqfn_saved, os.R_OK)
):
self._saved_groups = True
self.tcex.log.debug('groups-saved file found')
return self._saved_groups | [
"def",
"saved_groups",
"(",
"self",
")",
":",
"if",
"self",
".",
"_saved_groups",
"is",
"None",
":",
"self",
".",
"_saved_groups",
"=",
"False",
"fqfn_saved",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tcex",
".",
"args",
".",
"tc_temp_pat... | Return True if saved group files exits, else False. | [
"Return",
"True",
"if",
"saved",
"group",
"files",
"exits",
"else",
"False",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1203-L1215 | train | 27,505 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.saved_xids | def saved_xids(self):
"""Return previously saved xids."""
if self._saved_xids is None:
self._saved_xids = []
if self.debug:
fpfn = os.path.join(self.tcex.args.tc_temp_path, 'xids-saved')
if os.path.isfile(fpfn) and os.access(fpfn, os.R_OK):
with open(fpfn) as fh:
self._saved_xids = fh.read().splitlines()
return self._saved_xids | python | def saved_xids(self):
"""Return previously saved xids."""
if self._saved_xids is None:
self._saved_xids = []
if self.debug:
fpfn = os.path.join(self.tcex.args.tc_temp_path, 'xids-saved')
if os.path.isfile(fpfn) and os.access(fpfn, os.R_OK):
with open(fpfn) as fh:
self._saved_xids = fh.read().splitlines()
return self._saved_xids | [
"def",
"saved_xids",
"(",
"self",
")",
":",
"if",
"self",
".",
"_saved_xids",
"is",
"None",
":",
"self",
".",
"_saved_xids",
"=",
"[",
"]",
"if",
"self",
".",
"debug",
":",
"fpfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tcex",
".... | Return previously saved xids. | [
"Return",
"previously",
"saved",
"xids",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1233-L1242 | train | 27,506 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.settings | def settings(self):
"""Return batch job settings."""
_settings = {
'action': self._action,
# not supported in v2 batch
# 'attributeWriteType': self._attribute_write_type,
'attributeWriteType': 'Replace',
'haltOnError': str(self._halt_on_error).lower(),
'owner': self._owner,
'version': 'V2',
}
if self._playbook_triggers_enabled is not None:
_settings['playbookTriggersEnabled'] = str(self._playbook_triggers_enabled).lower()
if self._hash_collision_mode is not None:
_settings['hashCollisionMode'] = self._hash_collision_mode
if self._file_merge_mode is not None:
_settings['fileMergeMode'] = self._file_merge_mode
return _settings | python | def settings(self):
"""Return batch job settings."""
_settings = {
'action': self._action,
# not supported in v2 batch
# 'attributeWriteType': self._attribute_write_type,
'attributeWriteType': 'Replace',
'haltOnError': str(self._halt_on_error).lower(),
'owner': self._owner,
'version': 'V2',
}
if self._playbook_triggers_enabled is not None:
_settings['playbookTriggersEnabled'] = str(self._playbook_triggers_enabled).lower()
if self._hash_collision_mode is not None:
_settings['hashCollisionMode'] = self._hash_collision_mode
if self._file_merge_mode is not None:
_settings['fileMergeMode'] = self._file_merge_mode
return _settings | [
"def",
"settings",
"(",
"self",
")",
":",
"_settings",
"=",
"{",
"'action'",
":",
"self",
".",
"_action",
",",
"# not supported in v2 batch",
"# 'attributeWriteType': self._attribute_write_type,",
"'attributeWriteType'",
":",
"'Replace'",
",",
"'haltOnError'",
":",
"str... | Return batch job settings. | [
"Return",
"batch",
"job",
"settings",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1245-L1262 | train | 27,507 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.signature | def signature(self, name, file_name, file_type, file_text, **kwargs):
"""Add Signature data to Batch object.
Valid file_types:
+ Snort ®
+ Suricata
+ YARA
+ ClamAV ®
+ OpenIOC
+ CybOX ™
+ Bro
+ Regex
+ SPL - Splunk ® Search Processing Language
Args:
name (str): The name for this Group.
file_name (str): The name for the attached signature for this Group.
file_type (str): The signature type for this Group.
file_text (str): The signature content for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Signature.
"""
group_obj = Signature(name, file_name, file_type, file_text, **kwargs)
return self._group(group_obj) | python | def signature(self, name, file_name, file_type, file_text, **kwargs):
"""Add Signature data to Batch object.
Valid file_types:
+ Snort ®
+ Suricata
+ YARA
+ ClamAV ®
+ OpenIOC
+ CybOX ™
+ Bro
+ Regex
+ SPL - Splunk ® Search Processing Language
Args:
name (str): The name for this Group.
file_name (str): The name for the attached signature for this Group.
file_type (str): The signature type for this Group.
file_text (str): The signature content for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Signature.
"""
group_obj = Signature(name, file_name, file_type, file_text, **kwargs)
return self._group(group_obj) | [
"def",
"signature",
"(",
"self",
",",
"name",
",",
"file_name",
",",
"file_type",
",",
"file_text",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Signature",
"(",
"name",
",",
"file_name",
",",
"file_type",
",",
"file_text",
",",
"*",
"*",
"kwa... | Add Signature data to Batch object.
Valid file_types:
+ Snort ®
+ Suricata
+ YARA
+ ClamAV ®
+ OpenIOC
+ CybOX ™
+ Bro
+ Regex
+ SPL - Splunk ® Search Processing Language
Args:
name (str): The name for this Group.
file_name (str): The name for the attached signature for this Group.
file_type (str): The signature type for this Group.
file_text (str): The signature content for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Signature. | [
"Add",
"Signature",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1264-L1290 | train | 27,508 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.submit_files | def submit_files(self, halt_on_error=True):
"""Submit Files for Documents and Reports to ThreatConnect API.
Critical Errors
* There is insufficient document storage allocated to this account.
Args:
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The upload status for each xid.
"""
# check global setting for override
if self.halt_on_file_error is not None:
halt_on_error = self.halt_on_file_error
upload_status = []
for xid, content_data in self._files.items():
del self._files[xid] # win or loose remove the entry
status = True
# used for debug/testing to prevent upload of previously uploaded file
if self.debug and xid in self.saved_xids:
self.tcex.log.debug('skipping previously saved file {}.'.format(xid))
continue
# process the file content
content = content_data.get('fileContent')
if callable(content):
content = content_data.get('fileContent')(xid)
if content is None:
upload_status.append({'uploaded': False, 'xid': xid})
self.tcex.log.warning('File content was null for xid {}.'.format(xid))
continue
if content_data.get('type') == 'Document':
api_branch = 'documents'
elif content_data.get('type') == 'Report':
api_branch = 'reports'
# Post File
url = '/v2/groups/{}/{}/upload'.format(api_branch, xid)
headers = {'Content-Type': 'application/octet-stream'}
params = {'owner': self._owner}
r = self.submit_file_content('POST', url, content, headers, params, halt_on_error)
if r.status_code == 401:
# use PUT method if file already exists
self.tcex.log.info('Received 401 status code using POST. Trying PUT to update.')
r = self.submit_file_content('PUT', url, content, headers, params, halt_on_error)
self.tcex.log.debug('{} Upload URL: {}.'.format(content_data.get('type'), r.url))
if not r.ok:
status = False
self.tcex.handle_error(585, [r.status_code, r.text], halt_on_error)
elif self.debug:
self.saved_xids.append(xid)
self.tcex.log.info('Status {} for file upload with xid {}.'.format(r.status_code, xid))
upload_status.append({'uploaded': status, 'xid': xid})
return upload_status | python | def submit_files(self, halt_on_error=True):
"""Submit Files for Documents and Reports to ThreatConnect API.
Critical Errors
* There is insufficient document storage allocated to this account.
Args:
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The upload status for each xid.
"""
# check global setting for override
if self.halt_on_file_error is not None:
halt_on_error = self.halt_on_file_error
upload_status = []
for xid, content_data in self._files.items():
del self._files[xid] # win or loose remove the entry
status = True
# used for debug/testing to prevent upload of previously uploaded file
if self.debug and xid in self.saved_xids:
self.tcex.log.debug('skipping previously saved file {}.'.format(xid))
continue
# process the file content
content = content_data.get('fileContent')
if callable(content):
content = content_data.get('fileContent')(xid)
if content is None:
upload_status.append({'uploaded': False, 'xid': xid})
self.tcex.log.warning('File content was null for xid {}.'.format(xid))
continue
if content_data.get('type') == 'Document':
api_branch = 'documents'
elif content_data.get('type') == 'Report':
api_branch = 'reports'
# Post File
url = '/v2/groups/{}/{}/upload'.format(api_branch, xid)
headers = {'Content-Type': 'application/octet-stream'}
params = {'owner': self._owner}
r = self.submit_file_content('POST', url, content, headers, params, halt_on_error)
if r.status_code == 401:
# use PUT method if file already exists
self.tcex.log.info('Received 401 status code using POST. Trying PUT to update.')
r = self.submit_file_content('PUT', url, content, headers, params, halt_on_error)
self.tcex.log.debug('{} Upload URL: {}.'.format(content_data.get('type'), r.url))
if not r.ok:
status = False
self.tcex.handle_error(585, [r.status_code, r.text], halt_on_error)
elif self.debug:
self.saved_xids.append(xid)
self.tcex.log.info('Status {} for file upload with xid {}.'.format(r.status_code, xid))
upload_status.append({'uploaded': status, 'xid': xid})
return upload_status | [
"def",
"submit_files",
"(",
"self",
",",
"halt_on_error",
"=",
"True",
")",
":",
"# check global setting for override",
"if",
"self",
".",
"halt_on_file_error",
"is",
"not",
"None",
":",
"halt_on_error",
"=",
"self",
".",
"halt_on_file_error",
"upload_status",
"=",
... | Submit Files for Documents and Reports to ThreatConnect API.
Critical Errors
* There is insufficient document storage allocated to this account.
Args:
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
dict: The upload status for each xid. | [
"Submit",
"Files",
"for",
"Documents",
"and",
"Reports",
"to",
"ThreatConnect",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1477-L1534 | train | 27,509 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.submit_file_content | def submit_file_content(self, method, url, data, headers, params, halt_on_error=True):
"""Submit File Content for Documents and Reports to ThreatConnect API.
Args:
method (str): The HTTP method for the request (POST, PUT).
url (str): The URL for the request.
data (str;bytes;file): The body (data) for the request.
headers (dict): The headers for the request.
params (dict): The query string parameters for the request.
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
requests.models.Response: The response from the request.
"""
r = None
try:
r = self.tcex.session.request(method, url, data=data, headers=headers, params=params)
except Exception as e:
self.tcex.handle_error(580, [e], halt_on_error)
return r | python | def submit_file_content(self, method, url, data, headers, params, halt_on_error=True):
"""Submit File Content for Documents and Reports to ThreatConnect API.
Args:
method (str): The HTTP method for the request (POST, PUT).
url (str): The URL for the request.
data (str;bytes;file): The body (data) for the request.
headers (dict): The headers for the request.
params (dict): The query string parameters for the request.
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
requests.models.Response: The response from the request.
"""
r = None
try:
r = self.tcex.session.request(method, url, data=data, headers=headers, params=params)
except Exception as e:
self.tcex.handle_error(580, [e], halt_on_error)
return r | [
"def",
"submit_file_content",
"(",
"self",
",",
"method",
",",
"url",
",",
"data",
",",
"headers",
",",
"params",
",",
"halt_on_error",
"=",
"True",
")",
":",
"r",
"=",
"None",
"try",
":",
"r",
"=",
"self",
".",
"tcex",
".",
"session",
".",
"request"... | Submit File Content for Documents and Reports to ThreatConnect API.
Args:
method (str): The HTTP method for the request (POST, PUT).
url (str): The URL for the request.
data (str;bytes;file): The body (data) for the request.
headers (dict): The headers for the request.
params (dict): The query string parameters for the request.
halt_on_error (bool, default:True): If True any exception will raise an error.
Returns:
requests.models.Response: The response from the request. | [
"Submit",
"File",
"Content",
"for",
"Documents",
"and",
"Reports",
"to",
"ThreatConnect",
"API",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1536-L1555 | train | 27,510 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.threat | def threat(self, name, **kwargs):
"""Add Threat data to Batch object
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Threat.
"""
group_obj = Threat(name, **kwargs)
return self._group(group_obj) | python | def threat(self, name, **kwargs):
"""Add Threat data to Batch object
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Threat.
"""
group_obj = Threat(name, **kwargs)
return self._group(group_obj) | [
"def",
"threat",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"group_obj",
"=",
"Threat",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_group",
"(",
"group_obj",
")"
] | Add Threat data to Batch object
Args:
name (str): The name for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
xid (str, kwargs): The external id for this Group.
Returns:
obj: An instance of Threat. | [
"Add",
"Threat",
"data",
"to",
"Batch",
"object"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1575-L1587 | train | 27,511 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.user_agent | def user_agent(self, text, **kwargs):
"""Add User Agent data to Batch object
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of UserAgent.
"""
indicator_obj = UserAgent(text, **kwargs)
return self._indicator(indicator_obj) | python | def user_agent(self, text, **kwargs):
"""Add User Agent data to Batch object
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of UserAgent.
"""
indicator_obj = UserAgent(text, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"user_agent",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"UserAgent",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] | Add User Agent data to Batch object
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of UserAgent. | [
"Add",
"User",
"Agent",
"data",
"to",
"Batch",
"object"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1589-L1604 | train | 27,512 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.url | def url(self, text, **kwargs):
"""Add URL Address data to Batch object.
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of URL.
"""
indicator_obj = URL(text, **kwargs)
return self._indicator(indicator_obj) | python | def url(self, text, **kwargs):
"""Add URL Address data to Batch object.
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of URL.
"""
indicator_obj = URL(text, **kwargs)
return self._indicator(indicator_obj) | [
"def",
"url",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"URL",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] | Add URL Address data to Batch object.
Args:
text (str): The value for this Indicator.
confidence (str, kwargs): The threat confidence for this Indicator.
date_added (str, kwargs): The date timestamp the Indicator was created.
last_modified (str, kwargs): The date timestamp the Indicator was last modified.
rating (str, kwargs): The threat rating for this Indicator.
xid (str, kwargs): The external id for this Indicator.
Returns:
obj: An instance of URL. | [
"Add",
"URL",
"Address",
"data",
"to",
"Batch",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1606-L1621 | train | 27,513 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_batch.py | TcExBatch.write_batch_json | def write_batch_json(self, content):
"""Write batch json data to a file."""
timestamp = str(time.time()).replace('.', '')
batch_json_file = os.path.join(
self.tcex.args.tc_temp_path, 'batch-{}.json'.format(timestamp)
)
with open(batch_json_file, 'w') as fh:
json.dump(content, fh, indent=2) | python | def write_batch_json(self, content):
"""Write batch json data to a file."""
timestamp = str(time.time()).replace('.', '')
batch_json_file = os.path.join(
self.tcex.args.tc_temp_path, 'batch-{}.json'.format(timestamp)
)
with open(batch_json_file, 'w') as fh:
json.dump(content, fh, indent=2) | [
"def",
"write_batch_json",
"(",
"self",
",",
"content",
")",
":",
"timestamp",
"=",
"str",
"(",
"time",
".",
"time",
"(",
")",
")",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"batch_json_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
"."... | Write batch json data to a file. | [
"Write",
"batch",
"json",
"data",
"to",
"a",
"file",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_batch.py#L1623-L1630 | train | 27,514 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/tcex_ti_mappings.py | TIMappings.attribute_labels | def attribute_labels(self, attribute_id, params=None):
"""
Gets the security labels from a attribute
Yields: Security label json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
for al in self.tc_requests.attribute_labels(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_id,
owner=self.owner,
params=params,
):
yield al | python | def attribute_labels(self, attribute_id, params=None):
"""
Gets the security labels from a attribute
Yields: Security label json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
for al in self.tc_requests.attribute_labels(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_id,
owner=self.owner,
params=params,
):
yield al | [
"def",
"attribute_labels",
"(",
"self",
",",
"attribute_id",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_e... | Gets the security labels from a attribute
Yields: Security label json | [
"Gets",
"the",
"security",
"labels",
"from",
"a",
"attribute"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tcex_ti_mappings.py#L704-L724 | train | 27,515 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/tcex_ti_mappings.py | TIMappings.attribute_label | def attribute_label(self, attribute_id, label, action='GET', params=None):
"""
Gets a security labels from a attribute
Args:
attribute_id:
label:
action:
params:
Returns: Security label json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if action == 'GET':
return self.tc_requests.get_attribute_label(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_id,
label,
owner=self.owner,
params=params,
)
if action == 'DELETE':
return self.tc_requests.delete_attribute_label(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_id,
label,
owner=self.owner,
)
self._tcex.handle_error(925, ['action', 'attribute_label', 'action', 'action', action])
return None | python | def attribute_label(self, attribute_id, label, action='GET', params=None):
"""
Gets a security labels from a attribute
Args:
attribute_id:
label:
action:
params:
Returns: Security label json
"""
if params is None:
params = {}
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if action == 'GET':
return self.tc_requests.get_attribute_label(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_id,
label,
owner=self.owner,
params=params,
)
if action == 'DELETE':
return self.tc_requests.delete_attribute_label(
self.api_type,
self.api_sub_type,
self.unique_id,
attribute_id,
label,
owner=self.owner,
)
self._tcex.handle_error(925, ['action', 'attribute_label', 'action', 'action', action])
return None | [
"def",
"attribute_label",
"(",
"self",
",",
"attribute_id",
",",
"label",
",",
"action",
"=",
"'GET'",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"self",
".",
"can_update",
"(",
")",... | Gets a security labels from a attribute
Args:
attribute_id:
label:
action:
params:
Returns: Security label json | [
"Gets",
"a",
"security",
"labels",
"from",
"a",
"attribute"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tcex_ti_mappings.py#L726-L764 | train | 27,516 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/tcex_ti_mappings.py | TIMappings.add_attribute_label | def add_attribute_label(self, attribute_id, label):
"""
Adds a security labels to a attribute
Args:
attribute_id:
label:
Returns: A response json
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
return self.tc_requests.add_attribute_label(
self.api_type, self.api_sub_type, self.unique_id, attribute_id, label, owner=self.owner
) | python | def add_attribute_label(self, attribute_id, label):
"""
Adds a security labels to a attribute
Args:
attribute_id:
label:
Returns: A response json
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
return self.tc_requests.add_attribute_label(
self.api_type, self.api_sub_type, self.unique_id, attribute_id, label, owner=self.owner
) | [
"def",
"add_attribute_label",
"(",
"self",
",",
"attribute_id",
",",
"label",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"return",
"... | Adds a security labels to a attribute
Args:
attribute_id:
label:
Returns: A response json | [
"Adds",
"a",
"security",
"labels",
"to",
"a",
"attribute"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/tcex_ti_mappings.py#L766-L781 | train | 27,517 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_package.py | TcExPackage.bundle | def bundle(self, bundle_name):
"""Bundle multiple Job or Playbook Apps into a single zip file.
Args:
bundle_name (str): The output name of the bundle zip file.
"""
if self.args.bundle or self.tcex_json.get('package', {}).get('bundle', False):
if self.tcex_json.get('package', {}).get('bundle_packages') is not None:
for bundle in self.tcex_json.get('package', {}).get('bundle_packages') or []:
bundle_name = bundle.get('name')
bundle_patterns = bundle.get('patterns')
bundle_apps = []
for app in self._app_packages:
for app_pattern in bundle_patterns:
p = re.compile(app_pattern, re.IGNORECASE)
if p.match(app):
bundle_apps.append(app)
# bundle app in zip
if bundle_apps:
self.bundle_apps(bundle_name, bundle_apps)
else:
self.bundle_apps(bundle_name, self._app_packages) | python | def bundle(self, bundle_name):
"""Bundle multiple Job or Playbook Apps into a single zip file.
Args:
bundle_name (str): The output name of the bundle zip file.
"""
if self.args.bundle or self.tcex_json.get('package', {}).get('bundle', False):
if self.tcex_json.get('package', {}).get('bundle_packages') is not None:
for bundle in self.tcex_json.get('package', {}).get('bundle_packages') or []:
bundle_name = bundle.get('name')
bundle_patterns = bundle.get('patterns')
bundle_apps = []
for app in self._app_packages:
for app_pattern in bundle_patterns:
p = re.compile(app_pattern, re.IGNORECASE)
if p.match(app):
bundle_apps.append(app)
# bundle app in zip
if bundle_apps:
self.bundle_apps(bundle_name, bundle_apps)
else:
self.bundle_apps(bundle_name, self._app_packages) | [
"def",
"bundle",
"(",
"self",
",",
"bundle_name",
")",
":",
"if",
"self",
".",
"args",
".",
"bundle",
"or",
"self",
".",
"tcex_json",
".",
"get",
"(",
"'package'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'bundle'",
",",
"False",
")",
":",
"if",
"se... | Bundle multiple Job or Playbook Apps into a single zip file.
Args:
bundle_name (str): The output name of the bundle zip file. | [
"Bundle",
"multiple",
"Job",
"or",
"Playbook",
"Apps",
"into",
"a",
"single",
"zip",
"file",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_package.py#L85-L108 | train | 27,518 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_package.py | TcExPackage.commit_hash | def commit_hash(self):
"""Return the current commit hash if available.
This is not a required task so best effort is fine. In other words this is not guaranteed
to work 100% of the time.
"""
commit_hash = None
branch = None
branch_file = '.git/HEAD' # ref: refs/heads/develop
# get current branch
if os.path.isfile(branch_file):
with open(branch_file, 'r') as f:
try:
branch = f.read().strip().split('/')[2]
except IndexError:
pass
# get commit hash
if branch:
hash_file = '.git/refs/heads/{}'.format(branch)
if os.path.isfile(hash_file):
with open(hash_file, 'r') as f:
commit_hash = f.read().strip()
return commit_hash | python | def commit_hash(self):
"""Return the current commit hash if available.
This is not a required task so best effort is fine. In other words this is not guaranteed
to work 100% of the time.
"""
commit_hash = None
branch = None
branch_file = '.git/HEAD' # ref: refs/heads/develop
# get current branch
if os.path.isfile(branch_file):
with open(branch_file, 'r') as f:
try:
branch = f.read().strip().split('/')[2]
except IndexError:
pass
# get commit hash
if branch:
hash_file = '.git/refs/heads/{}'.format(branch)
if os.path.isfile(hash_file):
with open(hash_file, 'r') as f:
commit_hash = f.read().strip()
return commit_hash | [
"def",
"commit_hash",
"(",
"self",
")",
":",
"commit_hash",
"=",
"None",
"branch",
"=",
"None",
"branch_file",
"=",
"'.git/HEAD'",
"# ref: refs/heads/develop",
"# get current branch",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"branch_file",
")",
":",
"with",
... | Return the current commit hash if available.
This is not a required task so best effort is fine. In other words this is not guaranteed
to work 100% of the time. | [
"Return",
"the",
"current",
"commit",
"hash",
"if",
"available",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_package.py#L135-L159 | train | 27,519 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_package.py | TcExPackage.print_results | def print_results(self):
"""Print results of the package command."""
# Updates
if self.package_data.get('updates'):
print('\n{}{}Updates:'.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data['updates']:
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
)
)
# Packaging
print('\n{}{}Package:'.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data['package']:
if isinstance(p.get('output'), list):
n = 5
list_data = p.get('output')
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, ', '.join(p.get('output')[:n])
)
)
del list_data[:n]
for data in [
list_data[i : i + n] for i in range(0, len(list_data), n) # noqa: E203
]:
print(
'{!s:<20}{}{} {!s:<50}'.format(
'', c.Style.BRIGHT, c.Fore.CYAN, ', '.join(data)
)
)
else:
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
)
)
# Bundle
if self.package_data.get('bundle'):
print('\n{}{}Bundle:'.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data['bundle']:
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
)
)
# ignore exit code
if not self.args.ignore_validation:
print('\n') # separate errors from normal output
# print all errors
for error in self.package_data.get('errors'):
print('{}{}'.format(c.Fore.RED, error))
self.exit_code = 1 | python | def print_results(self):
"""Print results of the package command."""
# Updates
if self.package_data.get('updates'):
print('\n{}{}Updates:'.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data['updates']:
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
)
)
# Packaging
print('\n{}{}Package:'.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data['package']:
if isinstance(p.get('output'), list):
n = 5
list_data = p.get('output')
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, ', '.join(p.get('output')[:n])
)
)
del list_data[:n]
for data in [
list_data[i : i + n] for i in range(0, len(list_data), n) # noqa: E203
]:
print(
'{!s:<20}{}{} {!s:<50}'.format(
'', c.Style.BRIGHT, c.Fore.CYAN, ', '.join(data)
)
)
else:
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
)
)
# Bundle
if self.package_data.get('bundle'):
print('\n{}{}Bundle:'.format(c.Style.BRIGHT, c.Fore.BLUE))
for p in self.package_data['bundle']:
print(
'{!s:<20}{}{} {!s:<50}'.format(
p.get('action'), c.Style.BRIGHT, c.Fore.CYAN, p.get('output')
)
)
# ignore exit code
if not self.args.ignore_validation:
print('\n') # separate errors from normal output
# print all errors
for error in self.package_data.get('errors'):
print('{}{}'.format(c.Fore.RED, error))
self.exit_code = 1 | [
"def",
"print_results",
"(",
"self",
")",
":",
"# Updates",
"if",
"self",
".",
"package_data",
".",
"get",
"(",
"'updates'",
")",
":",
"print",
"(",
"'\\n{}{}Updates:'",
".",
"format",
"(",
"c",
".",
"Style",
".",
"BRIGHT",
",",
"c",
".",
"Fore",
".",
... | Print results of the package command. | [
"Print",
"results",
"of",
"the",
"package",
"command",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_package.py#L294-L350 | train | 27,520 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_package.py | TcExPackage.zip_file | def zip_file(self, app_path, app_name, tmp_path):
"""Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip.
"""
# zip build directory
zip_file = os.path.join(app_path, self.args.outdir, app_name)
zip_file_zip = '{}.zip'.format(zip_file)
zip_file_tcx = '{}.tcx'.format(zip_file)
shutil.make_archive(zip_file, 'zip', tmp_path, app_name)
shutil.move(zip_file_zip, zip_file_tcx)
self._app_packages.append(zip_file_tcx)
# update package data
self.package_data['package'].append({'action': 'App Package:', 'output': zip_file_tcx}) | python | def zip_file(self, app_path, app_name, tmp_path):
"""Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip.
"""
# zip build directory
zip_file = os.path.join(app_path, self.args.outdir, app_name)
zip_file_zip = '{}.zip'.format(zip_file)
zip_file_tcx = '{}.tcx'.format(zip_file)
shutil.make_archive(zip_file, 'zip', tmp_path, app_name)
shutil.move(zip_file_zip, zip_file_tcx)
self._app_packages.append(zip_file_tcx)
# update package data
self.package_data['package'].append({'action': 'App Package:', 'output': zip_file_tcx}) | [
"def",
"zip_file",
"(",
"self",
",",
"app_path",
",",
"app_name",
",",
"tmp_path",
")",
":",
"# zip build directory",
"zip_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app_path",
",",
"self",
".",
"args",
".",
"outdir",
",",
"app_name",
")",
"zip_fi... | Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip. | [
"Zip",
"the",
"App",
"with",
"tcex",
"extension",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_package.py#L352-L368 | train | 27,521 |
ThreatConnect-Inc/tcex | tcex/tcex_request.py | TcExRequest.content_type | def content_type(self, data):
"""The Content-Type header value for this request."""
self._content_type = str(data)
self.add_header('Content-Type', str(data)) | python | def content_type(self, data):
"""The Content-Type header value for this request."""
self._content_type = str(data)
self.add_header('Content-Type', str(data)) | [
"def",
"content_type",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_content_type",
"=",
"str",
"(",
"data",
")",
"self",
".",
"add_header",
"(",
"'Content-Type'",
",",
"str",
"(",
"data",
")",
")"
] | The Content-Type header value for this request. | [
"The",
"Content",
"-",
"Type",
"header",
"value",
"for",
"this",
"request",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_request.py#L131-L134 | train | 27,522 |
ThreatConnect-Inc/tcex | tcex/tcex_request.py | TcExRequest.set_basic_auth | def set_basic_auth(self, username, password):
"""Manually set basic auth in the header when normal method does not work."""
credentials = str(b64encode('{}:{}'.format(username, password).encode('utf-8')), 'utf-8')
self.authorization = 'Basic {}'.format(credentials) | python | def set_basic_auth(self, username, password):
"""Manually set basic auth in the header when normal method does not work."""
credentials = str(b64encode('{}:{}'.format(username, password).encode('utf-8')), 'utf-8')
self.authorization = 'Basic {}'.format(credentials) | [
"def",
"set_basic_auth",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"credentials",
"=",
"str",
"(",
"b64encode",
"(",
"'{}:{}'",
".",
"format",
"(",
"username",
",",
"password",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"'utf-8'",
... | Manually set basic auth in the header when normal method does not work. | [
"Manually",
"set",
"basic",
"auth",
"in",
"the",
"header",
"when",
"normal",
"method",
"does",
"not",
"work",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_request.py#L136-L139 | train | 27,523 |
ThreatConnect-Inc/tcex | tcex/tcex_request.py | TcExRequest.http_method | def http_method(self, data):
"""The HTTP method for this request."""
data = data.upper()
if data in ['DELETE', 'GET', 'POST', 'PUT']:
self._http_method = data
# set content type for commit methods (best guess)
if self._headers.get('Content-Type') is None and data in ['POST', 'PUT']:
self.add_header('Content-Type', 'application/json')
else:
raise AttributeError(
'Request Object Error: {} is not a valid HTTP method.'.format(data)
) | python | def http_method(self, data):
"""The HTTP method for this request."""
data = data.upper()
if data in ['DELETE', 'GET', 'POST', 'PUT']:
self._http_method = data
# set content type for commit methods (best guess)
if self._headers.get('Content-Type') is None and data in ['POST', 'PUT']:
self.add_header('Content-Type', 'application/json')
else:
raise AttributeError(
'Request Object Error: {} is not a valid HTTP method.'.format(data)
) | [
"def",
"http_method",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"upper",
"(",
")",
"if",
"data",
"in",
"[",
"'DELETE'",
",",
"'GET'",
",",
"'POST'",
",",
"'PUT'",
"]",
":",
"self",
".",
"_http_method",
"=",
"data",
"# set content ... | The HTTP method for this request. | [
"The",
"HTTP",
"method",
"for",
"this",
"request",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_request.py#L188-L200 | train | 27,524 |
ThreatConnect-Inc/tcex | tcex/tcex_request.py | TcExRequest.send | def send(self, stream=False):
"""Send the HTTP request via Python Requests modules.
This method will send the request to the remote endpoint. It will try to handle
temporary communications issues by retrying the request automatically.
Args:
stream (bool): Boolean to enable stream download.
Returns:
Requests.Response: The Request response
"""
#
# api request (gracefully handle temporary communications issues with the API)
#
try:
response = self.session.request(
self._http_method,
self._url,
auth=self._basic_auth,
data=self._body,
files=self._files,
headers=self._headers,
params=self._payload,
stream=stream,
timeout=self._timeout,
)
except Exception as e:
err = 'Failed making HTTP request ({}).'.format(e)
raise RuntimeError(err)
# self.tcex.log.info(u'URL ({}): {}'.format(self._http_method, response.url))
self.tcex.log.info(u'Status Code: {}'.format(response.status_code))
return response | python | def send(self, stream=False):
"""Send the HTTP request via Python Requests modules.
This method will send the request to the remote endpoint. It will try to handle
temporary communications issues by retrying the request automatically.
Args:
stream (bool): Boolean to enable stream download.
Returns:
Requests.Response: The Request response
"""
#
# api request (gracefully handle temporary communications issues with the API)
#
try:
response = self.session.request(
self._http_method,
self._url,
auth=self._basic_auth,
data=self._body,
files=self._files,
headers=self._headers,
params=self._payload,
stream=stream,
timeout=self._timeout,
)
except Exception as e:
err = 'Failed making HTTP request ({}).'.format(e)
raise RuntimeError(err)
# self.tcex.log.info(u'URL ({}): {}'.format(self._http_method, response.url))
self.tcex.log.info(u'Status Code: {}'.format(response.status_code))
return response | [
"def",
"send",
"(",
"self",
",",
"stream",
"=",
"False",
")",
":",
"#",
"# api request (gracefully handle temporary communications issues with the API)",
"#",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"self",
".",
"_http_method",
",... | Send the HTTP request via Python Requests modules.
This method will send the request to the remote endpoint. It will try to handle
temporary communications issues by retrying the request automatically.
Args:
stream (bool): Boolean to enable stream download.
Returns:
Requests.Response: The Request response | [
"Send",
"the",
"HTTP",
"request",
"via",
"Python",
"Requests",
"modules",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_request.py#L256-L289 | train | 27,525 |
ThreatConnect-Inc/tcex | app_init/playbook_utility/app.py | App.run | def run(self):
"""Run the App main logic.
This method should contain the core logic of the App.
"""
# read inputs
indent = int(self.tcex.playbook.read(self.args.indent))
json_data = self.tcex.playbook.read(self.args.json_data)
# get the playbook variable type
json_data_type = self.tcex.playbook.variable_type(self.args.json_data)
# convert string input to dict
if json_data_type in ['String']:
json_data = json.loads(json_data)
# generate the new "pretty" json (this will be used as an option variable)
try:
self.pretty_json = json.dumps(json_data, indent=indent, sort_keys=self.args.sort_keys)
except Exception:
self.tcex.exit(1, 'Failed parsing JSON data.')
# set the App exit message
self.exit_message = 'JSON prettified.' | python | def run(self):
"""Run the App main logic.
This method should contain the core logic of the App.
"""
# read inputs
indent = int(self.tcex.playbook.read(self.args.indent))
json_data = self.tcex.playbook.read(self.args.json_data)
# get the playbook variable type
json_data_type = self.tcex.playbook.variable_type(self.args.json_data)
# convert string input to dict
if json_data_type in ['String']:
json_data = json.loads(json_data)
# generate the new "pretty" json (this will be used as an option variable)
try:
self.pretty_json = json.dumps(json_data, indent=indent, sort_keys=self.args.sort_keys)
except Exception:
self.tcex.exit(1, 'Failed parsing JSON data.')
# set the App exit message
self.exit_message = 'JSON prettified.' | [
"def",
"run",
"(",
"self",
")",
":",
"# read inputs",
"indent",
"=",
"int",
"(",
"self",
".",
"tcex",
".",
"playbook",
".",
"read",
"(",
"self",
".",
"args",
".",
"indent",
")",
")",
"json_data",
"=",
"self",
".",
"tcex",
".",
"playbook",
".",
"rea... | Run the App main logic.
This method should contain the core logic of the App. | [
"Run",
"the",
"App",
"main",
"logic",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/playbook_utility/app.py#L25-L48 | train | 27,526 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook._parse_out_variable | def _parse_out_variable(self):
"""Internal method to parse the tc_playbook_out_variable arg.
**Example Variable Format**::
#App:1234:status!String,#App:1234:status_code!String
"""
self._out_variables = {}
self._out_variables_type = {}
if self.tcex.default_args.tc_playbook_out_variables:
variables = self.tcex.default_args.tc_playbook_out_variables.strip()
for o in variables.split(','):
# parse the variable to get individual parts
parsed_key = self.parse_variable(o)
variable_name = parsed_key['name']
variable_type = parsed_key['type']
# store the variables in dict by name (e.g. "status_code")
self._out_variables[variable_name] = {'variable': o}
# store the variables in dict by name-type (e.g. "status_code-String")
vt_key = '{}-{}'.format(variable_name, variable_type)
self._out_variables_type[vt_key] = {'variable': o} | python | def _parse_out_variable(self):
"""Internal method to parse the tc_playbook_out_variable arg.
**Example Variable Format**::
#App:1234:status!String,#App:1234:status_code!String
"""
self._out_variables = {}
self._out_variables_type = {}
if self.tcex.default_args.tc_playbook_out_variables:
variables = self.tcex.default_args.tc_playbook_out_variables.strip()
for o in variables.split(','):
# parse the variable to get individual parts
parsed_key = self.parse_variable(o)
variable_name = parsed_key['name']
variable_type = parsed_key['type']
# store the variables in dict by name (e.g. "status_code")
self._out_variables[variable_name] = {'variable': o}
# store the variables in dict by name-type (e.g. "status_code-String")
vt_key = '{}-{}'.format(variable_name, variable_type)
self._out_variables_type[vt_key] = {'variable': o} | [
"def",
"_parse_out_variable",
"(",
"self",
")",
":",
"self",
".",
"_out_variables",
"=",
"{",
"}",
"self",
".",
"_out_variables_type",
"=",
"{",
"}",
"if",
"self",
".",
"tcex",
".",
"default_args",
".",
"tc_playbook_out_variables",
":",
"variables",
"=",
"se... | Internal method to parse the tc_playbook_out_variable arg.
**Example Variable Format**::
#App:1234:status!String,#App:1234:status_code!String | [
"Internal",
"method",
"to",
"parse",
"the",
"tc_playbook_out_variable",
"arg",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L36-L56 | train | 27,527 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook._variable_pattern | def _variable_pattern(self):
"""Regex pattern to match and parse a playbook variable."""
variable_pattern = r'#([A-Za-z]+)' # match literal (#App) at beginning of String
variable_pattern += r':([\d]+)' # app id (:7979)
variable_pattern += r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name)
variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array)
variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array)
variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type
variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom
variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom
variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom)
return variable_pattern | python | def _variable_pattern(self):
"""Regex pattern to match and parse a playbook variable."""
variable_pattern = r'#([A-Za-z]+)' # match literal (#App) at beginning of String
variable_pattern += r':([\d]+)' # app id (:7979)
variable_pattern += r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name)
variable_pattern += r'!(StringArray|BinaryArray|KeyValueArray' # variable type (array)
variable_pattern += r'|TCEntityArray|TCEnhancedEntityArray' # variable type (array)
variable_pattern += r'|String|Binary|KeyValue|TCEntity|TCEnhancedEntity' # variable type
variable_pattern += r'|(?:(?!String)(?!Binary)(?!KeyValue)' # non matching for custom
variable_pattern += r'(?!TCEntity)(?!TCEnhancedEntity)' # non matching for custom
variable_pattern += r'[A-Za-z0-9_-]+))' # variable type (custom)
return variable_pattern | [
"def",
"_variable_pattern",
"(",
"self",
")",
":",
"variable_pattern",
"=",
"r'#([A-Za-z]+)'",
"# match literal (#App) at beginning of String",
"variable_pattern",
"+=",
"r':([\\d]+)'",
"# app id (:7979)",
"variable_pattern",
"+=",
"r':([A-Za-z0-9_\\.\\-\\[\\]]+)'",
"# variable nam... | Regex pattern to match and parse a playbook variable. | [
"Regex",
"pattern",
"to",
"match",
"and",
"parse",
"a",
"playbook",
"variable",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L59-L70 | train | 27,528 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.add_output | def add_output(self, key, value, variable_type):
"""Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the data can be
stored inline, when it is generated and then written before the App completes.
.. code-block:: python
:linenos:
:lineno-start: 1
for color in ['blue', 'red', 'yellow']:
tcex.playbook.add_output('app.colors', color, 'StringArray')
tcex.playbook.write_output() # writes the output stored in output_data
.. code-block:: json
:linenos:
:lineno-start: 1
{
"my_color-String": {
"key": "my_color",
"type": "String",
"value": "blue"
},
"my_numbers-String": {
"key": "my_numbers",
"type": "String",
"value": "seven"
},
"my_numbers-StringArray": {
"key": "my_numbers",
"type": "StringArray",
"value": ["seven", "five"]
}
}
Args:
key (string): The variable name to write to storage.
value (any): The value to write to storage.
variable_type (string): The variable type being written.
"""
index = '{}-{}'.format(key, variable_type)
self.output_data.setdefault(index, {})
if value is None:
return
if variable_type in ['String', 'Binary', 'KeyValue', 'TCEntity', 'TCEnhancedEntity']:
self.output_data[index] = {'key': key, 'type': variable_type, 'value': value}
elif variable_type in [
'StringArray',
'BinaryArray',
'KeyValueArray',
'TCEntityArray',
'TCEnhancedEntityArray',
]:
self.output_data[index].setdefault('key', key)
self.output_data[index].setdefault('type', variable_type)
if isinstance(value, list):
self.output_data[index].setdefault('value', []).extend(value)
else:
self.output_data[index].setdefault('value', []).append(value) | python | def add_output(self, key, value, variable_type):
"""Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the data can be
stored inline, when it is generated and then written before the App completes.
.. code-block:: python
:linenos:
:lineno-start: 1
for color in ['blue', 'red', 'yellow']:
tcex.playbook.add_output('app.colors', color, 'StringArray')
tcex.playbook.write_output() # writes the output stored in output_data
.. code-block:: json
:linenos:
:lineno-start: 1
{
"my_color-String": {
"key": "my_color",
"type": "String",
"value": "blue"
},
"my_numbers-String": {
"key": "my_numbers",
"type": "String",
"value": "seven"
},
"my_numbers-StringArray": {
"key": "my_numbers",
"type": "StringArray",
"value": ["seven", "five"]
}
}
Args:
key (string): The variable name to write to storage.
value (any): The value to write to storage.
variable_type (string): The variable type being written.
"""
index = '{}-{}'.format(key, variable_type)
self.output_data.setdefault(index, {})
if value is None:
return
if variable_type in ['String', 'Binary', 'KeyValue', 'TCEntity', 'TCEnhancedEntity']:
self.output_data[index] = {'key': key, 'type': variable_type, 'value': value}
elif variable_type in [
'StringArray',
'BinaryArray',
'KeyValueArray',
'TCEntityArray',
'TCEnhancedEntityArray',
]:
self.output_data[index].setdefault('key', key)
self.output_data[index].setdefault('type', variable_type)
if isinstance(value, list):
self.output_data[index].setdefault('value', []).extend(value)
else:
self.output_data[index].setdefault('value', []).append(value) | [
"def",
"add_output",
"(",
"self",
",",
"key",
",",
"value",
",",
"variable_type",
")",
":",
"index",
"=",
"'{}-{}'",
".",
"format",
"(",
"key",
",",
"variable_type",
")",
"self",
".",
"output_data",
".",
"setdefault",
"(",
"index",
",",
"{",
"}",
")",
... | Dynamically add output to output_data dictionary to be written to DB later.
This method provides an alternative and more dynamic way to create output variables in an
App. Instead of storing the output data manually and writing all at once the data can be
stored inline, when it is generated and then written before the App completes.
.. code-block:: python
:linenos:
:lineno-start: 1
for color in ['blue', 'red', 'yellow']:
tcex.playbook.add_output('app.colors', color, 'StringArray')
tcex.playbook.write_output() # writes the output stored in output_data
.. code-block:: json
:linenos:
:lineno-start: 1
{
"my_color-String": {
"key": "my_color",
"type": "String",
"value": "blue"
},
"my_numbers-String": {
"key": "my_numbers",
"type": "String",
"value": "seven"
},
"my_numbers-StringArray": {
"key": "my_numbers",
"type": "StringArray",
"value": ["seven", "five"]
}
}
Args:
key (string): The variable name to write to storage.
value (any): The value to write to storage.
variable_type (string): The variable type being written. | [
"Dynamically",
"add",
"output",
"to",
"output_data",
"dictionary",
"to",
"be",
"written",
"to",
"DB",
"later",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L72-L134 | train | 27,529 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.aot_blpop | def aot_blpop(self): # pylint: disable=R1710
"""Subscribe to AOT action channel."""
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
res = None
try:
self.tcex.log.info('Blocking for AOT message.')
msg_data = self.db.blpop(
self.tcex.default_args.tc_action_channel,
timeout=self.tcex.default_args.tc_terminate_seconds,
)
if msg_data is None:
self.tcex.exit(0, 'AOT subscription timeout reached.')
msg_data = json.loads(msg_data[1])
msg_type = msg_data.get('type', 'terminate')
if msg_type == 'execute':
res = msg_data.get('params', {})
elif msg_type == 'terminate':
self.tcex.exit(0, 'Received AOT terminate message.')
else:
self.tcex.log.warn('Unsupported AOT message type: ({}).'.format(msg_type))
res = self.aot_blpop()
except Exception as e:
self.tcex.exit(1, 'Exception during AOT subscription ({}).'.format(e))
return res | python | def aot_blpop(self): # pylint: disable=R1710
"""Subscribe to AOT action channel."""
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
res = None
try:
self.tcex.log.info('Blocking for AOT message.')
msg_data = self.db.blpop(
self.tcex.default_args.tc_action_channel,
timeout=self.tcex.default_args.tc_terminate_seconds,
)
if msg_data is None:
self.tcex.exit(0, 'AOT subscription timeout reached.')
msg_data = json.loads(msg_data[1])
msg_type = msg_data.get('type', 'terminate')
if msg_type == 'execute':
res = msg_data.get('params', {})
elif msg_type == 'terminate':
self.tcex.exit(0, 'Received AOT terminate message.')
else:
self.tcex.log.warn('Unsupported AOT message type: ({}).'.format(msg_type))
res = self.aot_blpop()
except Exception as e:
self.tcex.exit(1, 'Exception during AOT subscription ({}).'.format(e))
return res | [
"def",
"aot_blpop",
"(",
"self",
")",
":",
"# pylint: disable=R1710",
"if",
"self",
".",
"tcex",
".",
"default_args",
".",
"tc_playbook_db_type",
"==",
"'Redis'",
":",
"res",
"=",
"None",
"try",
":",
"self",
".",
"tcex",
".",
"log",
".",
"info",
"(",
"'B... | Subscribe to AOT action channel. | [
"Subscribe",
"to",
"AOT",
"action",
"channel",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L136-L162 | train | 27,530 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.aot_rpush | def aot_rpush(self, exit_code):
"""Push message to AOT action channel."""
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
try:
self.db.rpush(self.tcex.default_args.tc_exit_channel, exit_code)
except Exception as e:
self.tcex.exit(1, 'Exception during AOT exit push ({}).'.format(e)) | python | def aot_rpush(self, exit_code):
"""Push message to AOT action channel."""
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
try:
self.db.rpush(self.tcex.default_args.tc_exit_channel, exit_code)
except Exception as e:
self.tcex.exit(1, 'Exception during AOT exit push ({}).'.format(e)) | [
"def",
"aot_rpush",
"(",
"self",
",",
"exit_code",
")",
":",
"if",
"self",
".",
"tcex",
".",
"default_args",
".",
"tc_playbook_db_type",
"==",
"'Redis'",
":",
"try",
":",
"self",
".",
"db",
".",
"rpush",
"(",
"self",
".",
"tcex",
".",
"default_args",
"... | Push message to AOT action channel. | [
"Push",
"message",
"to",
"AOT",
"action",
"channel",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L164-L170 | train | 27,531 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.check_output_variable | def check_output_variable(self, variable):
"""Check to see if output variable was requested by downstream app.
Using the auto generated dictionary of output variables check to see if provided
variable was requested by downstream app.
Args:
variable (string): The variable name, not the full variable.
Returns:
(boolean): Boolean value indicator whether a match was found.
"""
match = False
if variable in self.out_variables:
match = True
return match | python | def check_output_variable(self, variable):
"""Check to see if output variable was requested by downstream app.
Using the auto generated dictionary of output variables check to see if provided
variable was requested by downstream app.
Args:
variable (string): The variable name, not the full variable.
Returns:
(boolean): Boolean value indicator whether a match was found.
"""
match = False
if variable in self.out_variables:
match = True
return match | [
"def",
"check_output_variable",
"(",
"self",
",",
"variable",
")",
":",
"match",
"=",
"False",
"if",
"variable",
"in",
"self",
".",
"out_variables",
":",
"match",
"=",
"True",
"return",
"match"
] | Check to see if output variable was requested by downstream app.
Using the auto generated dictionary of output variables check to see if provided
variable was requested by downstream app.
Args:
variable (string): The variable name, not the full variable.
Returns:
(boolean): Boolean value indicator whether a match was found. | [
"Check",
"to",
"see",
"if",
"output",
"variable",
"was",
"requested",
"by",
"downstream",
"app",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L172-L187 | train | 27,532 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create | def create(self, key, value):
"""Create method of CRUD operation for working with KeyValue DB.
This method will automatically determine the variable type and
call the appropriate method to write the data. If a non standard
type is provided the data will be written as RAW data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result string of DB write.
"""
data = None
if key is not None:
key = key.strip()
self.tcex.log.debug(u'create variable {}'.format(key))
# bcs - only for debugging or binary might cause issues
# self.tcex.log.debug(u'variable value: {}'.format(value))
parsed_key = self.parse_variable(key.strip())
variable_type = parsed_key['type']
if variable_type in self.read_data_types:
data = self.create_data_types[variable_type](key, value)
else:
data = self.create_raw(key, value)
return data | python | def create(self, key, value):
"""Create method of CRUD operation for working with KeyValue DB.
This method will automatically determine the variable type and
call the appropriate method to write the data. If a non standard
type is provided the data will be written as RAW data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result string of DB write.
"""
data = None
if key is not None:
key = key.strip()
self.tcex.log.debug(u'create variable {}'.format(key))
# bcs - only for debugging or binary might cause issues
# self.tcex.log.debug(u'variable value: {}'.format(value))
parsed_key = self.parse_variable(key.strip())
variable_type = parsed_key['type']
if variable_type in self.read_data_types:
data = self.create_data_types[variable_type](key, value)
else:
data = self.create_raw(key, value)
return data | [
"def",
"create",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"key",
"=",
"key",
".",
"strip",
"(",
")",
"self",
".",
"tcex",
".",
"log",
".",
"debug",
"(",
"u'create variable {}'",
... | Create method of CRUD operation for working with KeyValue DB.
This method will automatically determine the variable type and
call the appropriate method to write the data. If a non standard
type is provided the data will be written as RAW data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result string of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"working",
"with",
"KeyValue",
"DB",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L189-L215 | train | 27,533 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_data_types | def create_data_types(self):
"""Map of standard playbook variable types to create method."""
return {
'Binary': self.create_binary,
'BinaryArray': self.create_binary_array,
'KeyValue': self.create_key_value,
'KeyValueArray': self.create_key_value_array,
'String': self.create_string,
'StringArray': self.create_string_array,
'TCEntity': self.create_tc_entity,
'TCEntityArray': self.create_tc_entity_array,
} | python | def create_data_types(self):
"""Map of standard playbook variable types to create method."""
return {
'Binary': self.create_binary,
'BinaryArray': self.create_binary_array,
'KeyValue': self.create_key_value,
'KeyValueArray': self.create_key_value_array,
'String': self.create_string,
'StringArray': self.create_string_array,
'TCEntity': self.create_tc_entity,
'TCEntityArray': self.create_tc_entity_array,
} | [
"def",
"create_data_types",
"(",
"self",
")",
":",
"return",
"{",
"'Binary'",
":",
"self",
".",
"create_binary",
",",
"'BinaryArray'",
":",
"self",
".",
"create_binary_array",
",",
"'KeyValue'",
":",
"self",
".",
"create_key_value",
",",
"'KeyValueArray'",
":",
... | Map of standard playbook variable types to create method. | [
"Map",
"of",
"standard",
"playbook",
"variable",
"types",
"to",
"create",
"method",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L218-L229 | train | 27,534 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_output | def create_output(self, key, value, variable_type=None):
"""Wrapper for Create method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if provided variable was requested by
a downstream app and if so create the data in the KeyValue DB.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
variable_type (string): The variable type being written.
Returns:
(string): Result string of DB write.
"""
results = None
if key is not None:
key = key.strip()
key_type = '{}-{}'.format(key, variable_type)
if self.out_variables_type.get(key_type) is not None:
# variable key-type has been requested
v = self.out_variables_type.get(key_type)
self.tcex.log.info(
u'Variable {} was requested by downstream app.'.format(v.get('variable'))
)
if value is not None:
results = self.create(v.get('variable'), value)
else:
self.tcex.log.info(
u'Variable {} has a none value and will not be written.'.format(key)
)
elif self.out_variables.get(key) is not None and variable_type is None:
# variable key has been requested
v = self.out_variables.get(key)
self.tcex.log.info(
u'Variable {} was requested by downstream app.'.format(v.get('variable'))
)
if value is not None:
results = self.create(v.get('variable'), value)
else:
self.tcex.log.info(
u'Variable {} has a none value and will not be written.'.format(
v.get('variable')
)
)
else:
var_value = key
if variable_type is not None:
var_value = key_type
self.tcex.log.info(
u'Variable {} was NOT requested by downstream app.'.format(var_value)
)
return results | python | def create_output(self, key, value, variable_type=None):
"""Wrapper for Create method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if provided variable was requested by
a downstream app and if so create the data in the KeyValue DB.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
variable_type (string): The variable type being written.
Returns:
(string): Result string of DB write.
"""
results = None
if key is not None:
key = key.strip()
key_type = '{}-{}'.format(key, variable_type)
if self.out_variables_type.get(key_type) is not None:
# variable key-type has been requested
v = self.out_variables_type.get(key_type)
self.tcex.log.info(
u'Variable {} was requested by downstream app.'.format(v.get('variable'))
)
if value is not None:
results = self.create(v.get('variable'), value)
else:
self.tcex.log.info(
u'Variable {} has a none value and will not be written.'.format(key)
)
elif self.out_variables.get(key) is not None and variable_type is None:
# variable key has been requested
v = self.out_variables.get(key)
self.tcex.log.info(
u'Variable {} was requested by downstream app.'.format(v.get('variable'))
)
if value is not None:
results = self.create(v.get('variable'), value)
else:
self.tcex.log.info(
u'Variable {} has a none value and will not be written.'.format(
v.get('variable')
)
)
else:
var_value = key
if variable_type is not None:
var_value = key_type
self.tcex.log.info(
u'Variable {} was NOT requested by downstream app.'.format(var_value)
)
return results | [
"def",
"create_output",
"(",
"self",
",",
"key",
",",
"value",
",",
"variable_type",
"=",
"None",
")",
":",
"results",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"key",
"=",
"key",
".",
"strip",
"(",
")",
"key_type",
"=",
"'{}-{}'",
".",
"... | Wrapper for Create method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if provided variable was requested by
a downstream app and if so create the data in the KeyValue DB.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
variable_type (string): The variable type being written.
Returns:
(string): Result string of DB write. | [
"Wrapper",
"for",
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"working",
"with",
"KeyValue",
"DB",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L231-L282 | train | 27,535 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.db | def db(self):
"""Return the correct KV store for this execution."""
if self._db is None:
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
from .tcex_redis import TcExRedis
self._db = TcExRedis(
self.tcex.default_args.tc_playbook_db_path,
self.tcex.default_args.tc_playbook_db_port,
self.tcex.default_args.tc_playbook_db_context,
)
elif self.tcex.default_args.tc_playbook_db_type == 'TCKeyValueAPI':
from .tcex_key_value import TcExKeyValue
self._db = TcExKeyValue(self.tcex)
else:
err = u'Invalid DB Type: ({})'.format(self.tcex.default_args.tc_playbook_db_type)
raise RuntimeError(err)
return self._db | python | def db(self):
"""Return the correct KV store for this execution."""
if self._db is None:
if self.tcex.default_args.tc_playbook_db_type == 'Redis':
from .tcex_redis import TcExRedis
self._db = TcExRedis(
self.tcex.default_args.tc_playbook_db_path,
self.tcex.default_args.tc_playbook_db_port,
self.tcex.default_args.tc_playbook_db_context,
)
elif self.tcex.default_args.tc_playbook_db_type == 'TCKeyValueAPI':
from .tcex_key_value import TcExKeyValue
self._db = TcExKeyValue(self.tcex)
else:
err = u'Invalid DB Type: ({})'.format(self.tcex.default_args.tc_playbook_db_type)
raise RuntimeError(err)
return self._db | [
"def",
"db",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db",
"is",
"None",
":",
"if",
"self",
".",
"tcex",
".",
"default_args",
".",
"tc_playbook_db_type",
"==",
"'Redis'",
":",
"from",
".",
"tcex_redis",
"import",
"TcExRedis",
"self",
".",
"_db",
"="... | Return the correct KV store for this execution. | [
"Return",
"the",
"correct",
"KV",
"store",
"for",
"this",
"execution",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L285-L303 | train | 27,536 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.delete | def delete(self, key):
"""Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None:
data = self.db.delete(key.strip())
else:
self.tcex.log.warning(u'The key field was None.')
return data | python | def delete(self, key):
"""Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None:
data = self.db.delete(key.strip())
else:
self.tcex.log.warning(u'The key field was None.')
return data | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"db",
".",
"delete",
"(",
"key",
".",
"strip",
"(",
")",
")",
"else",
":",
"self",
".",
"tcex",
".",
"lo... | Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write. | [
"Delete",
"method",
"of",
"CRUD",
"operation",
"for",
"all",
"data",
"types",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L305-L319 | train | 27,537 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.exit | def exit(self, code=None, msg=None):
"""Playbook wrapper on TcEx exit method
Playbooks do not support partial failures so we change the exit method from 3 to 1 and call
it a partial success instead.
Args:
code (Optional [integer]): The exit code value for the app.
"""
if code is None:
code = self.tcex.exit_code
if code == 3:
self.tcex.log.info(u'Changing exit code from 3 to 0.')
code = 0 # playbooks doesn't support partial failure
elif code not in [0, 1]:
code = 1
self.tcex.exit(code, msg) | python | def exit(self, code=None, msg=None):
"""Playbook wrapper on TcEx exit method
Playbooks do not support partial failures so we change the exit method from 3 to 1 and call
it a partial success instead.
Args:
code (Optional [integer]): The exit code value for the app.
"""
if code is None:
code = self.tcex.exit_code
if code == 3:
self.tcex.log.info(u'Changing exit code from 3 to 0.')
code = 0 # playbooks doesn't support partial failure
elif code not in [0, 1]:
code = 1
self.tcex.exit(code, msg) | [
"def",
"exit",
"(",
"self",
",",
"code",
"=",
"None",
",",
"msg",
"=",
"None",
")",
":",
"if",
"code",
"is",
"None",
":",
"code",
"=",
"self",
".",
"tcex",
".",
"exit_code",
"if",
"code",
"==",
"3",
":",
"self",
".",
"tcex",
".",
"log",
".",
... | Playbook wrapper on TcEx exit method
Playbooks do not support partial failures so we change the exit method from 3 to 1 and call
it a partial success instead.
Args:
code (Optional [integer]): The exit code value for the app. | [
"Playbook",
"wrapper",
"on",
"TcEx",
"exit",
"method"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L321-L337 | train | 27,538 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.parse_variable | def parse_variable(self, variable):
"""Method to parse an input or output variable.
**Example Variable**::
#App:1234:output!String
Args:
variable (string): The variable name to parse.
Returns:
(dictionary): Result of parsed string.
"""
data = None
if variable is not None:
variable = variable.strip()
if re.match(self._variable_match, variable):
var = re.search(self._variable_parse, variable)
data = {
'root': var.group(0),
'job_id': var.group(2),
'name': var.group(3),
'type': var.group(4),
}
return data | python | def parse_variable(self, variable):
"""Method to parse an input or output variable.
**Example Variable**::
#App:1234:output!String
Args:
variable (string): The variable name to parse.
Returns:
(dictionary): Result of parsed string.
"""
data = None
if variable is not None:
variable = variable.strip()
if re.match(self._variable_match, variable):
var = re.search(self._variable_parse, variable)
data = {
'root': var.group(0),
'job_id': var.group(2),
'name': var.group(3),
'type': var.group(4),
}
return data | [
"def",
"parse_variable",
"(",
"self",
",",
"variable",
")",
":",
"data",
"=",
"None",
"if",
"variable",
"is",
"not",
"None",
":",
"variable",
"=",
"variable",
".",
"strip",
"(",
")",
"if",
"re",
".",
"match",
"(",
"self",
".",
"_variable_match",
",",
... | Method to parse an input or output variable.
**Example Variable**::
#App:1234:output!String
Args:
variable (string): The variable name to parse.
Returns:
(dictionary): Result of parsed string. | [
"Method",
"to",
"parse",
"an",
"input",
"or",
"output",
"variable",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L355-L379 | train | 27,539 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read | def read(self, key, array=False, embedded=True):
"""Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically determine the variable type to read.
Args:
key (string): The variable to read from the DB.
array (boolean): Convert string/dict to Array/List before returning.
embedded (boolean): Resolve embedded variables.
Returns:
(any): Results retrieved from DB
"""
self.tcex.log.debug('read variable {}'.format(key))
# if a non-variable value is passed it should be the default
data = key
if key is not None:
key = key.strip()
key_type = self.variable_type(key)
if re.match(self._variable_match, key):
if key_type in self.read_data_types:
# handle types with embedded variable
if key_type in ['Binary', 'BinaryArray']:
data = self.read_data_types[key_type](key)
else:
data = self.read_data_types[key_type](key, embedded)
else:
data = self.read_raw(key)
else:
if key_type == 'String':
# replace "\s" with a space only for user input.
# using '\\s' will prevent replacement.
data = re.sub(r'(?<!\\)\\s', ' ', data)
data = re.sub(r'\\\\s', '\\s', data)
if embedded:
# check for any embedded variables
data = self.read_embedded(data, key_type)
# return data as a list
if array and not isinstance(data, list):
if data is not None:
data = [data]
else:
# Adding none value to list breaks App logic. It's better to not request Array
# and build array externally if None values are required.
data = []
# self.tcex.log.debug(u'read data {}'.format(self.tcex.s(data)))
return data | python | def read(self, key, array=False, embedded=True):
"""Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically determine the variable type to read.
Args:
key (string): The variable to read from the DB.
array (boolean): Convert string/dict to Array/List before returning.
embedded (boolean): Resolve embedded variables.
Returns:
(any): Results retrieved from DB
"""
self.tcex.log.debug('read variable {}'.format(key))
# if a non-variable value is passed it should be the default
data = key
if key is not None:
key = key.strip()
key_type = self.variable_type(key)
if re.match(self._variable_match, key):
if key_type in self.read_data_types:
# handle types with embedded variable
if key_type in ['Binary', 'BinaryArray']:
data = self.read_data_types[key_type](key)
else:
data = self.read_data_types[key_type](key, embedded)
else:
data = self.read_raw(key)
else:
if key_type == 'String':
# replace "\s" with a space only for user input.
# using '\\s' will prevent replacement.
data = re.sub(r'(?<!\\)\\s', ' ', data)
data = re.sub(r'\\\\s', '\\s', data)
if embedded:
# check for any embedded variables
data = self.read_embedded(data, key_type)
# return data as a list
if array and not isinstance(data, list):
if data is not None:
data = [data]
else:
# Adding none value to list breaks App logic. It's better to not request Array
# and build array externally if None values are required.
data = []
# self.tcex.log.debug(u'read data {}'.format(self.tcex.s(data)))
return data | [
"def",
"read",
"(",
"self",
",",
"key",
",",
"array",
"=",
"False",
",",
"embedded",
"=",
"True",
")",
":",
"self",
".",
"tcex",
".",
"log",
".",
"debug",
"(",
"'read variable {}'",
".",
"format",
"(",
"key",
")",
")",
"# if a non-variable value is passe... | Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically determine the variable type to read.
Args:
key (string): The variable to read from the DB.
array (boolean): Convert string/dict to Array/List before returning.
embedded (boolean): Resolve embedded variables.
Returns:
(any): Results retrieved from DB | [
"Read",
"method",
"of",
"CRUD",
"operation",
"for",
"working",
"with",
"KeyValue",
"DB",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L381-L432 | train | 27,540 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_data_types | def read_data_types(self):
"""Map of standard playbook variable types to read method."""
return {
'Binary': self.read_binary,
'BinaryArray': self.read_binary_array,
'KeyValue': self.read_key_value,
'KeyValueArray': self.read_key_value_array,
'String': self.read_string,
'StringArray': self.read_string_array,
'TCEntity': self.read_tc_entity,
'TCEntityArray': self.read_tc_entity_array,
} | python | def read_data_types(self):
"""Map of standard playbook variable types to read method."""
return {
'Binary': self.read_binary,
'BinaryArray': self.read_binary_array,
'KeyValue': self.read_key_value,
'KeyValueArray': self.read_key_value_array,
'String': self.read_string,
'StringArray': self.read_string_array,
'TCEntity': self.read_tc_entity,
'TCEntityArray': self.read_tc_entity_array,
} | [
"def",
"read_data_types",
"(",
"self",
")",
":",
"return",
"{",
"'Binary'",
":",
"self",
".",
"read_binary",
",",
"'BinaryArray'",
":",
"self",
".",
"read_binary_array",
",",
"'KeyValue'",
":",
"self",
".",
"read_key_value",
",",
"'KeyValueArray'",
":",
"self"... | Map of standard playbook variable types to read method. | [
"Map",
"of",
"standard",
"playbook",
"variable",
"types",
"to",
"read",
"method",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L448-L459 | train | 27,541 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_embedded | def read_embedded(self, data, parent_var_type):
"""Read method for "mixed" variable type.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables. There usually is no reason to call
this method directly.
This method will automatically covert variables embedded in a string with data retrieved
from DB. If there are no keys/variables the raw string will be returned.
Examples::
DB Values
#App:7979:variable_name!String:
"embedded \\"variable\\""
#App:7979:two!String:
"two"
#App:7979:variable_name!StringArray:
["one", "two", "three"]
Examples 1:
Input: "This input has a embedded #App:7979:variable_name!String"
Examples 2:
Input: ["one", #App:7979:two!String, "three"]
Examples 3:
Input: [{
"key": "embedded string",
"value": "This input has a embedded #App:7979:variable_name!String"
}, {
"key": "string array",
"value": #App:7979:variable_name!StringArray
}, {
"key": "string",
"value": #App:7979:variable_name!String
}]
Args:
data (string): The data to parsed and updated from the DB.
parent_var_type (string): The parent type of the embedded variable.
Returns:
(string): Results retrieved from DB
"""
if data is None:
return data
# iterate all matching variables
for var in (v.group(0) for v in re.finditer(self._variable_parse, str(data))):
self.tcex.log.debug(
'embedded variable: {}, parent_var_type: {}'.format(var, parent_var_type)
)
key_type = self.variable_type(var)
val = self.read(var)
if val is None:
val = ''
elif key_type != 'String':
var = r'"?{}"?'.format(var) # replace quotes if they exist
val = json.dumps(val)
data = re.sub(var, val, data)
return data | python | def read_embedded(self, data, parent_var_type):
"""Read method for "mixed" variable type.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables. There usually is no reason to call
this method directly.
This method will automatically covert variables embedded in a string with data retrieved
from DB. If there are no keys/variables the raw string will be returned.
Examples::
DB Values
#App:7979:variable_name!String:
"embedded \\"variable\\""
#App:7979:two!String:
"two"
#App:7979:variable_name!StringArray:
["one", "two", "three"]
Examples 1:
Input: "This input has a embedded #App:7979:variable_name!String"
Examples 2:
Input: ["one", #App:7979:two!String, "three"]
Examples 3:
Input: [{
"key": "embedded string",
"value": "This input has a embedded #App:7979:variable_name!String"
}, {
"key": "string array",
"value": #App:7979:variable_name!StringArray
}, {
"key": "string",
"value": #App:7979:variable_name!String
}]
Args:
data (string): The data to parsed and updated from the DB.
parent_var_type (string): The parent type of the embedded variable.
Returns:
(string): Results retrieved from DB
"""
if data is None:
return data
# iterate all matching variables
for var in (v.group(0) for v in re.finditer(self._variable_parse, str(data))):
self.tcex.log.debug(
'embedded variable: {}, parent_var_type: {}'.format(var, parent_var_type)
)
key_type = self.variable_type(var)
val = self.read(var)
if val is None:
val = ''
elif key_type != 'String':
var = r'"?{}"?'.format(var) # replace quotes if they exist
val = json.dumps(val)
data = re.sub(var, val, data)
return data | [
"def",
"read_embedded",
"(",
"self",
",",
"data",
",",
"parent_var_type",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"data",
"# iterate all matching variables",
"for",
"var",
"in",
"(",
"v",
".",
"group",
"(",
"0",
")",
"for",
"v",
"in",
"re",
... | Read method for "mixed" variable type.
.. Note:: The ``read()`` method will automatically determine if the input is a variable or
needs to be searched for embedded variables. There usually is no reason to call
this method directly.
This method will automatically covert variables embedded in a string with data retrieved
from DB. If there are no keys/variables the raw string will be returned.
Examples::
DB Values
#App:7979:variable_name!String:
"embedded \\"variable\\""
#App:7979:two!String:
"two"
#App:7979:variable_name!StringArray:
["one", "two", "three"]
Examples 1:
Input: "This input has a embedded #App:7979:variable_name!String"
Examples 2:
Input: ["one", #App:7979:two!String, "three"]
Examples 3:
Input: [{
"key": "embedded string",
"value": "This input has a embedded #App:7979:variable_name!String"
}, {
"key": "string array",
"value": #App:7979:variable_name!StringArray
}, {
"key": "string",
"value": #App:7979:variable_name!String
}]
Args:
data (string): The data to parsed and updated from the DB.
parent_var_type (string): The parent type of the embedded variable.
Returns:
(string): Results retrieved from DB | [
"Read",
"method",
"for",
"mixed",
"variable",
"type",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L461-L524 | train | 27,542 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.variable_type | def variable_type(self, variable):
"""Get the Type from the variable string or default to String type.
The default type is "String" for those cases when the input variable is
contains not "DB variable" and is just a String.
**Example Variable**::
#App:1234:output!StringArray returns **StringArray**
**Example String**::
"My Data" returns **String**
Args:
variable (string): The variable to be parsed
Returns:
(string): The variable type.
"""
var_type = 'String'
if variable is not None:
variable = variable.strip()
# self.tcex.log.info(u'Variable {}'.format(variable))
if re.match(self._variable_match, variable):
var_type = re.search(self._variable_parse, variable).group(4)
return var_type | python | def variable_type(self, variable):
"""Get the Type from the variable string or default to String type.
The default type is "String" for those cases when the input variable is
contains not "DB variable" and is just a String.
**Example Variable**::
#App:1234:output!StringArray returns **StringArray**
**Example String**::
"My Data" returns **String**
Args:
variable (string): The variable to be parsed
Returns:
(string): The variable type.
"""
var_type = 'String'
if variable is not None:
variable = variable.strip()
# self.tcex.log.info(u'Variable {}'.format(variable))
if re.match(self._variable_match, variable):
var_type = re.search(self._variable_parse, variable).group(4)
return var_type | [
"def",
"variable_type",
"(",
"self",
",",
"variable",
")",
":",
"var_type",
"=",
"'String'",
"if",
"variable",
"is",
"not",
"None",
":",
"variable",
"=",
"variable",
".",
"strip",
"(",
")",
"# self.tcex.log.info(u'Variable {}'.format(variable))",
"if",
"re",
"."... | Get the Type from the variable string or default to String type.
The default type is "String" for those cases when the input variable is
contains not "DB variable" and is just a String.
**Example Variable**::
#App:1234:output!StringArray returns **StringArray**
**Example String**::
"My Data" returns **String**
Args:
variable (string): The variable to be parsed
Returns:
(string): The variable type. | [
"Get",
"the",
"Type",
"from",
"the",
"variable",
"string",
"or",
"default",
"to",
"String",
"type",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L526-L552 | train | 27,543 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.wrap_embedded_keyvalue | def wrap_embedded_keyvalue(self, data):
"""Wrap keyvalue embedded variable in double quotes.
Args:
data (string): The data with embedded variables.
Returns:
(string): Results retrieved from DB
"""
if data is not None:
try:
data = u'{}'.format(data)
# variables = re.findall(self._vars_keyvalue_embedded, u'{}'.format(data))
except UnicodeEncodeError:
# variables = re.findall(self._vars_keyvalue_embedded, data)
pass
variables = []
for v in re.finditer(self._vars_keyvalue_embedded, data):
variables.append(v.group(0))
for var in set(variables): # recursion over set to handle duplicates
# pull (#App:1441:embedded_string!String) from (": #App:1441:embedded_string!String)
variable_string = re.search(self._variable_parse, var).group(0)
# reformat to replace the correct instance only, handling the case where a variable
# is embedded multiple times in the same key value array.
data = data.replace(var, '": "{}"'.format(variable_string))
return data | python | def wrap_embedded_keyvalue(self, data):
"""Wrap keyvalue embedded variable in double quotes.
Args:
data (string): The data with embedded variables.
Returns:
(string): Results retrieved from DB
"""
if data is not None:
try:
data = u'{}'.format(data)
# variables = re.findall(self._vars_keyvalue_embedded, u'{}'.format(data))
except UnicodeEncodeError:
# variables = re.findall(self._vars_keyvalue_embedded, data)
pass
variables = []
for v in re.finditer(self._vars_keyvalue_embedded, data):
variables.append(v.group(0))
for var in set(variables): # recursion over set to handle duplicates
# pull (#App:1441:embedded_string!String) from (": #App:1441:embedded_string!String)
variable_string = re.search(self._variable_parse, var).group(0)
# reformat to replace the correct instance only, handling the case where a variable
# is embedded multiple times in the same key value array.
data = data.replace(var, '": "{}"'.format(variable_string))
return data | [
"def",
"wrap_embedded_keyvalue",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"not",
"None",
":",
"try",
":",
"data",
"=",
"u'{}'",
".",
"format",
"(",
"data",
")",
"# variables = re.findall(self._vars_keyvalue_embedded, u'{}'.format(data))",
"except",
... | Wrap keyvalue embedded variable in double quotes.
Args:
data (string): The data with embedded variables.
Returns:
(string): Results retrieved from DB | [
"Wrap",
"keyvalue",
"embedded",
"variable",
"in",
"double",
"quotes",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L554-L581 | train | 27,544 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.write_output | def write_output(self):
"""Write all stored output data to storage."""
for data in self.output_data.values():
self.create_output(data.get('key'), data.get('value'), data.get('type')) | python | def write_output(self):
"""Write all stored output data to storage."""
for data in self.output_data.values():
self.create_output(data.get('key'), data.get('value'), data.get('type')) | [
"def",
"write_output",
"(",
"self",
")",
":",
"for",
"data",
"in",
"self",
".",
"output_data",
".",
"values",
"(",
")",
":",
"self",
".",
"create_output",
"(",
"data",
".",
"get",
"(",
"'key'",
")",
",",
"data",
".",
"get",
"(",
"'value'",
")",
","... | Write all stored output data to storage. | [
"Write",
"all",
"stored",
"output",
"data",
"to",
"storage",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L583-L586 | train | 27,545 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_binary | def create_binary(self, key, value):
"""Create method of CRUD operation for binary data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
try:
# py2
# convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
data = self.db.create(
key.strip(), json.dumps(base64.b64encode(bytes(value)).decode('utf-8'))
)
except TypeError:
# py3
# set encoding on string and convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
data = self.db.create(
key.strip(), json.dumps(base64.b64encode(bytes(value, 'utf-8')).decode('utf-8'))
)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | python | def create_binary(self, key, value):
"""Create method of CRUD operation for binary data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
try:
# py2
# convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
data = self.db.create(
key.strip(), json.dumps(base64.b64encode(bytes(value)).decode('utf-8'))
)
except TypeError:
# py3
# set encoding on string and convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
data = self.db.create(
key.strip(), json.dumps(base64.b64encode(bytes(value, 'utf-8')).decode('utf-8'))
)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | [
"def",
"create_binary",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"try",
":",
"# py2",
"# convert to bytes as required for b64encode",
"# decode bytes for j... | Create method of CRUD operation for binary data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"binary",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L596-L624 | train | 27,546 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_binary | def read_binary(self, key, b64decode=True, decode=False):
"""Read method of CRUD operation for binary data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(bytes|string): Results retrieved from DB.
"""
data = None
if key is not None:
data = self.db.read(key.strip())
if data is not None:
data = json.loads(data)
if b64decode:
# if requested decode the base64 string
data = base64.b64decode(data)
if decode:
try:
# if requested decode bytes to a string
data = data.decode('utf-8')
except UnicodeDecodeError:
# for data written an upstream java App
data = data.decode('latin-1')
else:
self.tcex.log.warning(u'The key field was None.')
return data | python | def read_binary(self, key, b64decode=True, decode=False):
"""Read method of CRUD operation for binary data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(bytes|string): Results retrieved from DB.
"""
data = None
if key is not None:
data = self.db.read(key.strip())
if data is not None:
data = json.loads(data)
if b64decode:
# if requested decode the base64 string
data = base64.b64decode(data)
if decode:
try:
# if requested decode bytes to a string
data = data.decode('utf-8')
except UnicodeDecodeError:
# for data written an upstream java App
data = data.decode('latin-1')
else:
self.tcex.log.warning(u'The key field was None.')
return data | [
"def",
"read_binary",
"(",
"self",
",",
"key",
",",
"b64decode",
"=",
"True",
",",
"decode",
"=",
"False",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"db",
".",
"read",
"(",
"key",
".",
"strip"... | Read method of CRUD operation for binary data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(bytes|string): Results retrieved from DB. | [
"Read",
"method",
"of",
"CRUD",
"operation",
"for",
"binary",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L626-L654 | train | 27,547 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_binary_array | def create_binary_array(self, key, value):
"""Create method of CRUD operation for binary array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
value_encoded = []
for v in value:
try:
# py2
# convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
value_encoded.append(base64.b64encode(bytes(v)).decode('utf-8'))
except TypeError:
# py3
# set encoding on string and convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
value_encoded.append(base64.b64encode(bytes(v, 'utf-8')).decode('utf-8'))
data = self.db.create(key.strip(), json.dumps(value_encoded))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | python | def create_binary_array(self, key, value):
"""Create method of CRUD operation for binary array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
value_encoded = []
for v in value:
try:
# py2
# convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
value_encoded.append(base64.b64encode(bytes(v)).decode('utf-8'))
except TypeError:
# py3
# set encoding on string and convert to bytes as required for b64encode
# decode bytes for json serialization as required for json dumps
value_encoded.append(base64.b64encode(bytes(v, 'utf-8')).decode('utf-8'))
data = self.db.create(key.strip(), json.dumps(value_encoded))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | [
"def",
"create_binary_array",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"value_encoded",
"=",
"[",
"]",
"for",
"v",
"in",
"value",
":",
"try",
"... | Create method of CRUD operation for binary array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"binary",
"array",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L656-L683 | train | 27,548 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_binary_array | def read_binary_array(self, key, b64decode=True, decode=False):
"""Read method of CRUD operation for binary array data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(list): Results retrieved from DB.
"""
data = None
if key is not None:
data = self.db.read(key.strip())
if data is not None:
data_decoded = []
for d in json.loads(data, object_pairs_hook=OrderedDict):
if b64decode:
# if requested decode the base64 string
dd = base64.b64decode(d)
if decode:
# if requested decode bytes to a string
try:
dd = dd.decode('utf-8')
except UnicodeDecodeError:
# for data written an upstream java App
dd = dd.decode('latin-1')
data_decoded.append(dd)
else:
# for validation in tcrun it's easier to validate the base64 data
data_decoded.append(d)
data = data_decoded
else:
self.tcex.log.warning(u'The key field was None.')
return data | python | def read_binary_array(self, key, b64decode=True, decode=False):
"""Read method of CRUD operation for binary array data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(list): Results retrieved from DB.
"""
data = None
if key is not None:
data = self.db.read(key.strip())
if data is not None:
data_decoded = []
for d in json.loads(data, object_pairs_hook=OrderedDict):
if b64decode:
# if requested decode the base64 string
dd = base64.b64decode(d)
if decode:
# if requested decode bytes to a string
try:
dd = dd.decode('utf-8')
except UnicodeDecodeError:
# for data written an upstream java App
dd = dd.decode('latin-1')
data_decoded.append(dd)
else:
# for validation in tcrun it's easier to validate the base64 data
data_decoded.append(d)
data = data_decoded
else:
self.tcex.log.warning(u'The key field was None.')
return data | [
"def",
"read_binary_array",
"(",
"self",
",",
"key",
",",
"b64decode",
"=",
"True",
",",
"decode",
"=",
"False",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"db",
".",
"read",
"(",
"key",
".",
"... | Read method of CRUD operation for binary array data.
Args:
key (string): The variable to read from the DB.
b64decode (bool): If true the data will be base64 decoded.
decode (bool): If true the data will be decoded to a String.
Returns:
(list): Results retrieved from DB. | [
"Read",
"method",
"of",
"CRUD",
"operation",
"for",
"binary",
"array",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L685-L719 | train | 27,549 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_raw | def create_raw(self, key, value):
"""Create method of CRUD operation for raw data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
data = self.db.create(key.strip(), value)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | python | def create_raw(self, key, value):
"""Create method of CRUD operation for raw data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
data = self.db.create(key.strip(), value)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | [
"def",
"create_raw",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"db",
".",
"create",
"(",
"key",
".",
"strip",
"(",
... | Create method of CRUD operation for raw data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"raw",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L823-L838 | train | 27,550 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_raw | def read_raw(self, key):
"""Read method of CRUD operation for raw data.
Args:
key (string): The variable to read from the DB.
Returns:
(any): Results retrieved from DB.
"""
data = None
if key is not None:
data = self.db.read(key.strip())
else:
self.tcex.log.warning(u'The key field was None.')
return data | python | def read_raw(self, key):
"""Read method of CRUD operation for raw data.
Args:
key (string): The variable to read from the DB.
Returns:
(any): Results retrieved from DB.
"""
data = None
if key is not None:
data = self.db.read(key.strip())
else:
self.tcex.log.warning(u'The key field was None.')
return data | [
"def",
"read_raw",
"(",
"self",
",",
"key",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"db",
".",
"read",
"(",
"key",
".",
"strip",
"(",
")",
")",
"else",
":",
"self",
".",
"tcex",
".",
"lo... | Read method of CRUD operation for raw data.
Args:
key (string): The variable to read from the DB.
Returns:
(any): Results retrieved from DB. | [
"Read",
"method",
"of",
"CRUD",
"operation",
"for",
"raw",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L840-L854 | train | 27,551 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_string | def create_string(self, key, value):
"""Create method of CRUD operation for string data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
if isinstance(value, (bool, list, int, dict)):
# value = str(value)
value = u'{}'.format(value)
# data = self.db.create(key.strip(), str(json.dumps(value)))
data = self.db.create(key.strip(), u'{}'.format(json.dumps(value)))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | python | def create_string(self, key, value):
"""Create method of CRUD operation for string data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
if isinstance(value, (bool, list, int, dict)):
# value = str(value)
value = u'{}'.format(value)
# data = self.db.create(key.strip(), str(json.dumps(value)))
data = self.db.create(key.strip(), u'{}'.format(json.dumps(value)))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | [
"def",
"create_string",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"bool",
",",
"list",
",",
"int",
... | Create method of CRUD operation for string data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"string",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L856-L875 | train | 27,552 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_string | def read_string(self, key, embedded=True):
"""Read method of CRUD operation for string data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(string): Results retrieved from DB.
"""
data = None
if key is not None:
key_type = self.variable_type(key)
data = self.db.read(key.strip())
if data is not None:
# handle improperly saved string
try:
data = json.loads(data)
if embedded:
data = self.read_embedded(data, key_type)
if data is not None:
# reverted the previous change where data was encoded due to issues where
# it broke the operator method in py3 (e.g. b'1' ne '1').
# data = str(data)
data = u'{}'.format(data)
except ValueError as e:
err = u'Failed loading JSON data ({}). Error: ({})'.format(data, e)
self.tcex.log.error(err)
else:
self.tcex.log.warning(u'The key field was None.')
return data | python | def read_string(self, key, embedded=True):
"""Read method of CRUD operation for string data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(string): Results retrieved from DB.
"""
data = None
if key is not None:
key_type = self.variable_type(key)
data = self.db.read(key.strip())
if data is not None:
# handle improperly saved string
try:
data = json.loads(data)
if embedded:
data = self.read_embedded(data, key_type)
if data is not None:
# reverted the previous change where data was encoded due to issues where
# it broke the operator method in py3 (e.g. b'1' ne '1').
# data = str(data)
data = u'{}'.format(data)
except ValueError as e:
err = u'Failed loading JSON data ({}). Error: ({})'.format(data, e)
self.tcex.log.error(err)
else:
self.tcex.log.warning(u'The key field was None.')
return data | [
"def",
"read_string",
"(",
"self",
",",
"key",
",",
"embedded",
"=",
"True",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"key_type",
"=",
"self",
".",
"variable_type",
"(",
"key",
")",
"data",
"=",
"self",
".",
"db",
".",
... | Read method of CRUD operation for string data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(string): Results retrieved from DB. | [
"Read",
"method",
"of",
"CRUD",
"operation",
"for",
"string",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L877-L907 | train | 27,553 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_string_array | def create_string_array(self, key, value):
"""Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
if isinstance(value, (list)):
data = self.db.create(key.strip(), json.dumps(value))
else:
# used to save raw value with embedded variables
data = self.db.create(key.strip(), value)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | python | def create_string_array(self, key, value):
"""Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
if isinstance(value, (list)):
data = self.db.create(key.strip(), json.dumps(value))
else:
# used to save raw value with embedded variables
data = self.db.create(key.strip(), value)
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | [
"def",
"create_string_array",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
")",
")",
":",
"data... | Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"string",
"array",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L909-L928 | train | 27,554 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.read_string_array | def read_string_array(self, key, embedded=True):
"""Read method of CRUD operation for string array data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(list): Results retrieved from DB.
"""
data = None
if key is not None:
key_type = self.variable_type(key)
data = self.db.read(key.strip())
if embedded:
data = self.read_embedded(data, key_type)
if data is not None:
try:
data = json.loads(data, object_pairs_hook=OrderedDict)
except ValueError as e:
err = u'Failed loading JSON data ({}). Error: ({})'.format(data, e)
self.tcex.log.error(err)
self.tcex.message_tc(err)
self.tcex.exit(1)
else:
self.tcex.log.warning(u'The key field was None.')
return data | python | def read_string_array(self, key, embedded=True):
"""Read method of CRUD operation for string array data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(list): Results retrieved from DB.
"""
data = None
if key is not None:
key_type = self.variable_type(key)
data = self.db.read(key.strip())
if embedded:
data = self.read_embedded(data, key_type)
if data is not None:
try:
data = json.loads(data, object_pairs_hook=OrderedDict)
except ValueError as e:
err = u'Failed loading JSON data ({}). Error: ({})'.format(data, e)
self.tcex.log.error(err)
self.tcex.message_tc(err)
self.tcex.exit(1)
else:
self.tcex.log.warning(u'The key field was None.')
return data | [
"def",
"read_string_array",
"(",
"self",
",",
"key",
",",
"embedded",
"=",
"True",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
":",
"key_type",
"=",
"self",
".",
"variable_type",
"(",
"key",
")",
"data",
"=",
"self",
".",
"db",
... | Read method of CRUD operation for string array data.
Args:
key (string): The variable to read from the DB.
embedded (boolean): Resolve embedded variables.
Returns:
(list): Results retrieved from DB. | [
"Read",
"method",
"of",
"CRUD",
"operation",
"for",
"string",
"array",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L930-L956 | train | 27,555 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.create_tc_entity | def create_tc_entity(self, key, value):
"""Create method of CRUD operation for TC entity data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
data = self.db.create(key.strip(), json.dumps(value))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | python | def create_tc_entity(self, key, value):
"""Create method of CRUD operation for TC entity data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None and value is not None:
data = self.db.create(key.strip(), json.dumps(value))
else:
self.tcex.log.warning(u'The key or value field was None.')
return data | [
"def",
"create_tc_entity",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"data",
"=",
"None",
"if",
"key",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
":",
"data",
"=",
"self",
".",
"db",
".",
"create",
"(",
"key",
".",
"strip",
... | Create method of CRUD operation for TC entity data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | [
"Create",
"method",
"of",
"CRUD",
"operation",
"for",
"TC",
"entity",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L959-L974 | train | 27,556 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.entity_to_bulk | def entity_to_bulk(entities, resource_type_parent):
"""Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(dictionary): A dictionary representing TC Bulk format.
"""
if not isinstance(entities, list):
entities = [entities]
bulk_array = []
for e in entities:
bulk = {'type': e.get('type'), 'ownerName': e.get('ownerName')}
if resource_type_parent in ['Group', 'Task', 'Victim']:
bulk['name'] = e.get('value')
elif resource_type_parent in ['Indicator']:
bulk['confidence'] = e.get('confidence')
bulk['rating'] = e.get('rating')
bulk['summary'] = e.get('value')
bulk_array.append(bulk)
if len(bulk_array) == 1:
return bulk_array[0]
return bulk_array | python | def entity_to_bulk(entities, resource_type_parent):
"""Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(dictionary): A dictionary representing TC Bulk format.
"""
if not isinstance(entities, list):
entities = [entities]
bulk_array = []
for e in entities:
bulk = {'type': e.get('type'), 'ownerName': e.get('ownerName')}
if resource_type_parent in ['Group', 'Task', 'Victim']:
bulk['name'] = e.get('value')
elif resource_type_parent in ['Indicator']:
bulk['confidence'] = e.get('confidence')
bulk['rating'] = e.get('rating')
bulk['summary'] = e.get('value')
bulk_array.append(bulk)
if len(bulk_array) == 1:
return bulk_array[0]
return bulk_array | [
"def",
"entity_to_bulk",
"(",
"entities",
",",
"resource_type_parent",
")",
":",
"if",
"not",
"isinstance",
"(",
"entities",
",",
"list",
")",
":",
"entities",
"=",
"[",
"entities",
"]",
"bulk_array",
"=",
"[",
"]",
"for",
"e",
"in",
"entities",
":",
"bu... | Convert Single TC Entity to Bulk format.
.. Attention:: This method is subject to frequent changes
Args:
entities (dictionary): TC Entity to be converted to Bulk.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(dictionary): A dictionary representing TC Bulk format. | [
"Convert",
"Single",
"TC",
"Entity",
"to",
"Bulk",
"format",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L1057-L1086 | train | 27,557 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.indicator_arrays | def indicator_arrays(tc_entity_array):
"""Convert TCEntityArray to Indicator Type dictionary.
Args:
tc_entity_array (dictionary): The TCEntityArray to convert.
Returns:
(dictionary): Dictionary containing arrays of indicators for each indicator type.
"""
type_dict = {}
for ea in tc_entity_array:
type_dict.setdefault(ea['type'], []).append(ea['value'])
return type_dict | python | def indicator_arrays(tc_entity_array):
"""Convert TCEntityArray to Indicator Type dictionary.
Args:
tc_entity_array (dictionary): The TCEntityArray to convert.
Returns:
(dictionary): Dictionary containing arrays of indicators for each indicator type.
"""
type_dict = {}
for ea in tc_entity_array:
type_dict.setdefault(ea['type'], []).append(ea['value'])
return type_dict | [
"def",
"indicator_arrays",
"(",
"tc_entity_array",
")",
":",
"type_dict",
"=",
"{",
"}",
"for",
"ea",
"in",
"tc_entity_array",
":",
"type_dict",
".",
"setdefault",
"(",
"ea",
"[",
"'type'",
"]",
",",
"[",
"]",
")",
".",
"append",
"(",
"ea",
"[",
"'valu... | Convert TCEntityArray to Indicator Type dictionary.
Args:
tc_entity_array (dictionary): The TCEntityArray to convert.
Returns:
(dictionary): Dictionary containing arrays of indicators for each indicator type. | [
"Convert",
"TCEntityArray",
"to",
"Indicator",
"Type",
"dictionary",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L1089-L1101 | train | 27,558 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.json_to_bulk | def json_to_bulk(tc_data, value_fields, resource_type, resource_type_parent):
"""Convert ThreatConnect JSON response to a Bulk Format.
.. Attention:: This method is subject to frequent changes
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_fields (list): Field names that contain the "value" data.
resource_type (string): The resource type of the tc_data provided.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(list): A dictionary representing a TCEntityArray
"""
if not isinstance(tc_data, list):
tc_data = [tc_data]
bulk_array = []
for d in tc_data:
# value
values = []
for field in value_fields:
if d.get(field) is not None:
values.append(d.get(field))
del d[field]
if resource_type_parent in ['Group', 'Task', 'Victim']:
d['name'] = ' : '.join(values)
elif resource_type_parent in ['Indicator']:
d['summary'] = ' : '.join(values)
if 'owner' in d:
d['ownerName'] = d['owner']['name']
del d['owner']
# type
if d.get('type') is None:
d['type'] = resource_type
bulk_array.append(d)
return bulk_array | python | def json_to_bulk(tc_data, value_fields, resource_type, resource_type_parent):
"""Convert ThreatConnect JSON response to a Bulk Format.
.. Attention:: This method is subject to frequent changes
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_fields (list): Field names that contain the "value" data.
resource_type (string): The resource type of the tc_data provided.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(list): A dictionary representing a TCEntityArray
"""
if not isinstance(tc_data, list):
tc_data = [tc_data]
bulk_array = []
for d in tc_data:
# value
values = []
for field in value_fields:
if d.get(field) is not None:
values.append(d.get(field))
del d[field]
if resource_type_parent in ['Group', 'Task', 'Victim']:
d['name'] = ' : '.join(values)
elif resource_type_parent in ['Indicator']:
d['summary'] = ' : '.join(values)
if 'owner' in d:
d['ownerName'] = d['owner']['name']
del d['owner']
# type
if d.get('type') is None:
d['type'] = resource_type
bulk_array.append(d)
return bulk_array | [
"def",
"json_to_bulk",
"(",
"tc_data",
",",
"value_fields",
",",
"resource_type",
",",
"resource_type_parent",
")",
":",
"if",
"not",
"isinstance",
"(",
"tc_data",
",",
"list",
")",
":",
"tc_data",
"=",
"[",
"tc_data",
"]",
"bulk_array",
"=",
"[",
"]",
"fo... | Convert ThreatConnect JSON response to a Bulk Format.
.. Attention:: This method is subject to frequent changes
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_fields (list): Field names that contain the "value" data.
resource_type (string): The resource type of the tc_data provided.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(list): A dictionary representing a TCEntityArray | [
"Convert",
"ThreatConnect",
"JSON",
"response",
"to",
"a",
"Bulk",
"Format",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L1104-L1147 | train | 27,559 |
ThreatConnect-Inc/tcex | tcex/tcex_playbook.py | TcExPlaybook.json_to_entity | def json_to_entity(tc_data, value_fields, resource_type, resource_type_parent):
"""Convert ThreatConnect JSON response to a TCEntityArray.
.. Attention:: This method is subject to frequent changes.
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_fields (list): Field names that contain the "value" data.
resource_type (string): The resource type of the tc_data provided.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(list): A list representing a TCEntityArray.
"""
if not isinstance(tc_data, list):
tc_data = [tc_data]
entity_array = []
for d in tc_data:
entity = {'id': d.get('id'), 'webLink': d.get('webLink')}
# value
values = []
if 'summary' in d:
values.append(d.get('summary'))
else:
for field in value_fields:
if d.get(field) is not None:
values.append(d.get(field))
entity['value'] = ' : '.join(values)
# type
if d.get('type') is not None:
entity['type'] = d.get('type')
else:
entity['type'] = resource_type
if resource_type_parent in ['Indicator']:
entity['confidence'] = d.get('confidence')
entity['rating'] = d.get('rating')
entity['threatAssessConfidence'] = d.get('threatAssessConfidence')
entity['threatAssessRating'] = d.get('threatAssessRating')
entity['dateLastModified'] = d.get('lastModified')
if resource_type_parent in ['Indicator', 'Group']:
if 'owner' in d:
entity['ownerName'] = d['owner']['name']
else:
entity['ownerName'] = d.get('ownerName')
entity['dateAdded'] = d.get('dateAdded')
if resource_type_parent in ['Victim']:
entity['ownerName'] = d.get('org')
entity_array.append(entity)
return entity_array | python | def json_to_entity(tc_data, value_fields, resource_type, resource_type_parent):
"""Convert ThreatConnect JSON response to a TCEntityArray.
.. Attention:: This method is subject to frequent changes.
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_fields (list): Field names that contain the "value" data.
resource_type (string): The resource type of the tc_data provided.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(list): A list representing a TCEntityArray.
"""
if not isinstance(tc_data, list):
tc_data = [tc_data]
entity_array = []
for d in tc_data:
entity = {'id': d.get('id'), 'webLink': d.get('webLink')}
# value
values = []
if 'summary' in d:
values.append(d.get('summary'))
else:
for field in value_fields:
if d.get(field) is not None:
values.append(d.get(field))
entity['value'] = ' : '.join(values)
# type
if d.get('type') is not None:
entity['type'] = d.get('type')
else:
entity['type'] = resource_type
if resource_type_parent in ['Indicator']:
entity['confidence'] = d.get('confidence')
entity['rating'] = d.get('rating')
entity['threatAssessConfidence'] = d.get('threatAssessConfidence')
entity['threatAssessRating'] = d.get('threatAssessRating')
entity['dateLastModified'] = d.get('lastModified')
if resource_type_parent in ['Indicator', 'Group']:
if 'owner' in d:
entity['ownerName'] = d['owner']['name']
else:
entity['ownerName'] = d.get('ownerName')
entity['dateAdded'] = d.get('dateAdded')
if resource_type_parent in ['Victim']:
entity['ownerName'] = d.get('org')
entity_array.append(entity)
return entity_array | [
"def",
"json_to_entity",
"(",
"tc_data",
",",
"value_fields",
",",
"resource_type",
",",
"resource_type_parent",
")",
":",
"if",
"not",
"isinstance",
"(",
"tc_data",
",",
"list",
")",
":",
"tc_data",
"=",
"[",
"tc_data",
"]",
"entity_array",
"=",
"[",
"]",
... | Convert ThreatConnect JSON response to a TCEntityArray.
.. Attention:: This method is subject to frequent changes.
Args:
tc_data (dictionary): Array of data returned from TC API call.
value_fields (list): Field names that contain the "value" data.
resource_type (string): The resource type of the tc_data provided.
resource_type_parent (string): The resource parent type of the tc_data provided.
Returns:
(list): A list representing a TCEntityArray. | [
"Convert",
"ThreatConnect",
"JSON",
"response",
"to",
"a",
"TCEntityArray",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L1150-L1207 | train | 27,560 |
ThreatConnect-Inc/tcex | tcex/tcex_utils.py | TcExUtils.any_to_datetime | def any_to_datetime(self, time_input, tz=None):
"""Return datetime object from multiple formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object.
"""
# handle timestamp (e.g. 1510686617 or 1510686617.298753)
dt_value = self.unix_time_to_datetime(time_input, tz)
# handle ISO or other formatted date (e.g. 2017-11-08T16:52:42Z,
# 2017-11-08T16:52:42.400306+00:00)
if dt_value is None:
dt_value = self.date_to_datetime(time_input, tz)
# handle human readable relative time (e.g. 30 days ago, last friday)
if dt_value is None:
dt_value = self.human_date_to_datetime(time_input, tz)
# if all attempt to convert fail raise an error
if dt_value is None:
raise RuntimeError('Could not format input ({}) to datetime string.'.format(time_input))
return dt_value | python | def any_to_datetime(self, time_input, tz=None):
"""Return datetime object from multiple formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object.
"""
# handle timestamp (e.g. 1510686617 or 1510686617.298753)
dt_value = self.unix_time_to_datetime(time_input, tz)
# handle ISO or other formatted date (e.g. 2017-11-08T16:52:42Z,
# 2017-11-08T16:52:42.400306+00:00)
if dt_value is None:
dt_value = self.date_to_datetime(time_input, tz)
# handle human readable relative time (e.g. 30 days ago, last friday)
if dt_value is None:
dt_value = self.human_date_to_datetime(time_input, tz)
# if all attempt to convert fail raise an error
if dt_value is None:
raise RuntimeError('Could not format input ({}) to datetime string.'.format(time_input))
return dt_value | [
"def",
"any_to_datetime",
"(",
"self",
",",
"time_input",
",",
"tz",
"=",
"None",
")",
":",
"# handle timestamp (e.g. 1510686617 or 1510686617.298753)",
"dt_value",
"=",
"self",
".",
"unix_time_to_datetime",
"(",
"time_input",
",",
"tz",
")",
"# handle ISO or other form... | Return datetime object from multiple formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object. | [
"Return",
"datetime",
"object",
"from",
"multiple",
"formats",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L31-L64 | train | 27,561 |
ThreatConnect-Inc/tcex | tcex/tcex_utils.py | TcExUtils.date_to_datetime | def date_to_datetime(self, time_input, tz=None):
""" Convert ISO 8601 and other date strings to datetime.datetime type.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object.
"""
dt = None
try:
# dt = parser.parse(time_input, fuzzy_with_tokens=True)[0]
dt = parser.parse(time_input)
# don't convert timezone if dt timezone already in the correct timezone
if tz is not None and tz != dt.tzname():
if dt.tzinfo is None:
dt = self._replace_timezone(dt)
dt = dt.astimezone(timezone(tz))
except IndexError:
pass
except TypeError:
pass
except ValueError:
pass
return dt | python | def date_to_datetime(self, time_input, tz=None):
""" Convert ISO 8601 and other date strings to datetime.datetime type.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object.
"""
dt = None
try:
# dt = parser.parse(time_input, fuzzy_with_tokens=True)[0]
dt = parser.parse(time_input)
# don't convert timezone if dt timezone already in the correct timezone
if tz is not None and tz != dt.tzname():
if dt.tzinfo is None:
dt = self._replace_timezone(dt)
dt = dt.astimezone(timezone(tz))
except IndexError:
pass
except TypeError:
pass
except ValueError:
pass
return dt | [
"def",
"date_to_datetime",
"(",
"self",
",",
"time_input",
",",
"tz",
"=",
"None",
")",
":",
"dt",
"=",
"None",
"try",
":",
"# dt = parser.parse(time_input, fuzzy_with_tokens=True)[0]",
"dt",
"=",
"parser",
".",
"parse",
"(",
"time_input",
")",
"# don't convert ti... | Convert ISO 8601 and other date strings to datetime.datetime type.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime.datetime): Python datetime.datetime object. | [
"Convert",
"ISO",
"8601",
"and",
"other",
"date",
"strings",
"to",
"datetime",
".",
"datetime",
"type",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L80-L105 | train | 27,562 |
ThreatConnect-Inc/tcex | tcex/tcex_utils.py | TcExUtils.format_datetime | def format_datetime(self, time_input, tz=None, date_format=None):
""" Return timestamp from multiple input formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
.. note:: To get a unix timestamp format use the strftime format **%s**. Python
does not natively support **%s**, however this method has support.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
date_format (string): The strftime format to use, ISO by default.
Returns:
(string): Formatted datetime string.
"""
# handle timestamp (e.g. 1510686617 or 1510686617.298753)
dt_value = self.any_to_datetime(time_input, tz)
# format date
if date_format == '%s':
dt_value = calendar.timegm(dt_value.timetuple())
elif date_format:
dt_value = dt_value.strftime(date_format)
else:
dt_value = dt_value.isoformat()
return dt_value | python | def format_datetime(self, time_input, tz=None, date_format=None):
""" Return timestamp from multiple input formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
.. note:: To get a unix timestamp format use the strftime format **%s**. Python
does not natively support **%s**, however this method has support.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
date_format (string): The strftime format to use, ISO by default.
Returns:
(string): Formatted datetime string.
"""
# handle timestamp (e.g. 1510686617 or 1510686617.298753)
dt_value = self.any_to_datetime(time_input, tz)
# format date
if date_format == '%s':
dt_value = calendar.timegm(dt_value.timetuple())
elif date_format:
dt_value = dt_value.strftime(date_format)
else:
dt_value = dt_value.isoformat()
return dt_value | [
"def",
"format_datetime",
"(",
"self",
",",
"time_input",
",",
"tz",
"=",
"None",
",",
"date_format",
"=",
"None",
")",
":",
"# handle timestamp (e.g. 1510686617 or 1510686617.298753)",
"dt_value",
"=",
"self",
".",
"any_to_datetime",
"(",
"time_input",
",",
"tz",
... | Return timestamp from multiple input formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
.. note:: To get a unix timestamp format use the strftime format **%s**. Python
does not natively support **%s**, however this method has support.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
date_format (string): The strftime format to use, ISO by default.
Returns:
(string): Formatted datetime string. | [
"Return",
"timestamp",
"from",
"multiple",
"input",
"formats",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L107-L140 | train | 27,563 |
ThreatConnect-Inc/tcex | tcex/tcex_utils.py | TcExUtils.inflect | def inflect(self):
"""Return instance of inflect."""
if self._inflect is None:
import inflect
self._inflect = inflect.engine()
return self._inflect | python | def inflect(self):
"""Return instance of inflect."""
if self._inflect is None:
import inflect
self._inflect = inflect.engine()
return self._inflect | [
"def",
"inflect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_inflect",
"is",
"None",
":",
"import",
"inflect",
"self",
".",
"_inflect",
"=",
"inflect",
".",
"engine",
"(",
")",
"return",
"self",
".",
"_inflect"
] | Return instance of inflect. | [
"Return",
"instance",
"of",
"inflect",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L200-L206 | train | 27,564 |
ThreatConnect-Inc/tcex | tcex/tcex_utils.py | TcExUtils.write_temp_file | def write_temp_file(self, content, filename=None, mode='w'):
"""Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the file.
mode (str, optional): The file write mode which could be either 'w' or 'wb'.
Returns:
str: Fully qualified path name for the file.
"""
if filename is None:
filename = str(uuid.uuid4())
fqpn = os.path.join(self.tcex.default_args.tc_temp_path, filename)
with open(fqpn, mode) as fh:
fh.write(content)
return fqpn | python | def write_temp_file(self, content, filename=None, mode='w'):
"""Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the file.
mode (str, optional): The file write mode which could be either 'w' or 'wb'.
Returns:
str: Fully qualified path name for the file.
"""
if filename is None:
filename = str(uuid.uuid4())
fqpn = os.path.join(self.tcex.default_args.tc_temp_path, filename)
with open(fqpn, mode) as fh:
fh.write(content)
return fqpn | [
"def",
"write_temp_file",
"(",
"self",
",",
"content",
",",
"filename",
"=",
"None",
",",
"mode",
"=",
"'w'",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"fqpn",
"=",
"os",
".",
... | Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the file.
mode (str, optional): The file write mode which could be either 'w' or 'wb'.
Returns:
str: Fully qualified path name for the file. | [
"Write",
"content",
"to",
"a",
"temporary",
"file",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L221-L238 | train | 27,565 |
ThreatConnect-Inc/tcex | tcex/tcex_utils.py | TcExUtils.timedelta | def timedelta(self, time_input1, time_input2):
""" Calculates time delta between two time expressions.
Args:
time_input1 (string): The time input string (see formats above).
time_input2 (string): The time input string (see formats above).
Returns:
(dict): Dict with delta values.
"""
time_input1 = self.any_to_datetime(time_input1)
time_input2 = self.any_to_datetime(time_input2)
diff = time_input1 - time_input2 # timedelta
delta = relativedelta(time_input1, time_input2) # relativedelta
# totals
total_months = (delta.years * 12) + delta.months
total_weeks = (delta.years * 52) + (total_months * 4) + delta.weeks
total_days = diff.days # handles leap days
total_hours = (total_days * 24) + delta.hours
total_minutes = (total_hours * 60) + delta.minutes
total_seconds = (total_minutes * 60) + delta.seconds
total_microseconds = (total_seconds * 1000) + delta.microseconds
return {
'datetime_1': time_input1.isoformat(),
'datetime_2': time_input2.isoformat(),
'years': delta.years,
'months': delta.months,
'weeks': delta.weeks,
'days': delta.days,
'hours': delta.hours,
'minutes': delta.minutes,
'seconds': delta.seconds,
'microseconds': delta.microseconds,
'total_months': total_months,
'total_weeks': total_weeks,
'total_days': total_days,
'total_hours': total_hours,
'total_minutes': total_minutes,
'total_seconds': total_seconds,
'total_microseconds': total_microseconds,
} | python | def timedelta(self, time_input1, time_input2):
""" Calculates time delta between two time expressions.
Args:
time_input1 (string): The time input string (see formats above).
time_input2 (string): The time input string (see formats above).
Returns:
(dict): Dict with delta values.
"""
time_input1 = self.any_to_datetime(time_input1)
time_input2 = self.any_to_datetime(time_input2)
diff = time_input1 - time_input2 # timedelta
delta = relativedelta(time_input1, time_input2) # relativedelta
# totals
total_months = (delta.years * 12) + delta.months
total_weeks = (delta.years * 52) + (total_months * 4) + delta.weeks
total_days = diff.days # handles leap days
total_hours = (total_days * 24) + delta.hours
total_minutes = (total_hours * 60) + delta.minutes
total_seconds = (total_minutes * 60) + delta.seconds
total_microseconds = (total_seconds * 1000) + delta.microseconds
return {
'datetime_1': time_input1.isoformat(),
'datetime_2': time_input2.isoformat(),
'years': delta.years,
'months': delta.months,
'weeks': delta.weeks,
'days': delta.days,
'hours': delta.hours,
'minutes': delta.minutes,
'seconds': delta.seconds,
'microseconds': delta.microseconds,
'total_months': total_months,
'total_weeks': total_weeks,
'total_days': total_days,
'total_hours': total_hours,
'total_minutes': total_minutes,
'total_seconds': total_seconds,
'total_microseconds': total_microseconds,
} | [
"def",
"timedelta",
"(",
"self",
",",
"time_input1",
",",
"time_input2",
")",
":",
"time_input1",
"=",
"self",
".",
"any_to_datetime",
"(",
"time_input1",
")",
"time_input2",
"=",
"self",
".",
"any_to_datetime",
"(",
"time_input2",
")",
"diff",
"=",
"time_inpu... | Calculates time delta between two time expressions.
Args:
time_input1 (string): The time input string (see formats above).
time_input2 (string): The time input string (see formats above).
Returns:
(dict): Dict with delta values. | [
"Calculates",
"time",
"delta",
"between",
"two",
"time",
"expressions",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L240-L282 | train | 27,566 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/group/group_types/incident.py | Incident.event_date | def event_date(self, event_date):
"""
Updates the event_date.
Args:
event_date: Converted to %Y-%m-%dT%H:%M:%SZ date format.
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
event_date = self._utils.format_datetime(event_date, date_format='%Y-%m-%dT%H:%M:%SZ')
self._data['eventDate'] = event_date
request = {'eventDate': event_date}
return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request) | python | def event_date(self, event_date):
"""
Updates the event_date.
Args:
event_date: Converted to %Y-%m-%dT%H:%M:%SZ date format.
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
event_date = self._utils.format_datetime(event_date, date_format='%Y-%m-%dT%H:%M:%SZ')
self._data['eventDate'] = event_date
request = {'eventDate': event_date}
return self.tc_requests.update(self.api_type, self.api_sub_type, self.unique_id, request) | [
"def",
"event_date",
"(",
"self",
",",
"event_date",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"event_date",
"=",
"self",
".",
"_... | Updates the event_date.
Args:
event_date: Converted to %Y-%m-%dT%H:%M:%SZ date format.
Returns: | [
"Updates",
"the",
"event_date",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/group/group_types/incident.py#L61-L77 | train | 27,567 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/victim.py | Victim.add_asset | def add_asset(self, asset, asset_name, asset_type):
"""
Adds a asset to the Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset == 'PHONE':
return self.tc_requests.add_victim_phone_asset(self.unique_id, asset_name)
if asset == 'EMAIL':
return self.tc_requests.add_victim_email_asset(self.unique_id, asset_name, asset_type)
if asset == 'NETWORK':
return self.tc_requests.add_victim_network_asset(self.unique_id, asset_name, asset_type)
if asset == 'SOCIAL':
return self.tc_requests.add_victim_social_asset(self.unique_id, asset_name, asset_type)
if asset == 'WEB':
return self.tc_requests.add_victim_web_asset(self.unique_id, asset_name)
self._tcex.handle_error(
925, ['asset_type', 'add_asset', 'asset_type', 'asset_type', asset_type]
)
return None | python | def add_asset(self, asset, asset_name, asset_type):
"""
Adds a asset to the Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset == 'PHONE':
return self.tc_requests.add_victim_phone_asset(self.unique_id, asset_name)
if asset == 'EMAIL':
return self.tc_requests.add_victim_email_asset(self.unique_id, asset_name, asset_type)
if asset == 'NETWORK':
return self.tc_requests.add_victim_network_asset(self.unique_id, asset_name, asset_type)
if asset == 'SOCIAL':
return self.tc_requests.add_victim_social_asset(self.unique_id, asset_name, asset_type)
if asset == 'WEB':
return self.tc_requests.add_victim_web_asset(self.unique_id, asset_name)
self._tcex.handle_error(
925, ['asset_type', 'add_asset', 'asset_type', 'asset_type', asset_type]
)
return None | [
"def",
"add_asset",
"(",
"self",
",",
"asset",
",",
"asset_name",
",",
"asset_type",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"i... | Adds a asset to the Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns: | [
"Adds",
"a",
"asset",
"to",
"the",
"Victim"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/victim.py#L63-L98 | train | 27,568 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/victim.py | Victim.update_asset | def update_asset(self, asset, asset_id, asset_name, asset_type):
"""
Update a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_id:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset == 'PHONE':
return self.tc_requests.update_victim_phone_asset(self.unique_id, asset_id, asset_name)
if asset == 'EMAIL':
return self.tc_requests.update_victim_email_asset(
self.unique_id, asset_id, asset_name, asset_type
)
if asset == 'NETWORK':
return self.tc_requests.update_victim_network_asset(
self.unique_id, asset_id, asset_name, asset_type
)
if asset == 'SOCIAL':
return self.tc_requests.update_victim_social_asset(
self.unique_id, asset_id, asset_name, asset_type
)
if asset == 'WEB':
return self.tc_requests.update_victim_web_asset(self.unique_id, asset_id, asset_name)
self._tcex.handle_error(
925, ['asset_type', 'update_asset', 'asset_type', 'asset_type', asset_type]
)
return None | python | def update_asset(self, asset, asset_id, asset_name, asset_type):
"""
Update a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_id:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset == 'PHONE':
return self.tc_requests.update_victim_phone_asset(self.unique_id, asset_id, asset_name)
if asset == 'EMAIL':
return self.tc_requests.update_victim_email_asset(
self.unique_id, asset_id, asset_name, asset_type
)
if asset == 'NETWORK':
return self.tc_requests.update_victim_network_asset(
self.unique_id, asset_id, asset_name, asset_type
)
if asset == 'SOCIAL':
return self.tc_requests.update_victim_social_asset(
self.unique_id, asset_id, asset_name, asset_type
)
if asset == 'WEB':
return self.tc_requests.update_victim_web_asset(self.unique_id, asset_id, asset_name)
self._tcex.handle_error(
925, ['asset_type', 'update_asset', 'asset_type', 'asset_type', asset_type]
)
return None | [
"def",
"update_asset",
"(",
"self",
",",
"asset",
",",
"asset_id",
",",
"asset_name",
",",
"asset_type",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"t... | Update a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset:
asset_name:
asset_id:
asset_type: PHONE, EMAIL, NETWORK, SOCIAL, or WEB
Returns: | [
"Update",
"a",
"asset",
"of",
"a",
"Victim"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/victim.py#L100-L143 | train | 27,569 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/victim.py | Victim.asset | def asset(self, asset_id, asset_type, action='GET'):
"""
Gets a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset_type:
asset_id:
action:
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset_type == 'PHONE':
return self.tc_requests.victim_phone_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'EMAIL':
return self.tc_requests.victim_email_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'NETWORK':
return self.tc_requests.victim_network_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'SOCIAL':
return self.tc_requests.victim_social_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'WEB':
return self.tc_requests.victim_web_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
self._tcex.handle_error(
925, ['asset_type', 'asset', 'asset_type', 'asset_type', asset_type]
)
return None | python | def asset(self, asset_id, asset_type, action='GET'):
"""
Gets a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset_type:
asset_id:
action:
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if asset_type == 'PHONE':
return self.tc_requests.victim_phone_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'EMAIL':
return self.tc_requests.victim_email_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'NETWORK':
return self.tc_requests.victim_network_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'SOCIAL':
return self.tc_requests.victim_social_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
if asset_type == 'WEB':
return self.tc_requests.victim_web_asset(
self.api_type, self.api_sub_type, self.unique_id, asset_id, action=action
)
self._tcex.handle_error(
925, ['asset_type', 'asset', 'asset_type', 'asset_type', asset_type]
)
return None | [
"def",
"asset",
"(",
"self",
",",
"asset_id",
",",
"asset_type",
",",
"action",
"=",
"'GET'",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]"... | Gets a asset of a Victim
Valid asset_type:
+ PHONE
+ EMAIL
+ NETWORK
+ SOCIAL
+ WEB
Args:
asset_type:
asset_id:
action:
Returns: | [
"Gets",
"a",
"asset",
"of",
"a",
"Victim"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/victim.py#L145-L190 | train | 27,570 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/mappings/victim.py | Victim.assets | def assets(self, asset_type=None):
"""
Gets the assets of a Victim
Args:
asset_type:
Yields: asset json
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if not asset_type:
for a in self.tc_requests.victim_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'PHONE':
for a in self.tc_requests.victim_phone_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'EMAIL':
for a in self.tc_requests.victim_email_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'NETWORK':
for a in self.tc_requests.victim_network_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'SOCIAL':
for a in self.tc_requests.victim_social_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'WEB':
for a in self.tc_requests.victim_web_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
self._tcex.handle_error(
925, ['asset_type', 'assets', 'asset_type', 'asset_type', asset_type]
) | python | def assets(self, asset_type=None):
"""
Gets the assets of a Victim
Args:
asset_type:
Yields: asset json
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
if not asset_type:
for a in self.tc_requests.victim_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'PHONE':
for a in self.tc_requests.victim_phone_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'EMAIL':
for a in self.tc_requests.victim_email_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'NETWORK':
for a in self.tc_requests.victim_network_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'SOCIAL':
for a in self.tc_requests.victim_social_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
if asset_type == 'WEB':
for a in self.tc_requests.victim_web_assets(
self.api_type, self.api_sub_type, self.unique_id
):
yield a
self._tcex.handle_error(
925, ['asset_type', 'assets', 'asset_type', 'asset_type', asset_type]
) | [
"def",
"assets",
"(",
"self",
",",
"asset_type",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"can_update",
"(",
")",
":",
"self",
".",
"_tcex",
".",
"handle_error",
"(",
"910",
",",
"[",
"self",
".",
"type",
"]",
")",
"if",
"not",
"asset_type"... | Gets the assets of a Victim
Args:
asset_type:
Yields: asset json | [
"Gets",
"the",
"assets",
"of",
"a",
"Victim"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/mappings/victim.py#L192-L238 | train | 27,571 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.db_conn | def db_conn(self):
"""Create a temporary in memory DB and return the connection."""
if self._db_conn is None:
try:
self._db_conn = sqlite3.connect(':memory:')
except sqlite3.Error as e:
self.handle_error(e)
return self._db_conn | python | def db_conn(self):
"""Create a temporary in memory DB and return the connection."""
if self._db_conn is None:
try:
self._db_conn = sqlite3.connect(':memory:')
except sqlite3.Error as e:
self.handle_error(e)
return self._db_conn | [
"def",
"db_conn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_conn",
"is",
"None",
":",
"try",
":",
"self",
".",
"_db_conn",
"=",
"sqlite3",
".",
"connect",
"(",
"':memory:'",
")",
"except",
"sqlite3",
".",
"Error",
"as",
"e",
":",
"self",
".",
... | Create a temporary in memory DB and return the connection. | [
"Create",
"a",
"temporary",
"in",
"memory",
"DB",
"and",
"return",
"the",
"connection",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L53-L60 | train | 27,572 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.db_create_table | def db_create_table(self, table_name, columns):
"""Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB.
"""
formatted_columns = ''
for col in set(columns):
formatted_columns += '"{}" text, '.format(col.strip('"').strip('\''))
formatted_columns = formatted_columns.strip(', ')
create_table_sql = 'CREATE TABLE IF NOT EXISTS {} ({});'.format(
table_name, formatted_columns
)
try:
cr = self.db_conn.cursor()
cr.execute(create_table_sql)
except sqlite3.Error as e:
self.handle_error(e) | python | def db_create_table(self, table_name, columns):
"""Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB.
"""
formatted_columns = ''
for col in set(columns):
formatted_columns += '"{}" text, '.format(col.strip('"').strip('\''))
formatted_columns = formatted_columns.strip(', ')
create_table_sql = 'CREATE TABLE IF NOT EXISTS {} ({});'.format(
table_name, formatted_columns
)
try:
cr = self.db_conn.cursor()
cr.execute(create_table_sql)
except sqlite3.Error as e:
self.handle_error(e) | [
"def",
"db_create_table",
"(",
"self",
",",
"table_name",
",",
"columns",
")",
":",
"formatted_columns",
"=",
"''",
"for",
"col",
"in",
"set",
"(",
"columns",
")",
":",
"formatted_columns",
"+=",
"'\"{}\" text, '",
".",
"format",
"(",
"col",
".",
"strip",
... | Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB. | [
"Create",
"a",
"temporary",
"DB",
"table",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L62-L81 | train | 27,573 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.handle_error | def handle_error(err, halt=True):
"""Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit.
"""
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
if halt:
sys.exit(1) | python | def handle_error(err, halt=True):
"""Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit.
"""
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
if halt:
sys.exit(1) | [
"def",
"handle_error",
"(",
"err",
",",
"halt",
"=",
"True",
")",
":",
"print",
"(",
"'{}{}{}'",
".",
"format",
"(",
"c",
".",
"Style",
".",
"BRIGHT",
",",
"c",
".",
"Fore",
".",
"RED",
",",
"err",
")",
")",
"if",
"halt",
":",
"sys",
".",
"exit... | Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit. | [
"Print",
"errors",
"message",
"and",
"optionally",
"exit",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L109-L118 | train | 27,574 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.install_json | def install_json(self):
"""Return install.json contents."""
file_fqpn = os.path.join(self.app_path, 'install.json')
if self._install_json is None:
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
self._install_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return self._install_json | python | def install_json(self):
"""Return install.json contents."""
file_fqpn = os.path.join(self.app_path, 'install.json')
if self._install_json is None:
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
self._install_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return self._install_json | [
"def",
"install_json",
"(",
"self",
")",
":",
"file_fqpn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"app_path",
",",
"'install.json'",
")",
"if",
"self",
".",
"_install_json",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"... | Return install.json contents. | [
"Return",
"install",
".",
"json",
"contents",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L121-L133 | train | 27,575 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.install_json_params | def install_json_params(self, ij=None):
"""Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key.
"""
if self._install_json_params is None or ij is not None:
self._install_json_params = {}
# TODO: support for projects with multiple install.json files is not supported
if ij is None:
ij = self.install_json
for p in ij.get('params') or []:
self._install_json_params.setdefault(p.get('name'), p)
return self._install_json_params | python | def install_json_params(self, ij=None):
"""Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key.
"""
if self._install_json_params is None or ij is not None:
self._install_json_params = {}
# TODO: support for projects with multiple install.json files is not supported
if ij is None:
ij = self.install_json
for p in ij.get('params') or []:
self._install_json_params.setdefault(p.get('name'), p)
return self._install_json_params | [
"def",
"install_json_params",
"(",
"self",
",",
"ij",
"=",
"None",
")",
":",
"if",
"self",
".",
"_install_json_params",
"is",
"None",
"or",
"ij",
"is",
"not",
"None",
":",
"self",
".",
"_install_json_params",
"=",
"{",
"}",
"# TODO: support for projects with m... | Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key. | [
"Return",
"install",
".",
"json",
"params",
"in",
"a",
"dict",
"with",
"name",
"param",
"as",
"key",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L135-L151 | train | 27,576 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.install_json_output_variables | def install_json_output_variables(self, ij=None):
"""Return install.json output variables in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json output variables with name as key.
"""
if self._install_json_output_variables is None or ij is not None:
self._install_json_output_variables = {}
# TODO: currently there is no support for projects with multiple install.json files.
if ij is None:
ij = self.install_json
for p in ij.get('playbook', {}).get('outputVariables') or []:
self._install_json_output_variables.setdefault(p.get('name'), []).append(p)
return self._install_json_output_variables | python | def install_json_output_variables(self, ij=None):
"""Return install.json output variables in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json output variables with name as key.
"""
if self._install_json_output_variables is None or ij is not None:
self._install_json_output_variables = {}
# TODO: currently there is no support for projects with multiple install.json files.
if ij is None:
ij = self.install_json
for p in ij.get('playbook', {}).get('outputVariables') or []:
self._install_json_output_variables.setdefault(p.get('name'), []).append(p)
return self._install_json_output_variables | [
"def",
"install_json_output_variables",
"(",
"self",
",",
"ij",
"=",
"None",
")",
":",
"if",
"self",
".",
"_install_json_output_variables",
"is",
"None",
"or",
"ij",
"is",
"not",
"None",
":",
"self",
".",
"_install_json_output_variables",
"=",
"{",
"}",
"# TOD... | Return install.json output variables in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json output variables with name as key. | [
"Return",
"install",
".",
"json",
"output",
"variables",
"in",
"a",
"dict",
"with",
"name",
"param",
"as",
"key",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L153-L169 | train | 27,577 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.layout_json | def layout_json(self):
"""Return layout.json contents."""
file_fqpn = os.path.join(self.app_path, 'layout.json')
if self._layout_json is None:
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
self._layout_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return self._layout_json | python | def layout_json(self):
"""Return layout.json contents."""
file_fqpn = os.path.join(self.app_path, 'layout.json')
if self._layout_json is None:
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
self._layout_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return self._layout_json | [
"def",
"layout_json",
"(",
"self",
")",
":",
"file_fqpn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"app_path",
",",
"'layout.json'",
")",
"if",
"self",
".",
"_layout_json",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",... | Return layout.json contents. | [
"Return",
"layout",
".",
"json",
"contents",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L172-L184 | train | 27,578 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.layout_json_params | def layout_json_params(self):
"""Return layout.json params in a flattened dict with name param as key."""
if self._layout_json_params is None:
self._layout_json_params = {}
for i in self.layout_json.get('inputs', []):
for p in i.get('parameters', []):
self._layout_json_params.setdefault(p.get('name'), p)
return self._layout_json_params | python | def layout_json_params(self):
"""Return layout.json params in a flattened dict with name param as key."""
if self._layout_json_params is None:
self._layout_json_params = {}
for i in self.layout_json.get('inputs', []):
for p in i.get('parameters', []):
self._layout_json_params.setdefault(p.get('name'), p)
return self._layout_json_params | [
"def",
"layout_json_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"_layout_json_params",
"is",
"None",
":",
"self",
".",
"_layout_json_params",
"=",
"{",
"}",
"for",
"i",
"in",
"self",
".",
"layout_json",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
... | Return layout.json params in a flattened dict with name param as key. | [
"Return",
"layout",
".",
"json",
"params",
"in",
"a",
"flattened",
"dict",
"with",
"name",
"param",
"as",
"key",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L187-L194 | train | 27,579 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.layout_json_names | def layout_json_names(self):
"""Return layout.json names."""
if self._layout_json_names is None:
self._layout_json_names = self.layout_json_params.keys()
return self._layout_json_names | python | def layout_json_names(self):
"""Return layout.json names."""
if self._layout_json_names is None:
self._layout_json_names = self.layout_json_params.keys()
return self._layout_json_names | [
"def",
"layout_json_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"_layout_json_names",
"is",
"None",
":",
"self",
".",
"_layout_json_names",
"=",
"self",
".",
"layout_json_params",
".",
"keys",
"(",
")",
"return",
"self",
".",
"_layout_json_names"
] | Return layout.json names. | [
"Return",
"layout",
".",
"json",
"names",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L197-L201 | train | 27,580 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.layout_json_outputs | def layout_json_outputs(self):
"""Return layout.json outputs in a flattened dict with name param as key."""
if self._layout_json_outputs is None:
self._layout_json_outputs = {}
for o in self.layout_json.get('outputs', []):
self._layout_json_outputs.setdefault(o.get('name'), o)
return self._layout_json_outputs | python | def layout_json_outputs(self):
"""Return layout.json outputs in a flattened dict with name param as key."""
if self._layout_json_outputs is None:
self._layout_json_outputs = {}
for o in self.layout_json.get('outputs', []):
self._layout_json_outputs.setdefault(o.get('name'), o)
return self._layout_json_outputs | [
"def",
"layout_json_outputs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_layout_json_outputs",
"is",
"None",
":",
"self",
".",
"_layout_json_outputs",
"=",
"{",
"}",
"for",
"o",
"in",
"self",
".",
"layout_json",
".",
"get",
"(",
"'outputs'",
",",
"[",
"... | Return layout.json outputs in a flattened dict with name param as key. | [
"Return",
"layout",
".",
"json",
"outputs",
"in",
"a",
"flattened",
"dict",
"with",
"name",
"param",
"as",
"key",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L204-L210 | train | 27,581 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.load_install_json | def load_install_json(self, filename=None):
"""Return install.json data.
Args:
filename (str, optional): Defaults to None. The install.json filename (for bundled
Apps).
Returns:
dict: The contents of the install.json file.
"""
if filename is None:
filename = 'install.json'
file_fqpn = os.path.join(self.app_path, filename)
install_json = None
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
install_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return install_json | python | def load_install_json(self, filename=None):
"""Return install.json data.
Args:
filename (str, optional): Defaults to None. The install.json filename (for bundled
Apps).
Returns:
dict: The contents of the install.json file.
"""
if filename is None:
filename = 'install.json'
file_fqpn = os.path.join(self.app_path, filename)
install_json = None
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
install_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return install_json | [
"def",
"load_install_json",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'install.json'",
"file_fqpn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"app_path",
",",
"filename",
")",... | Return install.json data.
Args:
filename (str, optional): Defaults to None. The install.json filename (for bundled
Apps).
Returns:
dict: The contents of the install.json file. | [
"Return",
"install",
".",
"json",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L212-L235 | train | 27,582 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.redis | def redis(self):
"""Return instance of Redis."""
if self._redis is None:
self._redis = redis.StrictRedis(host=self.args.redis_host, port=self.args.redis_port)
return self._redis | python | def redis(self):
"""Return instance of Redis."""
if self._redis is None:
self._redis = redis.StrictRedis(host=self.args.redis_host, port=self.args.redis_port)
return self._redis | [
"def",
"redis",
"(",
"self",
")",
":",
"if",
"self",
".",
"_redis",
"is",
"None",
":",
"self",
".",
"_redis",
"=",
"redis",
".",
"StrictRedis",
"(",
"host",
"=",
"self",
".",
"args",
".",
"redis_host",
",",
"port",
"=",
"self",
".",
"args",
".",
... | Return instance of Redis. | [
"Return",
"instance",
"of",
"Redis",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L238-L242 | train | 27,583 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.tcex_json | def tcex_json(self):
"""Return tcex.json file contents."""
file_fqpn = os.path.join(self.app_path, 'tcex.json')
if self._tcex_json is None:
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
self._tcex_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return self._tcex_json | python | def tcex_json(self):
"""Return tcex.json file contents."""
file_fqpn = os.path.join(self.app_path, 'tcex.json')
if self._tcex_json is None:
if os.path.isfile(file_fqpn):
try:
with open(file_fqpn, 'r') as fh:
self._tcex_json = json.load(fh)
except ValueError as e:
self.handle_error('Failed to load "{}" file ({}).'.format(file_fqpn, e))
else:
self.handle_error('File "{}" could not be found.'.format(file_fqpn))
return self._tcex_json | [
"def",
"tcex_json",
"(",
"self",
")",
":",
"file_fqpn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"app_path",
",",
"'tcex.json'",
")",
"if",
"self",
".",
"_tcex_json",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"fi... | Return tcex.json file contents. | [
"Return",
"tcex",
".",
"json",
"file",
"contents",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L245-L257 | train | 27,584 |
ThreatConnect-Inc/tcex | tcex/tcex_bin.py | TcExBin.update_system_path | def update_system_path():
"""Update the system path to ensure project modules and dependencies can be found."""
cwd = os.getcwd()
lib_dir = os.path.join(os.getcwd(), 'lib_')
lib_latest = os.path.join(os.getcwd(), 'lib_latest')
# insert the lib_latest directory into the system Path if no other lib directory found. This
# entry will be bumped to index 1 after adding the current working directory.
if not [p for p in sys.path if lib_dir in p]:
sys.path.insert(0, lib_latest)
# insert the current working directory into the system Path for the App, ensuring that it is
# always the first entry in the list.
try:
sys.path.remove(cwd)
except ValueError:
pass
sys.path.insert(0, cwd) | python | def update_system_path():
"""Update the system path to ensure project modules and dependencies can be found."""
cwd = os.getcwd()
lib_dir = os.path.join(os.getcwd(), 'lib_')
lib_latest = os.path.join(os.getcwd(), 'lib_latest')
# insert the lib_latest directory into the system Path if no other lib directory found. This
# entry will be bumped to index 1 after adding the current working directory.
if not [p for p in sys.path if lib_dir in p]:
sys.path.insert(0, lib_latest)
# insert the current working directory into the system Path for the App, ensuring that it is
# always the first entry in the list.
try:
sys.path.remove(cwd)
except ValueError:
pass
sys.path.insert(0, cwd) | [
"def",
"update_system_path",
"(",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"lib_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'lib_'",
")",
"lib_latest",
"=",
"os",
".",
"path",
".",
"join",
"(",... | Update the system path to ensure project modules and dependencies can be found. | [
"Update",
"the",
"system",
"path",
"to",
"ensure",
"project",
"modules",
"and",
"dependencies",
"can",
"be",
"found",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin.py#L260-L277 | train | 27,585 |
ThreatConnect-Inc/tcex | tcex/tcex_session.py | TcExSession._hmac_auth | def _hmac_auth(self):
"""Add ThreatConnect HMAC Auth to Session."""
return TcExHmacAuth(self.args.api_access_id, self.args.api_secret_key, self.tcex.log) | python | def _hmac_auth(self):
"""Add ThreatConnect HMAC Auth to Session."""
return TcExHmacAuth(self.args.api_access_id, self.args.api_secret_key, self.tcex.log) | [
"def",
"_hmac_auth",
"(",
"self",
")",
":",
"return",
"TcExHmacAuth",
"(",
"self",
".",
"args",
".",
"api_access_id",
",",
"self",
".",
"args",
".",
"api_secret_key",
",",
"self",
".",
"tcex",
".",
"log",
")"
] | Add ThreatConnect HMAC Auth to Session. | [
"Add",
"ThreatConnect",
"HMAC",
"Auth",
"to",
"Session",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_session.py#L56-L58 | train | 27,586 |
ThreatConnect-Inc/tcex | tcex/tcex_session.py | TcExSession._token_auth | def _token_auth(self):
"""Add ThreatConnect Token Auth to Session."""
return TcExTokenAuth(
self,
self.args.tc_token,
self.args.tc_token_expires,
self.args.tc_api_path,
self.tcex.log,
) | python | def _token_auth(self):
"""Add ThreatConnect Token Auth to Session."""
return TcExTokenAuth(
self,
self.args.tc_token,
self.args.tc_token_expires,
self.args.tc_api_path,
self.tcex.log,
) | [
"def",
"_token_auth",
"(",
"self",
")",
":",
"return",
"TcExTokenAuth",
"(",
"self",
",",
"self",
".",
"args",
".",
"tc_token",
",",
"self",
".",
"args",
".",
"tc_token_expires",
",",
"self",
".",
"args",
".",
"tc_api_path",
",",
"self",
".",
"tcex",
"... | Add ThreatConnect Token Auth to Session. | [
"Add",
"ThreatConnect",
"Token",
"Auth",
"to",
"Session",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_session.py#L60-L68 | train | 27,587 |
ThreatConnect-Inc/tcex | tcex/tcex_session.py | TcExSession.request | def request(self, method, url, **kwargs):
"""Override request method disabling verify on token renewal if disabled on session."""
if not url.startswith('https'):
url = '{}{}'.format(self.args.tc_api_path, url)
return super(TcExSession, self).request(method, url, **kwargs) | python | def request(self, method, url, **kwargs):
"""Override request method disabling verify on token renewal if disabled on session."""
if not url.startswith('https'):
url = '{}{}'.format(self.args.tc_api_path, url)
return super(TcExSession, self).request(method, url, **kwargs) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'https'",
")",
":",
"url",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"args",
".",
"tc_api_path",
",",
... | Override request method disabling verify on token renewal if disabled on session. | [
"Override",
"request",
"method",
"disabling",
"verify",
"on",
"token",
"renewal",
"if",
"disabled",
"on",
"session",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_session.py#L70-L74 | train | 27,588 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | Indicator.add_key_value | def add_key_value(self, key, value):
"""Add custom field to Indicator object.
.. note:: The key must be the exact name required by the batch schema.
Example::
file_hash = tcex.batch.file('File', '1d878cdc391461e392678ba3fc9f6f32')
file_hash.add_key_value('size', '1024')
Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data.
"""
key = self._metadata_map.get(key, key)
if key in ['dateAdded', 'lastModified']:
self._indicator_data[key] = self._utils.format_datetime(
value, date_format='%Y-%m-%dT%H:%M:%SZ'
)
elif key == 'confidence':
self._indicator_data[key] = int(value)
elif key == 'rating':
self._indicator_data[key] = float(value)
else:
self._indicator_data[key] = value | python | def add_key_value(self, key, value):
"""Add custom field to Indicator object.
.. note:: The key must be the exact name required by the batch schema.
Example::
file_hash = tcex.batch.file('File', '1d878cdc391461e392678ba3fc9f6f32')
file_hash.add_key_value('size', '1024')
Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data.
"""
key = self._metadata_map.get(key, key)
if key in ['dateAdded', 'lastModified']:
self._indicator_data[key] = self._utils.format_datetime(
value, date_format='%Y-%m-%dT%H:%M:%SZ'
)
elif key == 'confidence':
self._indicator_data[key] = int(value)
elif key == 'rating':
self._indicator_data[key] = float(value)
else:
self._indicator_data[key] = value | [
"def",
"add_key_value",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"_metadata_map",
".",
"get",
"(",
"key",
",",
"key",
")",
"if",
"key",
"in",
"[",
"'dateAdded'",
",",
"'lastModified'",
"]",
":",
"self",
".",
"_indicat... | Add custom field to Indicator object.
.. note:: The key must be the exact name required by the batch schema.
Example::
file_hash = tcex.batch.file('File', '1d878cdc391461e392678ba3fc9f6f32')
file_hash.add_key_value('size', '1024')
Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data. | [
"Add",
"custom",
"field",
"to",
"Indicator",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L105-L129 | train | 27,589 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | Indicator.association | def association(self, group_xid):
"""Add association using xid value.
Args:
group_xid (str): The external id of the Group to associate.
"""
association = {'groupXid': group_xid}
self._indicator_data.setdefault('associatedGroups', []).append(association) | python | def association(self, group_xid):
"""Add association using xid value.
Args:
group_xid (str): The external id of the Group to associate.
"""
association = {'groupXid': group_xid}
self._indicator_data.setdefault('associatedGroups', []).append(association) | [
"def",
"association",
"(",
"self",
",",
"group_xid",
")",
":",
"association",
"=",
"{",
"'groupXid'",
":",
"group_xid",
"}",
"self",
".",
"_indicator_data",
".",
"setdefault",
"(",
"'associatedGroups'",
",",
"[",
"]",
")",
".",
"append",
"(",
"association",
... | Add association using xid value.
Args:
group_xid (str): The external id of the Group to associate. | [
"Add",
"association",
"using",
"xid",
"value",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L141-L148 | train | 27,590 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | Indicator.attribute | def attribute(
self, attr_type, attr_value, displayed=False, source=None, unique=True, formatter=None
):
"""Return instance of Attribute
unique:
* False - Attribute type:value can be duplicated.
* Type - Attribute type has to be unique (e.g., only 1 Description Attribute).
* True - Attribute type:value combo must be unique.
Args:
attr_type (str): The ThreatConnect defined attribute type.
attr_value (str): The value for this attribute.
displayed (bool, default:false): If True the supported attribute will be marked for
display.
source (str, optional): The source value for this attribute.
unique (bool|string, optional): Control attribute creation.
formatter (method, optional): A method that takes a single attribute value and returns a
single formatted value.
Returns:
obj: An instance of Attribute.
"""
attr = Attribute(attr_type, attr_value, displayed, source, formatter)
if unique == 'Type':
for attribute_data in self._attributes:
if attribute_data.type == attr_type:
attr = attribute_data
break
else:
self._attributes.append(attr)
elif unique is True:
for attribute_data in self._attributes:
if attribute_data.type == attr_type and attribute_data.value == attr.value:
attr = attribute_data
break
else:
self._attributes.append(attr)
elif unique is False:
self._attributes.append(attr)
return attr | python | def attribute(
self, attr_type, attr_value, displayed=False, source=None, unique=True, formatter=None
):
"""Return instance of Attribute
unique:
* False - Attribute type:value can be duplicated.
* Type - Attribute type has to be unique (e.g., only 1 Description Attribute).
* True - Attribute type:value combo must be unique.
Args:
attr_type (str): The ThreatConnect defined attribute type.
attr_value (str): The value for this attribute.
displayed (bool, default:false): If True the supported attribute will be marked for
display.
source (str, optional): The source value for this attribute.
unique (bool|string, optional): Control attribute creation.
formatter (method, optional): A method that takes a single attribute value and returns a
single formatted value.
Returns:
obj: An instance of Attribute.
"""
attr = Attribute(attr_type, attr_value, displayed, source, formatter)
if unique == 'Type':
for attribute_data in self._attributes:
if attribute_data.type == attr_type:
attr = attribute_data
break
else:
self._attributes.append(attr)
elif unique is True:
for attribute_data in self._attributes:
if attribute_data.type == attr_type and attribute_data.value == attr.value:
attr = attribute_data
break
else:
self._attributes.append(attr)
elif unique is False:
self._attributes.append(attr)
return attr | [
"def",
"attribute",
"(",
"self",
",",
"attr_type",
",",
"attr_value",
",",
"displayed",
"=",
"False",
",",
"source",
"=",
"None",
",",
"unique",
"=",
"True",
",",
"formatter",
"=",
"None",
")",
":",
"attr",
"=",
"Attribute",
"(",
"attr_type",
",",
"att... | Return instance of Attribute
unique:
* False - Attribute type:value can be duplicated.
* Type - Attribute type has to be unique (e.g., only 1 Description Attribute).
* True - Attribute type:value combo must be unique.
Args:
attr_type (str): The ThreatConnect defined attribute type.
attr_value (str): The value for this attribute.
displayed (bool, default:false): If True the supported attribute will be marked for
display.
source (str, optional): The source value for this attribute.
unique (bool|string, optional): Control attribute creation.
formatter (method, optional): A method that takes a single attribute value and returns a
single formatted value.
Returns:
obj: An instance of Attribute. | [
"Return",
"instance",
"of",
"Attribute"
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L150-L190 | train | 27,591 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | Indicator.data | def data(self):
"""Return Indicator data."""
# add attributes
if self._attributes:
self._indicator_data['attribute'] = []
for attr in self._attributes:
if attr.valid:
self._indicator_data['attribute'].append(attr.data)
# add file actions
if self._file_actions:
self._indicator_data.setdefault('fileAction', {})
self._indicator_data['fileAction'].setdefault('children', [])
for action in self._file_actions:
self._indicator_data['fileAction']['children'].append(action.data)
# add file occurrences
if self._occurrences:
self._indicator_data.setdefault('fileOccurrence', [])
for occurrence in self._occurrences:
self._indicator_data['fileOccurrence'].append(occurrence.data)
# add security labels
if self._labels:
self._indicator_data['securityLabel'] = []
for label in self._labels:
self._indicator_data['securityLabel'].append(label.data)
# add tags
if self._tags:
self._indicator_data['tag'] = []
for tag in self._tags:
if tag.valid:
self._indicator_data['tag'].append(tag.data)
return self._indicator_data | python | def data(self):
"""Return Indicator data."""
# add attributes
if self._attributes:
self._indicator_data['attribute'] = []
for attr in self._attributes:
if attr.valid:
self._indicator_data['attribute'].append(attr.data)
# add file actions
if self._file_actions:
self._indicator_data.setdefault('fileAction', {})
self._indicator_data['fileAction'].setdefault('children', [])
for action in self._file_actions:
self._indicator_data['fileAction']['children'].append(action.data)
# add file occurrences
if self._occurrences:
self._indicator_data.setdefault('fileOccurrence', [])
for occurrence in self._occurrences:
self._indicator_data['fileOccurrence'].append(occurrence.data)
# add security labels
if self._labels:
self._indicator_data['securityLabel'] = []
for label in self._labels:
self._indicator_data['securityLabel'].append(label.data)
# add tags
if self._tags:
self._indicator_data['tag'] = []
for tag in self._tags:
if tag.valid:
self._indicator_data['tag'].append(tag.data)
return self._indicator_data | [
"def",
"data",
"(",
"self",
")",
":",
"# add attributes",
"if",
"self",
".",
"_attributes",
":",
"self",
".",
"_indicator_data",
"[",
"'attribute'",
"]",
"=",
"[",
"]",
"for",
"attr",
"in",
"self",
".",
"_attributes",
":",
"if",
"attr",
".",
"valid",
"... | Return Indicator data. | [
"Return",
"Indicator",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L218-L248 | train | 27,592 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | Indicator.last_modified | def last_modified(self, last_modified):
"""Set Indicator lastModified."""
self._indicator_data['lastModified'] = self._utils.format_datetime(
last_modified, date_format='%Y-%m-%dT%H:%M:%SZ'
) | python | def last_modified(self, last_modified):
"""Set Indicator lastModified."""
self._indicator_data['lastModified'] = self._utils.format_datetime(
last_modified, date_format='%Y-%m-%dT%H:%M:%SZ'
) | [
"def",
"last_modified",
"(",
"self",
",",
"last_modified",
")",
":",
"self",
".",
"_indicator_data",
"[",
"'lastModified'",
"]",
"=",
"self",
".",
"_utils",
".",
"format_datetime",
"(",
"last_modified",
",",
"date_format",
"=",
"'%Y-%m-%dT%H:%M:%SZ'",
")"
] | Set Indicator lastModified. | [
"Set",
"Indicator",
"lastModified",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L268-L272 | train | 27,593 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | Indicator.occurrence | def occurrence(self, file_name=None, path=None, date=None):
"""Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence.
Returns:
obj: An instance of Occurrence.
"""
if self._indicator_data.get('type') != 'File':
# Indicator object has no logger to output warning
return None
occurrence_obj = FileOccurrence(file_name, path, date)
self._occurrences.append(occurrence_obj)
return occurrence_obj | python | def occurrence(self, file_name=None, path=None, date=None):
"""Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence.
Returns:
obj: An instance of Occurrence.
"""
if self._indicator_data.get('type') != 'File':
# Indicator object has no logger to output warning
return None
occurrence_obj = FileOccurrence(file_name, path, date)
self._occurrences.append(occurrence_obj)
return occurrence_obj | [
"def",
"occurrence",
"(",
"self",
",",
"file_name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"if",
"self",
".",
"_indicator_data",
".",
"get",
"(",
"'type'",
")",
"!=",
"'File'",
":",
"# Indicator object has no logger to o... | Add a file Occurrence.
Args:
file_name (str, optional): The file name for this occurrence.
path (str, optional): The file path for this occurrence.
date (str, optional): The datetime expression for this occurrence.
Returns:
obj: An instance of Occurrence. | [
"Add",
"a",
"file",
"Occurrence",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L274-L291 | train | 27,594 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | File.action | def action(self, relationship):
"""Add a File Action."""
action_obj = FileAction(self._indicator_data.get('xid'), relationship)
self._file_actions.append(action_obj)
return action_obj | python | def action(self, relationship):
"""Add a File Action."""
action_obj = FileAction(self._indicator_data.get('xid'), relationship)
self._file_actions.append(action_obj)
return action_obj | [
"def",
"action",
"(",
"self",
",",
"relationship",
")",
":",
"action_obj",
"=",
"FileAction",
"(",
"self",
".",
"_indicator_data",
".",
"get",
"(",
"'xid'",
")",
",",
"relationship",
")",
"self",
".",
"_file_actions",
".",
"append",
"(",
"action_obj",
")",... | Add a File Action. | [
"Add",
"a",
"File",
"Action",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L490-L494 | train | 27,595 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | FileAction.data | def data(self):
"""Return File Occurrence data."""
if self._children:
for child in self._children:
self._action_data.setdefault('children', []).append(child.data)
return self._action_data | python | def data(self):
"""Return File Occurrence data."""
if self._children:
for child in self._children:
self._action_data.setdefault('children', []).append(child.data)
return self._action_data | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_children",
":",
"for",
"child",
"in",
"self",
".",
"_children",
":",
"self",
".",
"_action_data",
".",
"setdefault",
"(",
"'children'",
",",
"[",
"]",
")",
".",
"append",
"(",
"child",
".",
... | Return File Occurrence data. | [
"Return",
"File",
"Occurrence",
"data",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L696-L701 | train | 27,596 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | FileAction.action | def action(self, relationship):
"""Add a nested File Action."""
action_obj = FileAction(self.xid, relationship)
self._children.append(action_obj) | python | def action(self, relationship):
"""Add a nested File Action."""
action_obj = FileAction(self.xid, relationship)
self._children.append(action_obj) | [
"def",
"action",
"(",
"self",
",",
"relationship",
")",
":",
"action_obj",
"=",
"FileAction",
"(",
"self",
".",
"xid",
",",
"relationship",
")",
"self",
".",
"_children",
".",
"append",
"(",
"action_obj",
")"
] | Add a nested File Action. | [
"Add",
"a",
"nested",
"File",
"Action",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L703-L706 | train | 27,597 |
ThreatConnect-Inc/tcex | tcex/tcex_ti_indicator.py | FileOccurrence.date | def date(self, date):
"""Set File Occurrence date."""
self._occurrence_data['date'] = self._utils.format_datetime(
date, date_format='%Y-%m-%dT%H:%M:%SZ'
) | python | def date(self, date):
"""Set File Occurrence date."""
self._occurrence_data['date'] = self._utils.format_datetime(
date, date_format='%Y-%m-%dT%H:%M:%SZ'
) | [
"def",
"date",
"(",
"self",
",",
"date",
")",
":",
"self",
".",
"_occurrence_data",
"[",
"'date'",
"]",
"=",
"self",
".",
"_utils",
".",
"format_datetime",
"(",
"date",
",",
"date_format",
"=",
"'%Y-%m-%dT%H:%M:%SZ'",
")"
] | Set File Occurrence date. | [
"Set",
"File",
"Occurrence",
"date",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L749-L753 | train | 27,598 |
ThreatConnect-Inc/tcex | tcex/tcex_ti/tcex_ti.py | TcExTi.address | def address(self, ip, owner=None, **kwargs):
"""
Create the Address TI object.
Args:
owner:
ip:
**kwargs:
Return:
"""
return Address(self.tcex, ip, owner=owner, **kwargs) | python | def address(self, ip, owner=None, **kwargs):
"""
Create the Address TI object.
Args:
owner:
ip:
**kwargs:
Return:
"""
return Address(self.tcex, ip, owner=owner, **kwargs) | [
"def",
"address",
"(",
"self",
",",
"ip",
",",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Address",
"(",
"self",
".",
"tcex",
",",
"ip",
",",
"owner",
"=",
"owner",
",",
"*",
"*",
"kwargs",
")"
] | Create the Address TI object.
Args:
owner:
ip:
**kwargs:
Return: | [
"Create",
"the",
"Address",
"TI",
"object",
"."
] | dd4d7a1ef723af1561687120191886b9a2fd4b47 | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L52-L64 | train | 27,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.