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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
crytic/slither | slither/slithir/convert.py | find_references_origin | def find_references_origin(irs):
"""
Make lvalue of each Index, Member operation
points to the left variable
"""
for ir in irs:
if isinstance(ir, (Index, Member)):
ir.lvalue.points_to = ir.variable_left | python | def find_references_origin(irs):
"""
Make lvalue of each Index, Member operation
points to the left variable
"""
for ir in irs:
if isinstance(ir, (Index, Member)):
ir.lvalue.points_to = ir.variable_left | [
"def",
"find_references_origin",
"(",
"irs",
")",
":",
"for",
"ir",
"in",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"(",
"Index",
",",
"Member",
")",
")",
":",
"ir",
".",
"lvalue",
".",
"points_to",
"=",
"ir",
".",
"variable_left"
] | Make lvalue of each Index, Member operation
points to the left variable | [
"Make",
"lvalue",
"of",
"each",
"Index",
"Member",
"operation",
"points",
"to",
"the",
"left",
"variable"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L768-L775 | train | 225,700 |
crytic/slither | slither/slithir/convert.py | apply_ir_heuristics | def apply_ir_heuristics(irs, node):
"""
Apply a set of heuristic to improve slithIR
"""
irs = integrate_value_gas(irs)
irs = propagate_type_and_convert_call(irs, node)
irs = remove_unused(irs)
find_references_origin(irs)
return irs | python | def apply_ir_heuristics(irs, node):
"""
Apply a set of heuristic to improve slithIR
"""
irs = integrate_value_gas(irs)
irs = propagate_type_and_convert_call(irs, node)
irs = remove_unused(irs)
find_references_origin(irs)
return irs | [
"def",
"apply_ir_heuristics",
"(",
"irs",
",",
"node",
")",
":",
"irs",
"=",
"integrate_value_gas",
"(",
"irs",
")",
"irs",
"=",
"propagate_type_and_convert_call",
"(",
"irs",
",",
"node",
")",
"irs",
"=",
"remove_unused",
"(",
"irs",
")",
"find_references_ori... | Apply a set of heuristic to improve slithIR | [
"Apply",
"a",
"set",
"of",
"heuristic",
"to",
"improve",
"slithIR"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L832-L844 | train | 225,701 |
crytic/slither | slither/core/declarations/function.py | Function.return_type | def return_type(self):
"""
Return the list of return type
If no return, return None
"""
returns = self.returns
if returns:
return [r.type for r in returns]
return None | python | def return_type(self):
"""
Return the list of return type
If no return, return None
"""
returns = self.returns
if returns:
return [r.type for r in returns]
return None | [
"def",
"return_type",
"(",
"self",
")",
":",
"returns",
"=",
"self",
".",
"returns",
"if",
"returns",
":",
"return",
"[",
"r",
".",
"type",
"for",
"r",
"in",
"returns",
"]",
"return",
"None"
] | Return the list of return type
If no return, return None | [
"Return",
"the",
"list",
"of",
"return",
"type",
"If",
"no",
"return",
"return",
"None"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L249-L257 | train | 225,702 |
crytic/slither | slither/core/declarations/function.py | Function.all_solidity_variables_read | def all_solidity_variables_read(self):
""" recursive version of solidity_read
"""
if self._all_solidity_variables_read is None:
self._all_solidity_variables_read = self._explore_functions(
lambda x: x.solidity_variables_read)
return self._all_solidity_variables_read | python | def all_solidity_variables_read(self):
""" recursive version of solidity_read
"""
if self._all_solidity_variables_read is None:
self._all_solidity_variables_read = self._explore_functions(
lambda x: x.solidity_variables_read)
return self._all_solidity_variables_read | [
"def",
"all_solidity_variables_read",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_solidity_variables_read",
"is",
"None",
":",
"self",
".",
"_all_solidity_variables_read",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"solidity_var... | recursive version of solidity_read | [
"recursive",
"version",
"of",
"solidity_read"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L629-L635 | train | 225,703 |
crytic/slither | slither/core/declarations/function.py | Function.all_state_variables_written | def all_state_variables_written(self):
""" recursive version of variables_written
"""
if self._all_state_variables_written is None:
self._all_state_variables_written = self._explore_functions(
lambda x: x.state_variables_written)
return self._all_state_variables_written | python | def all_state_variables_written(self):
""" recursive version of variables_written
"""
if self._all_state_variables_written is None:
self._all_state_variables_written = self._explore_functions(
lambda x: x.state_variables_written)
return self._all_state_variables_written | [
"def",
"all_state_variables_written",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_state_variables_written",
"is",
"None",
":",
"self",
".",
"_all_state_variables_written",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"state_variab... | recursive version of variables_written | [
"recursive",
"version",
"of",
"variables_written"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L651-L657 | train | 225,704 |
crytic/slither | slither/core/declarations/function.py | Function.all_internal_calls | def all_internal_calls(self):
""" recursive version of internal_calls
"""
if self._all_internals_calls is None:
self._all_internals_calls = self._explore_functions(lambda x: x.internal_calls)
return self._all_internals_calls | python | def all_internal_calls(self):
""" recursive version of internal_calls
"""
if self._all_internals_calls is None:
self._all_internals_calls = self._explore_functions(lambda x: x.internal_calls)
return self._all_internals_calls | [
"def",
"all_internal_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_internals_calls",
"is",
"None",
":",
"self",
".",
"_all_internals_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"internal_calls",
")",
"return",
... | recursive version of internal_calls | [
"recursive",
"version",
"of",
"internal_calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L659-L664 | train | 225,705 |
crytic/slither | slither/core/declarations/function.py | Function.all_low_level_calls | def all_low_level_calls(self):
""" recursive version of low_level calls
"""
if self._all_low_level_calls is None:
self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls)
return self._all_low_level_calls | python | def all_low_level_calls(self):
""" recursive version of low_level calls
"""
if self._all_low_level_calls is None:
self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls)
return self._all_low_level_calls | [
"def",
"all_low_level_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_low_level_calls",
"is",
"None",
":",
"self",
".",
"_all_low_level_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"low_level_calls",
")",
"return",... | recursive version of low_level calls | [
"recursive",
"version",
"of",
"low_level",
"calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L666-L671 | train | 225,706 |
crytic/slither | slither/core/declarations/function.py | Function.all_high_level_calls | def all_high_level_calls(self):
""" recursive version of high_level calls
"""
if self._all_high_level_calls is None:
self._all_high_level_calls = self._explore_functions(lambda x: x.high_level_calls)
return self._all_high_level_calls | python | def all_high_level_calls(self):
""" recursive version of high_level calls
"""
if self._all_high_level_calls is None:
self._all_high_level_calls = self._explore_functions(lambda x: x.high_level_calls)
return self._all_high_level_calls | [
"def",
"all_high_level_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_high_level_calls",
"is",
"None",
":",
"self",
".",
"_all_high_level_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"high_level_calls",
")",
"retu... | recursive version of high_level calls | [
"recursive",
"version",
"of",
"high_level",
"calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L673-L678 | train | 225,707 |
crytic/slither | slither/core/declarations/function.py | Function.all_library_calls | def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls | python | def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls | [
"def",
"all_library_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_library_calls",
"is",
"None",
":",
"self",
".",
"_all_library_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"library_calls",
")",
"return",
"self... | recursive version of library calls | [
"recursive",
"version",
"of",
"library",
"calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L680-L685 | train | 225,708 |
crytic/slither | slither/core/declarations/function.py | Function.all_conditional_state_variables_read | def all_conditional_state_variables_read(self, include_loop=True):
"""
Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_state_variables_read_with_loop is None:
self._all_conditional_state_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read_with_loop
else:
if self._all_conditional_state_variables_read is None:
self._all_conditional_state_variables_read = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read | python | def all_conditional_state_variables_read(self, include_loop=True):
"""
Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_state_variables_read_with_loop is None:
self._all_conditional_state_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read_with_loop
else:
if self._all_conditional_state_variables_read is None:
self._all_conditional_state_variables_read = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read | [
"def",
"all_conditional_state_variables_read",
"(",
"self",
",",
"include_loop",
"=",
"True",
")",
":",
"if",
"include_loop",
":",
"if",
"self",
".",
"_all_conditional_state_variables_read_with_loop",
"is",
"None",
":",
"self",
".",
"_all_conditional_state_variables_read_... | Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable | [
"Return",
"the",
"state",
"variable",
"used",
"in",
"a",
"condition"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L692-L710 | train | 225,709 |
crytic/slither | slither/core/declarations/function.py | Function.all_conditional_solidity_variables_read | def all_conditional_solidity_variables_read(self, include_loop=True):
"""
Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_solidity_variables_read_with_loop is None:
self._all_conditional_solidity_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read_with_loop
else:
if self._all_conditional_solidity_variables_read is None:
self._all_conditional_solidity_variables_read = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read | python | def all_conditional_solidity_variables_read(self, include_loop=True):
"""
Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_solidity_variables_read_with_loop is None:
self._all_conditional_solidity_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read_with_loop
else:
if self._all_conditional_solidity_variables_read is None:
self._all_conditional_solidity_variables_read = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read | [
"def",
"all_conditional_solidity_variables_read",
"(",
"self",
",",
"include_loop",
"=",
"True",
")",
":",
"if",
"include_loop",
":",
"if",
"self",
".",
"_all_conditional_solidity_variables_read_with_loop",
"is",
"None",
":",
"self",
".",
"_all_conditional_solidity_variab... | Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable | [
"Return",
"the",
"Soldiity",
"variables",
"directly",
"used",
"in",
"a",
"condtion"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L726-L747 | train | 225,710 |
crytic/slither | slither/core/declarations/function.py | Function.all_solidity_variables_used_as_args | def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solidity_variables_used_as_args = self._explore_functions(
lambda x: self._explore_func_nodes(x, self._solidity_variable_in_internal_calls))
return self._all_solidity_variables_used_as_args | python | def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solidity_variables_used_as_args = self._explore_functions(
lambda x: self._explore_func_nodes(x, self._solidity_variable_in_internal_calls))
return self._all_solidity_variables_used_as_args | [
"def",
"all_solidity_variables_used_as_args",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_solidity_variables_used_as_args",
"is",
"None",
":",
"self",
".",
"_all_solidity_variables_used_as_args",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"se... | Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender) | [
"Return",
"the",
"Soldiity",
"variables",
"directly",
"used",
"in",
"a",
"call"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L763-L773 | train | 225,711 |
crytic/slither | slither/core/declarations/function.py | Function.is_protected | def is_protected(self):
"""
Determine if the function is protected using a check on msg.sender
Only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool)
"""
if self.is_constructor:
return True
conditional_vars = self.all_conditional_solidity_variables_read(include_loop=False)
args_vars = self.all_solidity_variables_used_as_args()
return SolidityVariableComposed('msg.sender') in conditional_vars + args_vars | python | def is_protected(self):
"""
Determine if the function is protected using a check on msg.sender
Only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool)
"""
if self.is_constructor:
return True
conditional_vars = self.all_conditional_solidity_variables_read(include_loop=False)
args_vars = self.all_solidity_variables_used_as_args()
return SolidityVariableComposed('msg.sender') in conditional_vars + args_vars | [
"def",
"is_protected",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_constructor",
":",
"return",
"True",
"conditional_vars",
"=",
"self",
".",
"all_conditional_solidity_variables_read",
"(",
"include_loop",
"=",
"False",
")",
"args_vars",
"=",
"self",
".",
"all... | Determine if the function is protected using a check on msg.sender
Only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool) | [
"Determine",
"if",
"the",
"function",
"is",
"protected",
"using",
"a",
"check",
"on",
"msg",
".",
"sender"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L940-L956 | train | 225,712 |
TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.auth_string | def auth_string(self):
'''
Authenticate based on username and token which is base64-encoded
'''
username_token = '{username}:{token}'.format(username=self.username, token=self.token)
b64encoded_string = b64encode(username_token)
auth_string = 'Token {b64}'.format(b64=b64encoded_string)
return auth_string | python | def auth_string(self):
'''
Authenticate based on username and token which is base64-encoded
'''
username_token = '{username}:{token}'.format(username=self.username, token=self.token)
b64encoded_string = b64encode(username_token)
auth_string = 'Token {b64}'.format(b64=b64encoded_string)
return auth_string | [
"def",
"auth_string",
"(",
"self",
")",
":",
"username_token",
"=",
"'{username}:{token}'",
".",
"format",
"(",
"username",
"=",
"self",
".",
"username",
",",
"token",
"=",
"self",
".",
"token",
")",
"b64encoded_string",
"=",
"b64encode",
"(",
"username_token"... | Authenticate based on username and token which is base64-encoded | [
"Authenticate",
"based",
"on",
"username",
"and",
"token",
"which",
"is",
"base64",
"-",
"encoded"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L27-L36 | train | 225,713 |
TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.api_related | def api_related(self, query):
'''
Find related objects through SoltraEdge API
'''
url = "{0}/{1}/related/?format=json".format(self.base_url, query)
response = requests.get(url, headers=self.headers, verify=self.verify_ssl)
if response.status_code == 200:
return response.json()
else:
self.error('Received status code: {0} from Soltra Server. Content:\n{1}'.format(
response.status_code, response.text)
) | python | def api_related(self, query):
'''
Find related objects through SoltraEdge API
'''
url = "{0}/{1}/related/?format=json".format(self.base_url, query)
response = requests.get(url, headers=self.headers, verify=self.verify_ssl)
if response.status_code == 200:
return response.json()
else:
self.error('Received status code: {0} from Soltra Server. Content:\n{1}'.format(
response.status_code, response.text)
) | [
"def",
"api_related",
"(",
"self",
",",
"query",
")",
":",
"url",
"=",
"\"{0}/{1}/related/?format=json\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"query",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
"... | Find related objects through SoltraEdge API | [
"Find",
"related",
"objects",
"through",
"SoltraEdge",
"API"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L55-L68 | train | 225,714 |
TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.tlp_classifiers | def tlp_classifiers(self, name_tlp, val_tlp):
'''
Classifier between Cortex and Soltra.
Soltra uses name-TLP, and Cortex "value-TLP"
'''
classifier = {
"WHITE": 0,
"GREEN": 1,
"AMBER": 2,
"RED": 3
}
valid = True
if classifier[name_tlp] > val_tlp:
valid = False
return valid | python | def tlp_classifiers(self, name_tlp, val_tlp):
'''
Classifier between Cortex and Soltra.
Soltra uses name-TLP, and Cortex "value-TLP"
'''
classifier = {
"WHITE": 0,
"GREEN": 1,
"AMBER": 2,
"RED": 3
}
valid = True
if classifier[name_tlp] > val_tlp:
valid = False
return valid | [
"def",
"tlp_classifiers",
"(",
"self",
",",
"name_tlp",
",",
"val_tlp",
")",
":",
"classifier",
"=",
"{",
"\"WHITE\"",
":",
"0",
",",
"\"GREEN\"",
":",
"1",
",",
"\"AMBER\"",
":",
"2",
",",
"\"RED\"",
":",
"3",
"}",
"valid",
"=",
"True",
"if",
"class... | Classifier between Cortex and Soltra.
Soltra uses name-TLP, and Cortex "value-TLP" | [
"Classifier",
"between",
"Cortex",
"and",
"Soltra",
".",
"Soltra",
"uses",
"name",
"-",
"TLP",
"and",
"Cortex",
"value",
"-",
"TLP"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L71-L89 | train | 225,715 |
TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.pop_object | def pop_object(self, element):
'''
Pop the object element if the object contains an higher TLP then allowed.
'''
redacted_text = "Redacted. Object contained TLP value higher than allowed."
element['id'] = ''
element['url'] = ''
element['type'] = ''
element['tags'] = []
element['etlp'] = None
element['title'] = redacted_text
element['tlpColor'] = element['tlpColor']
element['uploaded_on'] = ''
element['uploaded_by'] = ''
element['description'] = redacted_text
element['children_types'] = []
element['summary']['type'] = ''
element['summary']['value'] = ''
element['summary']['title'] = redacted_text
element['summary']['description'] = redacted_text
return element | python | def pop_object(self, element):
'''
Pop the object element if the object contains an higher TLP then allowed.
'''
redacted_text = "Redacted. Object contained TLP value higher than allowed."
element['id'] = ''
element['url'] = ''
element['type'] = ''
element['tags'] = []
element['etlp'] = None
element['title'] = redacted_text
element['tlpColor'] = element['tlpColor']
element['uploaded_on'] = ''
element['uploaded_by'] = ''
element['description'] = redacted_text
element['children_types'] = []
element['summary']['type'] = ''
element['summary']['value'] = ''
element['summary']['title'] = redacted_text
element['summary']['description'] = redacted_text
return element | [
"def",
"pop_object",
"(",
"self",
",",
"element",
")",
":",
"redacted_text",
"=",
"\"Redacted. Object contained TLP value higher than allowed.\"",
"element",
"[",
"'id'",
"]",
"=",
"''",
"element",
"[",
"'url'",
"]",
"=",
"''",
"element",
"[",
"'type'",
"]",
"="... | Pop the object element if the object contains an higher TLP then allowed. | [
"Pop",
"the",
"object",
"element",
"if",
"the",
"object",
"contains",
"an",
"higher",
"TLP",
"then",
"allowed",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L92-L116 | train | 225,716 |
TheHive-Project/Cortex-Analyzers | analyzers/CERTatPassiveDNS/whois_wrapper.py | __query | def __query(domain, limit=100):
"""Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess
functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.
:param domain: The domain pdns is queried with.
:type domain: str
:param limit: Maximum number of results
:type limit: int
:returns: str -- Console output from whois call.
:rtype: str
"""
s = check_output(['{}'.format(os.path.join(os.path.dirname(__file__), 'whois.sh')), '--limit {} {}'.format(limit, domain)], universal_newlines=True)
return s | python | def __query(domain, limit=100):
"""Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess
functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.
:param domain: The domain pdns is queried with.
:type domain: str
:param limit: Maximum number of results
:type limit: int
:returns: str -- Console output from whois call.
:rtype: str
"""
s = check_output(['{}'.format(os.path.join(os.path.dirname(__file__), 'whois.sh')), '--limit {} {}'.format(limit, domain)], universal_newlines=True)
return s | [
"def",
"__query",
"(",
"domain",
",",
"limit",
"=",
"100",
")",
":",
"s",
"=",
"check_output",
"(",
"[",
"'{}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'whois.sh'",
... | Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess
functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.
:param domain: The domain pdns is queried with.
:type domain: str
:param limit: Maximum number of results
:type limit: int
:returns: str -- Console output from whois call.
:rtype: str | [
"Using",
"the",
"shell",
"script",
"to",
"query",
"pdns",
".",
"cert",
".",
"at",
"is",
"a",
"hack",
"but",
"python",
"raises",
"an",
"error",
"every",
"time",
"using",
"subprocess",
"functions",
"to",
"call",
"whois",
".",
"So",
"this",
"hack",
"is",
... | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CERTatPassiveDNS/whois_wrapper.py#L6-L18 | train | 225,717 |
TheHive-Project/Cortex-Analyzers | analyzers/FileInfo/submodules/submodule_oletools.py | OLEToolsSubmodule.analyze_vba | def analyze_vba(self, path):
"""Analyze a given sample for malicious vba."""
try:
vba_parser = VBA_Parser_CLI(path, relaxed=True)
vbaparser_result = vba_parser.process_file_json(show_decoded_strings=True,
display_code=True,
hide_attributes=False,
vba_code_only=False,
show_deobfuscated_code=True,
deobfuscate=True)
self.add_result_subsection('Olevba', vbaparser_result)
except TypeError:
self.add_result_subsection('Oletools VBA Analysis failed', 'Analysis failed due to an filetype error.'
'The file does not seem to be a valid MS-Office '
'file.') | python | def analyze_vba(self, path):
"""Analyze a given sample for malicious vba."""
try:
vba_parser = VBA_Parser_CLI(path, relaxed=True)
vbaparser_result = vba_parser.process_file_json(show_decoded_strings=True,
display_code=True,
hide_attributes=False,
vba_code_only=False,
show_deobfuscated_code=True,
deobfuscate=True)
self.add_result_subsection('Olevba', vbaparser_result)
except TypeError:
self.add_result_subsection('Oletools VBA Analysis failed', 'Analysis failed due to an filetype error.'
'The file does not seem to be a valid MS-Office '
'file.') | [
"def",
"analyze_vba",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"vba_parser",
"=",
"VBA_Parser_CLI",
"(",
"path",
",",
"relaxed",
"=",
"True",
")",
"vbaparser_result",
"=",
"vba_parser",
".",
"process_file_json",
"(",
"show_decoded_strings",
"=",
"True",... | Analyze a given sample for malicious vba. | [
"Analyze",
"a",
"given",
"sample",
"for",
"malicious",
"vba",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/FileInfo/submodules/submodule_oletools.py#L98-L115 | train | 225,718 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/maxminddb/reader.py | Reader.get | def get(self, ip_address):
"""Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation
"""
address = ipaddress.ip_address(ip_address)
if address.version == 6 and self._metadata.ip_version == 4:
raise ValueError('Error looking up {0}. You attempted to look up '
'an IPv6 address in an IPv4-only database.'.format(
ip_address))
pointer = self._find_address_in_tree(address)
return self._resolve_data_pointer(pointer) if pointer else None | python | def get(self, ip_address):
"""Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation
"""
address = ipaddress.ip_address(ip_address)
if address.version == 6 and self._metadata.ip_version == 4:
raise ValueError('Error looking up {0}. You attempted to look up '
'an IPv6 address in an IPv4-only database.'.format(
ip_address))
pointer = self._find_address_in_tree(address)
return self._resolve_data_pointer(pointer) if pointer else None | [
"def",
"get",
"(",
"self",
",",
"ip_address",
")",
":",
"address",
"=",
"ipaddress",
".",
"ip_address",
"(",
"ip_address",
")",
"if",
"address",
".",
"version",
"==",
"6",
"and",
"self",
".",
"_metadata",
".",
"ip_version",
"==",
"4",
":",
"raise",
"Va... | Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation | [
"Return",
"the",
"record",
"for",
"the",
"ip_address",
"in",
"the",
"MaxMind",
"DB"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/maxminddb/reader.py#L61-L76 | train | 225,719 |
TheHive-Project/Cortex-Analyzers | analyzers/Crtsh/crtshquery.py | CrtshAnalyzer.search | def search(self, domain, wildcard=True):
"""
Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "hatch.uber.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
}
XML notation would also include the base64 cert:
https://crt.sh/atom?q={}
"""
base_url = "https://crt.sh/?q={}&output=json"
if wildcard:
domain = "%25.{}".format(domain)
url = base_url.format(domain)
ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
req = requests.get(url, headers={'User-Agent': ua})
if req.ok:
try:
content = req.content.decode('utf-8')
data = json.loads(content.replace('}{', '},{'))
return data
except Exception:
self.error("Error retrieving information.")
return None | python | def search(self, domain, wildcard=True):
"""
Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "hatch.uber.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
}
XML notation would also include the base64 cert:
https://crt.sh/atom?q={}
"""
base_url = "https://crt.sh/?q={}&output=json"
if wildcard:
domain = "%25.{}".format(domain)
url = base_url.format(domain)
ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
req = requests.get(url, headers={'User-Agent': ua})
if req.ok:
try:
content = req.content.decode('utf-8')
data = json.loads(content.replace('}{', '},{'))
return data
except Exception:
self.error("Error retrieving information.")
return None | [
"def",
"search",
"(",
"self",
",",
"domain",
",",
"wildcard",
"=",
"True",
")",
":",
"base_url",
"=",
"\"https://crt.sh/?q={}&output=json\"",
"if",
"wildcard",
":",
"domain",
"=",
"\"%25.{}\"",
".",
"format",
"(",
"domain",
")",
"url",
"=",
"base_url",
".",
... | Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "hatch.uber.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
}
XML notation would also include the base64 cert:
https://crt.sh/atom?q={} | [
"Search",
"crt",
".",
"sh",
"for",
"the",
"given",
"domain",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Crtsh/crtshquery.py#L10-L47 | train | 225,720 |
TheHive-Project/Cortex-Analyzers | analyzers/MISP/mispclient.py | MISPClient.__search | def __search(self, value, type_attribute):
"""Search method call wrapper.
:param value: value to search for.
:type value: str
:param type_attribute: attribute types to search for.
:type type_attribute: [list, none]
"""
results = []
if not value:
raise EmptySearchtermError
for idx, connection in enumerate(self.misp_connections):
misp_response = connection.search(type_attribute=type_attribute, values=value)
# Fixes #94
if isinstance(self.misp_name, list):
name = self.misp_name[idx]
else:
name = self.misp_name
results.append({'url': connection.root_url,
'name': name,
'result': self.__clean(misp_response)})
return results | python | def __search(self, value, type_attribute):
"""Search method call wrapper.
:param value: value to search for.
:type value: str
:param type_attribute: attribute types to search for.
:type type_attribute: [list, none]
"""
results = []
if not value:
raise EmptySearchtermError
for idx, connection in enumerate(self.misp_connections):
misp_response = connection.search(type_attribute=type_attribute, values=value)
# Fixes #94
if isinstance(self.misp_name, list):
name = self.misp_name[idx]
else:
name = self.misp_name
results.append({'url': connection.root_url,
'name': name,
'result': self.__clean(misp_response)})
return results | [
"def",
"__search",
"(",
"self",
",",
"value",
",",
"type_attribute",
")",
":",
"results",
"=",
"[",
"]",
"if",
"not",
"value",
":",
"raise",
"EmptySearchtermError",
"for",
"idx",
",",
"connection",
"in",
"enumerate",
"(",
"self",
".",
"misp_connections",
"... | Search method call wrapper.
:param value: value to search for.
:type value: str
:param type_attribute: attribute types to search for.
:type type_attribute: [list, none] | [
"Search",
"method",
"call",
"wrapper",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MISP/mispclient.py#L213-L236 | train | 225,721 |
TheHive-Project/Cortex-Analyzers | analyzers/TorBlutmagie/tor_blutmagie.py | TorBlutmagieClient.search_tor_node | def search_tor_node(self, data_type, data):
"""Lookup an artifact to check if it is a known tor exit node.
:param data_type: The artifact type. Must be one of 'ip', 'fqdn'
or 'domain'
:param data: The artifact to lookup
:type data_type: str
:type data: str
:return: Data relative to the tor node. If the looked-up artifact is
related to a tor exit node it will contain a `nodes` array.
That array will contains a list of nodes containing the
following keys:
- name: name given to the router
- ip: their IP address
- hostname: Hostname of the router
- country_code: ISO2 code of the country hosting the router
- as_name: ASName registering the router
- as_number: ASNumber registering the router
Otherwise, `nodes` will be empty.
:rtype: list
"""
results = []
if data_type == 'ip':
results = self._get_node_from_ip(data)
elif data_type == 'fqdn':
results = self._get_node_from_fqdn(data)
elif data_type == 'domain':
results = self._get_node_from_domain(data)
else:
pass
return {"nodes": results} | python | def search_tor_node(self, data_type, data):
"""Lookup an artifact to check if it is a known tor exit node.
:param data_type: The artifact type. Must be one of 'ip', 'fqdn'
or 'domain'
:param data: The artifact to lookup
:type data_type: str
:type data: str
:return: Data relative to the tor node. If the looked-up artifact is
related to a tor exit node it will contain a `nodes` array.
That array will contains a list of nodes containing the
following keys:
- name: name given to the router
- ip: their IP address
- hostname: Hostname of the router
- country_code: ISO2 code of the country hosting the router
- as_name: ASName registering the router
- as_number: ASNumber registering the router
Otherwise, `nodes` will be empty.
:rtype: list
"""
results = []
if data_type == 'ip':
results = self._get_node_from_ip(data)
elif data_type == 'fqdn':
results = self._get_node_from_fqdn(data)
elif data_type == 'domain':
results = self._get_node_from_domain(data)
else:
pass
return {"nodes": results} | [
"def",
"search_tor_node",
"(",
"self",
",",
"data_type",
",",
"data",
")",
":",
"results",
"=",
"[",
"]",
"if",
"data_type",
"==",
"'ip'",
":",
"results",
"=",
"self",
".",
"_get_node_from_ip",
"(",
"data",
")",
"elif",
"data_type",
"==",
"'fqdn'",
":",
... | Lookup an artifact to check if it is a known tor exit node.
:param data_type: The artifact type. Must be one of 'ip', 'fqdn'
or 'domain'
:param data: The artifact to lookup
:type data_type: str
:type data: str
:return: Data relative to the tor node. If the looked-up artifact is
related to a tor exit node it will contain a `nodes` array.
That array will contains a list of nodes containing the
following keys:
- name: name given to the router
- ip: their IP address
- hostname: Hostname of the router
- country_code: ISO2 code of the country hosting the router
- as_name: ASName registering the router
- as_number: ASNumber registering the router
Otherwise, `nodes` will be empty.
:rtype: list | [
"Lookup",
"an",
"artifact",
"to",
"check",
"if",
"it",
"is",
"a",
"known",
"tor",
"exit",
"node",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/TorBlutmagie/tor_blutmagie.py#L80-L110 | train | 225,722 |
TheHive-Project/Cortex-Analyzers | analyzers/Yara/yara_analyzer.py | YaraAnalyzer.check | def check(self, file):
"""
Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list
"""
result = []
for rule in self.ruleset:
matches = rule.match(file)
for match in matches:
result.append(str(match))
return result | python | def check(self, file):
"""
Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list
"""
result = []
for rule in self.ruleset:
matches = rule.match(file)
for match in matches:
result.append(str(match))
return result | [
"def",
"check",
"(",
"self",
",",
"file",
")",
":",
"result",
"=",
"[",
"]",
"for",
"rule",
"in",
"self",
".",
"ruleset",
":",
"matches",
"=",
"rule",
".",
"match",
"(",
"file",
")",
"for",
"match",
"in",
"matches",
":",
"result",
".",
"append",
... | Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list | [
"Checks",
"a",
"given",
"file",
"against",
"all",
"available",
"yara",
"rules"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Yara/yara_analyzer.py#L32-L47 | train | 225,723 |
TheHive-Project/Cortex-Analyzers | analyzers/CIRCLPassiveDNS/circl_passivedns.py | CIRCLPassiveDNSAnalyzer.query | def query(self, domain):
"""The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict]
"""
result = {}
try:
result = self.pdns.query(domain)
except:
self.error('Exception while querying passiveDNS. Check the domain format.')
# Clean the datetime problems in order to correct the json serializability
clean_result = []
for ind, resultset in enumerate(result):
if resultset.get('time_first', None):
resultset['time_first'] = resultset.get('time_first').isoformat(' ')
if resultset.get('time_last', None):
resultset['time_last'] = resultset.get('time_last').isoformat(' ')
clean_result.append(resultset)
return clean_result | python | def query(self, domain):
"""The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict]
"""
result = {}
try:
result = self.pdns.query(domain)
except:
self.error('Exception while querying passiveDNS. Check the domain format.')
# Clean the datetime problems in order to correct the json serializability
clean_result = []
for ind, resultset in enumerate(result):
if resultset.get('time_first', None):
resultset['time_first'] = resultset.get('time_first').isoformat(' ')
if resultset.get('time_last', None):
resultset['time_last'] = resultset.get('time_last').isoformat(' ')
clean_result.append(resultset)
return clean_result | [
"def",
"query",
"(",
"self",
",",
"domain",
")",
":",
"result",
"=",
"{",
"}",
"try",
":",
"result",
"=",
"self",
".",
"pdns",
".",
"query",
"(",
"domain",
")",
"except",
":",
"self",
".",
"error",
"(",
"'Exception while querying passiveDNS. Check the doma... | The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict] | [
"The",
"actual",
"query",
"happens",
"here",
".",
"Time",
"from",
"queries",
"is",
"replaced",
"with",
"isoformat",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CIRCLPassiveDNS/circl_passivedns.py#L13-L37 | train | 225,724 |
TheHive-Project/Cortex-Analyzers | analyzers/CIRCLPassiveSSL/circl_passivessl.py | CIRCLPassiveSSLAnalyzer.query_ip | def query_ip(self, ip):
"""
Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found.
:param ip: IP to query for
:type ip: str
:returns: python dict of results
:rtype: dict
"""
try:
result = self.pssl.query(ip)
except:
self.error('Exception during processing with passiveSSL. '
'Please check the format of ip.')
# Check for empty result
# result is always assigned, self.error exits the function.
if not result.get(ip, None):
certificates = []
else:
certificates = list(result.get(ip).get('certificates'))
newresult = {'ip': ip,
'certificates': []}
for cert in certificates:
newresult['certificates'].append({'fingerprint': cert,
'subject': result.get(ip).get('subjects').get(cert).get('values')[0]})
return newresult | python | def query_ip(self, ip):
"""
Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found.
:param ip: IP to query for
:type ip: str
:returns: python dict of results
:rtype: dict
"""
try:
result = self.pssl.query(ip)
except:
self.error('Exception during processing with passiveSSL. '
'Please check the format of ip.')
# Check for empty result
# result is always assigned, self.error exits the function.
if not result.get(ip, None):
certificates = []
else:
certificates = list(result.get(ip).get('certificates'))
newresult = {'ip': ip,
'certificates': []}
for cert in certificates:
newresult['certificates'].append({'fingerprint': cert,
'subject': result.get(ip).get('subjects').get(cert).get('values')[0]})
return newresult | [
"def",
"query_ip",
"(",
"self",
",",
"ip",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"pssl",
".",
"query",
"(",
"ip",
")",
"except",
":",
"self",
".",
"error",
"(",
"'Exception during processing with passiveSSL. '",
"'Please check the format of ip.'",
... | Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found.
:param ip: IP to query for
:type ip: str
:returns: python dict of results
:rtype: dict | [
"Queries",
"Circl",
".",
"lu",
"Passive",
"SSL",
"for",
"an",
"ip",
"using",
"PyPSSL",
"class",
".",
"Returns",
"error",
"if",
"nothing",
"is",
"found",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CIRCLPassiveSSL/circl_passivessl.py#L16-L43 | train | 225,725 |
TheHive-Project/Cortex-Analyzers | analyzers/CIRCLPassiveSSL/circl_passivessl.py | CIRCLPassiveSSLAnalyzer.query_certificate | def query_certificate(self, cert_hash):
"""
Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.
:param cert_hash: hash to query for
:type cert_hash: str
:return: python dict of results
:rtype: dict
"""
try:
cquery = self.pssl.query_cert(cert_hash)
except Exception:
self.error('Exception during processing with passiveSSL. '
'This happens if the given hash is not sha1 or contains dashes/colons etc. '
'Please make sure to submit a clean formatted sha1 hash.')
# fetch_cert raises an error if no certificate was found.
try:
cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)
except Exception:
cfetch = {}
return {'query': cquery,
'cert': cfetch} | python | def query_certificate(self, cert_hash):
"""
Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.
:param cert_hash: hash to query for
:type cert_hash: str
:return: python dict of results
:rtype: dict
"""
try:
cquery = self.pssl.query_cert(cert_hash)
except Exception:
self.error('Exception during processing with passiveSSL. '
'This happens if the given hash is not sha1 or contains dashes/colons etc. '
'Please make sure to submit a clean formatted sha1 hash.')
# fetch_cert raises an error if no certificate was found.
try:
cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)
except Exception:
cfetch = {}
return {'query': cquery,
'cert': cfetch} | [
"def",
"query_certificate",
"(",
"self",
",",
"cert_hash",
")",
":",
"try",
":",
"cquery",
"=",
"self",
".",
"pssl",
".",
"query_cert",
"(",
"cert_hash",
")",
"except",
"Exception",
":",
"self",
".",
"error",
"(",
"'Exception during processing with passiveSSL. '... | Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.
:param cert_hash: hash to query for
:type cert_hash: str
:return: python dict of results
:rtype: dict | [
"Queries",
"Circl",
".",
"lu",
"Passive",
"SSL",
"for",
"a",
"certificate",
"hash",
"using",
"PyPSSL",
"class",
".",
"Returns",
"error",
"if",
"nothing",
"is",
"found",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CIRCLPassiveSSL/circl_passivessl.py#L45-L68 | train | 225,726 |
TheHive-Project/Cortex-Analyzers | analyzers/GreyNoise/greynoise.py | GreyNoiseAnalyzer._get_level | def _get_level(current_level, new_intention):
"""
Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive-Project/CortexDocs/blob/master/api/how-to-create-an-analyzer.md#output
:param new_intention: An intention field value from a GreyNoise record
https://github.com/GreyNoise-Intelligence/api.greynoise.io#v1queryip
:return: The more malicious of the 2 submitted values as a Cortex maliciousness level
"""
intention_level_map = OrderedDict([
('info', 'info'),
('benign', 'safe'),
('suspicious', 'suspicious'),
('malicious', 'malicious')
])
levels = intention_level_map.values()
new_level = intention_level_map.get(new_intention, 'info')
new_index = levels.index(new_level)
try:
current_index = levels.index(current_level)
except ValueError: # There is no existing level
current_index = -1
return new_level if new_index > current_index else current_level | python | def _get_level(current_level, new_intention):
"""
Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive-Project/CortexDocs/blob/master/api/how-to-create-an-analyzer.md#output
:param new_intention: An intention field value from a GreyNoise record
https://github.com/GreyNoise-Intelligence/api.greynoise.io#v1queryip
:return: The more malicious of the 2 submitted values as a Cortex maliciousness level
"""
intention_level_map = OrderedDict([
('info', 'info'),
('benign', 'safe'),
('suspicious', 'suspicious'),
('malicious', 'malicious')
])
levels = intention_level_map.values()
new_level = intention_level_map.get(new_intention, 'info')
new_index = levels.index(new_level)
try:
current_index = levels.index(current_level)
except ValueError: # There is no existing level
current_index = -1
return new_level if new_index > current_index else current_level | [
"def",
"_get_level",
"(",
"current_level",
",",
"new_intention",
")",
":",
"intention_level_map",
"=",
"OrderedDict",
"(",
"[",
"(",
"'info'",
",",
"'info'",
")",
",",
"(",
"'benign'",
",",
"'safe'",
")",
",",
"(",
"'suspicious'",
",",
"'suspicious'",
")",
... | Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive-Project/CortexDocs/blob/master/api/how-to-create-an-analyzer.md#output
:param new_intention: An intention field value from a GreyNoise record
https://github.com/GreyNoise-Intelligence/api.greynoise.io#v1queryip
:return: The more malicious of the 2 submitted values as a Cortex maliciousness level | [
"Map",
"GreyNoise",
"intentions",
"to",
"Cortex",
"maliciousness",
"levels",
".",
"Accept",
"a",
"Cortex",
"level",
"and",
"a",
"GreyNoise",
"intention",
"the",
"return",
"the",
"more",
"malicious",
"of",
"the",
"two",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/GreyNoise/greynoise.py#L16-L44 | train | 225,727 |
TheHive-Project/Cortex-Analyzers | analyzers/GreyNoise/greynoise.py | GreyNoiseAnalyzer.summary | def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{
"name": SCANNER1,
"intention": ""
}
Output
GreyNoise:SCANNER1 = 1 (info)
Input
{
"name": SCANNER1,
"intention": "malicious"
},
{
"name": SCANNER1,
"intention": "benign"
}
Output
GreyNoise:SCANNER1 = 2 (malicious)
Input
{
"name": SCANNER1,
"intention": ""
},
{
"name": SCANNER1,
"intention": "safe"
},
{
"name": SCANNER2,
"intention": ""
}
Output
GreyNoise:entries = 3 (safe)
"""
try:
taxonomies = []
if raw.get('records'):
final_level = None
taxonomy_data = defaultdict(int)
for record in raw.get('records', []):
name = record.get('name', 'unknown')
intention = record.get('intention', 'unknown')
taxonomy_data[name] += 1
final_level = self._get_level(final_level, intention)
if len(taxonomy_data) > 1: # Multiple tags have been found
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', 'entries', len(taxonomy_data)))
else: # There is only one tag found, possibly multiple times
for name, count in taxonomy_data.iteritems():
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', name, count))
else:
taxonomies.append(self.build_taxonomy('info', 'GreyNoise', 'Records', 'None'))
return {"taxonomies": taxonomies}
except Exception as e:
self.error('Summary failed\n{}'.format(e.message)) | python | def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{
"name": SCANNER1,
"intention": ""
}
Output
GreyNoise:SCANNER1 = 1 (info)
Input
{
"name": SCANNER1,
"intention": "malicious"
},
{
"name": SCANNER1,
"intention": "benign"
}
Output
GreyNoise:SCANNER1 = 2 (malicious)
Input
{
"name": SCANNER1,
"intention": ""
},
{
"name": SCANNER1,
"intention": "safe"
},
{
"name": SCANNER2,
"intention": ""
}
Output
GreyNoise:entries = 3 (safe)
"""
try:
taxonomies = []
if raw.get('records'):
final_level = None
taxonomy_data = defaultdict(int)
for record in raw.get('records', []):
name = record.get('name', 'unknown')
intention = record.get('intention', 'unknown')
taxonomy_data[name] += 1
final_level = self._get_level(final_level, intention)
if len(taxonomy_data) > 1: # Multiple tags have been found
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', 'entries', len(taxonomy_data)))
else: # There is only one tag found, possibly multiple times
for name, count in taxonomy_data.iteritems():
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', name, count))
else:
taxonomies.append(self.build_taxonomy('info', 'GreyNoise', 'Records', 'None'))
return {"taxonomies": taxonomies}
except Exception as e:
self.error('Summary failed\n{}'.format(e.message)) | [
"def",
"summary",
"(",
"self",
",",
"raw",
")",
":",
"try",
":",
"taxonomies",
"=",
"[",
"]",
"if",
"raw",
".",
"get",
"(",
"'records'",
")",
":",
"final_level",
"=",
"None",
"taxonomy_data",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"record",
"in"... | Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{
"name": SCANNER1,
"intention": ""
}
Output
GreyNoise:SCANNER1 = 1 (info)
Input
{
"name": SCANNER1,
"intention": "malicious"
},
{
"name": SCANNER1,
"intention": "benign"
}
Output
GreyNoise:SCANNER1 = 2 (malicious)
Input
{
"name": SCANNER1,
"intention": ""
},
{
"name": SCANNER1,
"intention": "safe"
},
{
"name": SCANNER2,
"intention": ""
}
Output
GreyNoise:entries = 3 (safe) | [
"Return",
"one",
"taxonomy",
"summarizing",
"the",
"reported",
"tags",
"If",
"there",
"is",
"only",
"one",
"tag",
"use",
"it",
"as",
"the",
"predicate",
"If",
"there",
"are",
"multiple",
"tags",
"use",
"entries",
"as",
"the",
"predicate",
"Use",
"the",
"to... | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/GreyNoise/greynoise.py#L62-L136 | train | 225,728 |
TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PublicApi.scan_file | def scan_file(self, this_file):
""" Submit a file to be scanned by VirusTotal
:param this_file: File to be scanned (32MB file size limit)
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key}
try:
if type(this_file) == str and os.path.isfile(this_file):
files = {'file': (this_file, open(this_file, 'rb'))}
elif isinstance(this_file, StringIO.StringIO):
files = {'file': this_file.read()}
else:
files = {'file': this_file}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/scan', files=files, params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def scan_file(self, this_file):
""" Submit a file to be scanned by VirusTotal
:param this_file: File to be scanned (32MB file size limit)
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key}
try:
if type(this_file) == str and os.path.isfile(this_file):
files = {'file': (this_file, open(this_file, 'rb'))}
elif isinstance(this_file, StringIO.StringIO):
files = {'file': this_file.read()}
else:
files = {'file': this_file}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/scan', files=files, params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"scan_file",
"(",
"self",
",",
"this_file",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
"}",
"try",
":",
"if",
"type",
"(",
"this_file",
")",
"==",
"str",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"this_file",
... | Submit a file to be scanned by VirusTotal
:param this_file: File to be scanned (32MB file size limit)
:return: JSON response that contains scan_id and permalink. | [
"Submit",
"a",
"file",
"to",
"be",
"scanned",
"by",
"VirusTotal"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L62-L84 | train | 225,729 |
TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PublicApi.scan_url | def scan_url(self, this_url):
""" Submit a URL to be scanned by VirusTotal.
:param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the
standard request rate) so as to perform a batch scanning request with one single call. The
URLs must be separated by a new line character.
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key, 'url': this_url}
try:
response = requests.post(self.base + 'url/scan', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def scan_url(self, this_url):
""" Submit a URL to be scanned by VirusTotal.
:param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the
standard request rate) so as to perform a batch scanning request with one single call. The
URLs must be separated by a new line character.
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key, 'url': this_url}
try:
response = requests.post(self.base + 'url/scan', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"scan_url",
"(",
"self",
",",
"this_url",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'url'",
":",
"this_url",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"base",
"+",
"'url/sca... | Submit a URL to be scanned by VirusTotal.
:param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the
standard request rate) so as to perform a batch scanning request with one single call. The
URLs must be separated by a new line character.
:return: JSON response that contains scan_id and permalink. | [
"Submit",
"a",
"URL",
"to",
"be",
"scanned",
"by",
"VirusTotal",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L124-L139 | train | 225,730 |
TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PrivateApi.get_file | def get_file(self, this_hash):
""" Download a file by its hash.
Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with
the file searching call in order to download samples that match a given set of criteria.
:param this_hash: The md5/sha1/sha256 hash of the file you want to download.
:return: Downloaded file in response.content
"""
params = {'apikey': self.api_key, 'hash': this_hash}
try:
response = requests.get(self.base + 'file/download', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
if response.status_code == requests.codes.ok:
return response.content
elif response.status_code == 403:
return dict(error='You tried to perform calls to functions for which you require a Private API key.',
response_code=response.status_code)
elif response.status_code == 404:
return dict(error='File not found.', response_code=response.status_code)
else:
return dict(response_code=response.status_code) | python | def get_file(self, this_hash):
""" Download a file by its hash.
Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with
the file searching call in order to download samples that match a given set of criteria.
:param this_hash: The md5/sha1/sha256 hash of the file you want to download.
:return: Downloaded file in response.content
"""
params = {'apikey': self.api_key, 'hash': this_hash}
try:
response = requests.get(self.base + 'file/download', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
if response.status_code == requests.codes.ok:
return response.content
elif response.status_code == 403:
return dict(error='You tried to perform calls to functions for which you require a Private API key.',
response_code=response.status_code)
elif response.status_code == 404:
return dict(error='File not found.', response_code=response.status_code)
else:
return dict(response_code=response.status_code) | [
"def",
"get_file",
"(",
"self",
",",
"this_hash",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'hash'",
":",
"this_hash",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base",
"+",
"'file/... | Download a file by its hash.
Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with
the file searching call in order to download samples that match a given set of criteria.
:param this_hash: The md5/sha1/sha256 hash of the file you want to download.
:return: Downloaded file in response.content | [
"Download",
"a",
"file",
"by",
"its",
"hash",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L501-L525 | train | 225,731 |
TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PrivateApi.get_url_report | def get_url_report(self, this_url, scan='0', allinfo=1):
""" Get the scan results for a URL.
:param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id
(sha256-timestamp as returned by the URL submission API) to access a specific report. At the same time, you
can specify a CSV list made up of a combination of urls and scan_ids (up to 25 items) so as to perform a batch
request with one single call. The CSV list must be separated by new line characters.
:param scan: (optional) This is an optional parameter that when set to "1" will automatically submit the URL
for analysis if no report is found for it in VirusTotal's database. In this case the result will contain a
scan_id field that can be used to query the analysis report later on.
:param allinfo: (optional) If this parameter is specified and set to "1" additional info regarding the URL
(other than the URL scanning engine results) will also be returned. This additional info includes VirusTotal
related metadata (first seen date, last seen date, files downloaded from the given URL, etc.) and the output
of other tools and datasets when fed with the URL.
:return: JSON response
"""
params = {'apikey': self.api_key, 'resource': this_url, 'scan': scan, 'allinfo': allinfo}
try:
response = requests.get(self.base + 'url/report', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def get_url_report(self, this_url, scan='0', allinfo=1):
""" Get the scan results for a URL.
:param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id
(sha256-timestamp as returned by the URL submission API) to access a specific report. At the same time, you
can specify a CSV list made up of a combination of urls and scan_ids (up to 25 items) so as to perform a batch
request with one single call. The CSV list must be separated by new line characters.
:param scan: (optional) This is an optional parameter that when set to "1" will automatically submit the URL
for analysis if no report is found for it in VirusTotal's database. In this case the result will contain a
scan_id field that can be used to query the analysis report later on.
:param allinfo: (optional) If this parameter is specified and set to "1" additional info regarding the URL
(other than the URL scanning engine results) will also be returned. This additional info includes VirusTotal
related metadata (first seen date, last seen date, files downloaded from the given URL, etc.) and the output
of other tools and datasets when fed with the URL.
:return: JSON response
"""
params = {'apikey': self.api_key, 'resource': this_url, 'scan': scan, 'allinfo': allinfo}
try:
response = requests.get(self.base + 'url/report', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"get_url_report",
"(",
"self",
",",
"this_url",
",",
"scan",
"=",
"'0'",
",",
"allinfo",
"=",
"1",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'resource'",
":",
"this_url",
",",
"'scan'",
":",
"scan",
",",
"'al... | Get the scan results for a URL.
:param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id
(sha256-timestamp as returned by the URL submission API) to access a specific report. At the same time, you
can specify a CSV list made up of a combination of urls and scan_ids (up to 25 items) so as to perform a batch
request with one single call. The CSV list must be separated by new line characters.
:param scan: (optional) This is an optional parameter that when set to "1" will automatically submit the URL
for analysis if no report is found for it in VirusTotal's database. In this case the result will contain a
scan_id field that can be used to query the analysis report later on.
:param allinfo: (optional) If this parameter is specified and set to "1" additional info regarding the URL
(other than the URL scanning engine results) will also be returned. This additional info includes VirusTotal
related metadata (first seen date, last seen date, files downloaded from the given URL, etc.) and the output
of other tools and datasets when fed with the URL.
:return: JSON response | [
"Get",
"the",
"scan",
"results",
"for",
"a",
"URL",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L548-L572 | train | 225,732 |
TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PrivateApi.get_comments | def get_comments(self, resource, before=None):
""" Get comments for a file or URL.
Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are
user submitted reviews on a given item, these comments may contain anything from the in-the-wild locations of
files up to fully-featured reverse engineering reports on a given sample.
:param resource: Either an md5/sha1/sha256 hash of the file or the URL itself you want to retrieve.
:param before: (optional) A datetime token that allows you to iterate over all comments on a specific item
whenever it has been commented on more than 25 times.
:return: JSON response - The application answers with the comments sorted in descending order according to
their date.
"""
params = dict(apikey=self.api_key, resource=resource, before=before)
try:
response = requests.get(self.base + 'comments/get', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def get_comments(self, resource, before=None):
""" Get comments for a file or URL.
Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are
user submitted reviews on a given item, these comments may contain anything from the in-the-wild locations of
files up to fully-featured reverse engineering reports on a given sample.
:param resource: Either an md5/sha1/sha256 hash of the file or the URL itself you want to retrieve.
:param before: (optional) A datetime token that allows you to iterate over all comments on a specific item
whenever it has been commented on more than 25 times.
:return: JSON response - The application answers with the comments sorted in descending order according to
their date.
"""
params = dict(apikey=self.api_key, resource=resource, before=before)
try:
response = requests.get(self.base + 'comments/get', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"get_comments",
"(",
"self",
",",
"resource",
",",
"before",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"apikey",
"=",
"self",
".",
"api_key",
",",
"resource",
"=",
"resource",
",",
"before",
"=",
"before",
")",
"try",
":",
"response",
... | Get comments for a file or URL.
Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are
user submitted reviews on a given item, these comments may contain anything from the in-the-wild locations of
files up to fully-featured reverse engineering reports on a given sample.
:param resource: Either an md5/sha1/sha256 hash of the file or the URL itself you want to retrieve.
:param before: (optional) A datetime token that allows you to iterate over all comments on a specific item
whenever it has been commented on more than 25 times.
:return: JSON response - The application answers with the comments sorted in descending order according to
their date. | [
"Get",
"comments",
"for",
"a",
"file",
"or",
"URL",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L659-L679 | train | 225,733 |
TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | IntelApi.save_downloaded_file | def save_downloaded_file(filename, save_file_at, file_stream):
""" Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file.
"""
filename = os.path.join(save_file_at, filename)
with open(filename, 'wb') as f:
f.write(file_stream)
f.flush() | python | def save_downloaded_file(filename, save_file_at, file_stream):
""" Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file.
"""
filename = os.path.join(save_file_at, filename)
with open(filename, 'wb') as f:
f.write(file_stream)
f.flush() | [
"def",
"save_downloaded_file",
"(",
"filename",
",",
"save_file_at",
",",
"file_stream",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"save_file_at",
",",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
"... | Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file. | [
"Save",
"Downloaded",
"File",
"to",
"Disk",
"Helper",
"Function"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L758-L768 | train | 225,734 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/geoip2/records.py | PlaceRecord.name | def name(self):
"""Dict with locale codes as keys and localized name as value"""
# pylint:disable=E1101
return next((self.names.get(x) for x in self._locales if x in
self.names), None) | python | def name(self):
"""Dict with locale codes as keys and localized name as value"""
# pylint:disable=E1101
return next((self.names.get(x) for x in self._locales if x in
self.names), None) | [
"def",
"name",
"(",
"self",
")",
":",
"# pylint:disable=E1101",
"return",
"next",
"(",
"(",
"self",
".",
"names",
".",
"get",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_locales",
"if",
"x",
"in",
"self",
".",
"names",
")",
",",
"None",
")"
] | Dict with locale codes as keys and localized name as value | [
"Dict",
"with",
"locale",
"codes",
"as",
"keys",
"and",
"localized",
"name",
"as",
"value"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/geoip2/records.py#L40-L44 | train | 225,735 |
TheHive-Project/Cortex-Analyzers | analyzers/Patrowl/patrowl.py | PatrowlAnalyzer.summary | def summary(self, raw):
"""Parse, format and return scan summary."""
taxonomies = []
level = "info"
namespace = "Patrowl"
# getreport service
if self.service == 'getreport':
if 'risk_level' in raw and raw['risk_level']:
risk_level = raw['risk_level']
# Grade
if risk_level['grade'] in ["A", "B"]:
level = "safe"
else:
level = "suspicious"
taxonomies.append(self.build_taxonomy(level, namespace, "Grade", risk_level['grade']))
# Findings
if risk_level['high'] > 0:
level = "malicious"
elif risk_level['medium'] > 0 or risk_level['low'] > 0:
level = "suspicious"
else:
level = "info"
taxonomies.append(self.build_taxonomy(
level, namespace, "Findings", "{}/{}/{}/{}".format(
risk_level['high'],
risk_level['medium'],
risk_level['low'],
risk_level['info']
)))
#todo: add_asset service
return {"taxonomies": taxonomies} | python | def summary(self, raw):
"""Parse, format and return scan summary."""
taxonomies = []
level = "info"
namespace = "Patrowl"
# getreport service
if self.service == 'getreport':
if 'risk_level' in raw and raw['risk_level']:
risk_level = raw['risk_level']
# Grade
if risk_level['grade'] in ["A", "B"]:
level = "safe"
else:
level = "suspicious"
taxonomies.append(self.build_taxonomy(level, namespace, "Grade", risk_level['grade']))
# Findings
if risk_level['high'] > 0:
level = "malicious"
elif risk_level['medium'] > 0 or risk_level['low'] > 0:
level = "suspicious"
else:
level = "info"
taxonomies.append(self.build_taxonomy(
level, namespace, "Findings", "{}/{}/{}/{}".format(
risk_level['high'],
risk_level['medium'],
risk_level['low'],
risk_level['info']
)))
#todo: add_asset service
return {"taxonomies": taxonomies} | [
"def",
"summary",
"(",
"self",
",",
"raw",
")",
":",
"taxonomies",
"=",
"[",
"]",
"level",
"=",
"\"info\"",
"namespace",
"=",
"\"Patrowl\"",
"# getreport service",
"if",
"self",
".",
"service",
"==",
"'getreport'",
":",
"if",
"'risk_level'",
"in",
"raw",
"... | Parse, format and return scan summary. | [
"Parse",
"format",
"and",
"return",
"scan",
"summary",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Patrowl/patrowl.py#L17-L53 | train | 225,736 |
TheHive-Project/Cortex-Analyzers | analyzers/Patrowl/patrowl.py | PatrowlAnalyzer.run | def run(self):
"""Run the analyzer."""
try:
if self.service == 'getreport':
service_url = '{}/assets/api/v1/details/{}'.format(
self.url, self.get_data())
headers = {
'Authorization': 'token {}'.format(self.api_key)
}
response = requests.get(service_url, headers=headers)
self.report(response.json())
else:
self.error('Unknown Patrowl service')
except Exception as e:
self.unexpectedError(e) | python | def run(self):
"""Run the analyzer."""
try:
if self.service == 'getreport':
service_url = '{}/assets/api/v1/details/{}'.format(
self.url, self.get_data())
headers = {
'Authorization': 'token {}'.format(self.api_key)
}
response = requests.get(service_url, headers=headers)
self.report(response.json())
else:
self.error('Unknown Patrowl service')
except Exception as e:
self.unexpectedError(e) | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"service",
"==",
"'getreport'",
":",
"service_url",
"=",
"'{}/assets/api/v1/details/{}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"self",
".",
"get_data",
"(",
")",
")",
"headers",
... | Run the analyzer. | [
"Run",
"the",
"analyzer",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Patrowl/patrowl.py#L55-L73 | train | 225,737 |
TheHive-Project/Cortex-Analyzers | analyzers/BackscatterIO/backscatter-io.py | BackscatterAnalyzer.run | def run(self):
"""Run the process to get observation data from Backscatter.io."""
kwargs = {'query': self.get_data()}
if self.data_type == "ip":
kwargs.update({'query_type': 'ip'})
elif self.data_type == "network":
kwargs.update({'query_type': 'network'})
elif self.data_type == 'autonomous-system':
kwargs.update({'query_type': 'asn'})
elif self.data_type == 'port':
kwargs.update({'query_type': 'port'})
else:
self.notSupported()
return False
if self.service == 'observations':
response = self.bs.get_observations(**kwargs)
self.report(response)
elif self.service == 'enrichment':
response = self.bs.enrich(**kwargs)
self.report(response)
else:
self.report({'error': 'Invalid service defined.'}) | python | def run(self):
"""Run the process to get observation data from Backscatter.io."""
kwargs = {'query': self.get_data()}
if self.data_type == "ip":
kwargs.update({'query_type': 'ip'})
elif self.data_type == "network":
kwargs.update({'query_type': 'network'})
elif self.data_type == 'autonomous-system':
kwargs.update({'query_type': 'asn'})
elif self.data_type == 'port':
kwargs.update({'query_type': 'port'})
else:
self.notSupported()
return False
if self.service == 'observations':
response = self.bs.get_observations(**kwargs)
self.report(response)
elif self.service == 'enrichment':
response = self.bs.enrich(**kwargs)
self.report(response)
else:
self.report({'error': 'Invalid service defined.'}) | [
"def",
"run",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'query'",
":",
"self",
".",
"get_data",
"(",
")",
"}",
"if",
"self",
".",
"data_type",
"==",
"\"ip\"",
":",
"kwargs",
".",
"update",
"(",
"{",
"'query_type'",
":",
"'ip'",
"}",
")",
"elif",
... | Run the process to get observation data from Backscatter.io. | [
"Run",
"the",
"process",
"to",
"get",
"observation",
"data",
"from",
"Backscatter",
".",
"io",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/BackscatterIO/backscatter-io.py#L28-L50 | train | 225,738 |
TheHive-Project/Cortex-Analyzers | analyzers/BackscatterIO/backscatter-io.py | BackscatterAnalyzer.summary | def summary(self, raw):
"""Use the Backscatter.io summary data to create a view."""
taxonomies = list()
level = 'info'
namespace = 'Backscatter.io'
if self.service == 'observations':
summary = raw.get('results', dict()).get('summary', dict())
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Observations', summary.get('observations_count', 0)),
self.build_taxonomy(level, namespace, 'IP Addresses', summary.get('ip_address_count', 0)),
self.build_taxonomy(level, namespace, 'Networks', summary.get('network_count', 0)),
self.build_taxonomy(level, namespace, 'AS', summary.get('autonomous_system_count', 0)),
self.build_taxonomy(level, namespace, 'Ports', summary.get('port_count', 0)),
self.build_taxonomy(level, namespace, 'Protocols', summary.get('protocol_count', 0))
]
elif self.service == 'enrichment':
summary = raw.get('results', dict())
if self.data_type == 'ip':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network', summary.get('network')),
self.build_taxonomy(level, namespace, 'Network Broadcast', summary.get('network_broadcast')),
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size')),
self.build_taxonomy(level, namespace, 'Country', summary.get('country_name')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name')),
]
elif self.data_type == 'network':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size'))
]
elif self.data_type == 'autonomous-system':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Prefix Count', summary.get('prefix_count')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name'))
]
elif self.data_type == 'port':
for result in raw.get('results', list()):
display = "%s (%s)" % (result.get('service'), result.get('protocol'))
taxonomies.append(self.build_taxonomy(level, namespace, 'Service', display))
else:
pass
else:
pass
return {"taxonomies": taxonomies} | python | def summary(self, raw):
"""Use the Backscatter.io summary data to create a view."""
taxonomies = list()
level = 'info'
namespace = 'Backscatter.io'
if self.service == 'observations':
summary = raw.get('results', dict()).get('summary', dict())
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Observations', summary.get('observations_count', 0)),
self.build_taxonomy(level, namespace, 'IP Addresses', summary.get('ip_address_count', 0)),
self.build_taxonomy(level, namespace, 'Networks', summary.get('network_count', 0)),
self.build_taxonomy(level, namespace, 'AS', summary.get('autonomous_system_count', 0)),
self.build_taxonomy(level, namespace, 'Ports', summary.get('port_count', 0)),
self.build_taxonomy(level, namespace, 'Protocols', summary.get('protocol_count', 0))
]
elif self.service == 'enrichment':
summary = raw.get('results', dict())
if self.data_type == 'ip':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network', summary.get('network')),
self.build_taxonomy(level, namespace, 'Network Broadcast', summary.get('network_broadcast')),
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size')),
self.build_taxonomy(level, namespace, 'Country', summary.get('country_name')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name')),
]
elif self.data_type == 'network':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size'))
]
elif self.data_type == 'autonomous-system':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Prefix Count', summary.get('prefix_count')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name'))
]
elif self.data_type == 'port':
for result in raw.get('results', list()):
display = "%s (%s)" % (result.get('service'), result.get('protocol'))
taxonomies.append(self.build_taxonomy(level, namespace, 'Service', display))
else:
pass
else:
pass
return {"taxonomies": taxonomies} | [
"def",
"summary",
"(",
"self",
",",
"raw",
")",
":",
"taxonomies",
"=",
"list",
"(",
")",
"level",
"=",
"'info'",
"namespace",
"=",
"'Backscatter.io'",
"if",
"self",
".",
"service",
"==",
"'observations'",
":",
"summary",
"=",
"raw",
".",
"get",
"(",
"... | Use the Backscatter.io summary data to create a view. | [
"Use",
"the",
"Backscatter",
".",
"io",
"summary",
"data",
"to",
"create",
"a",
"view",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/BackscatterIO/backscatter-io.py#L52-L97 | train | 225,739 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/maxminddb/decoder.py | Decoder.decode | def decode(self, offset):
"""Decode a section of the data section starting at offset
Arguments:
offset -- the location of the data structure to decode
"""
new_offset = offset + 1
(ctrl_byte,) = struct.unpack(b'!B', self._buffer[offset:new_offset])
type_num = ctrl_byte >> 5
# Extended type
if not type_num:
(type_num, new_offset) = self._read_extended(new_offset)
(size, new_offset) = self._size_from_ctrl_byte(
ctrl_byte, new_offset, type_num)
return self._type_decoder[type_num](self, size, new_offset) | python | def decode(self, offset):
"""Decode a section of the data section starting at offset
Arguments:
offset -- the location of the data structure to decode
"""
new_offset = offset + 1
(ctrl_byte,) = struct.unpack(b'!B', self._buffer[offset:new_offset])
type_num = ctrl_byte >> 5
# Extended type
if not type_num:
(type_num, new_offset) = self._read_extended(new_offset)
(size, new_offset) = self._size_from_ctrl_byte(
ctrl_byte, new_offset, type_num)
return self._type_decoder[type_num](self, size, new_offset) | [
"def",
"decode",
"(",
"self",
",",
"offset",
")",
":",
"new_offset",
"=",
"offset",
"+",
"1",
"(",
"ctrl_byte",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"b'!B'",
",",
"self",
".",
"_buffer",
"[",
"offset",
":",
"new_offset",
"]",
")",
"type_num",... | Decode a section of the data section starting at offset
Arguments:
offset -- the location of the data structure to decode | [
"Decode",
"a",
"section",
"of",
"the",
"data",
"section",
"starting",
"at",
"offset"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/maxminddb/decoder.py#L116-L131 | train | 225,740 |
TheHive-Project/Cortex-Analyzers | analyzers/VMRay/vmrayclient.py | VMRayClient.get_sample | def get_sample(self, samplehash):
"""
Downloads information about a sample using a given hash.
:param samplehash: hash to search for. Has to be either md5, sha1 or sha256
:type samplehash: str
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/'
if len(samplehash) == 32: # MD5
apiurl += 'md5/'
elif len(samplehash) == 40: # SHA1
apiurl += 'sha1/'
elif len(samplehash) == 64: # SHA256
apiurl += 'sha256/'
else:
raise UnknownHashTypeError('Sample hash has an unknown length.')
res = self.session.get(self.url + apiurl + samplehash)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text)) | python | def get_sample(self, samplehash):
"""
Downloads information about a sample using a given hash.
:param samplehash: hash to search for. Has to be either md5, sha1 or sha256
:type samplehash: str
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/'
if len(samplehash) == 32: # MD5
apiurl += 'md5/'
elif len(samplehash) == 40: # SHA1
apiurl += 'sha1/'
elif len(samplehash) == 64: # SHA256
apiurl += 'sha256/'
else:
raise UnknownHashTypeError('Sample hash has an unknown length.')
res = self.session.get(self.url + apiurl + samplehash)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text)) | [
"def",
"get_sample",
"(",
"self",
",",
"samplehash",
")",
":",
"apiurl",
"=",
"'/rest/sample/'",
"if",
"len",
"(",
"samplehash",
")",
"==",
"32",
":",
"# MD5",
"apiurl",
"+=",
"'md5/'",
"elif",
"len",
"(",
"samplehash",
")",
"==",
"40",
":",
"# SHA1",
... | Downloads information about a sample using a given hash.
:param samplehash: hash to search for. Has to be either md5, sha1 or sha256
:type samplehash: str
:returns: Dictionary of results
:rtype: dict | [
"Downloads",
"information",
"about",
"a",
"sample",
"using",
"a",
"given",
"hash",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VMRay/vmrayclient.py#L69-L93 | train | 225,741 |
TheHive-Project/Cortex-Analyzers | analyzers/VMRay/vmrayclient.py | VMRayClient.submit_sample | def submit_sample(self, filepath, filename, tags=['TheHive']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/submit?sample_file'
params = {'sample_filename_b64enc': base64.b64encode(filename.encode('utf-8')),
'reanalyze': self.reanalyze}
if tags:
params['tags'] = ','.join(tags)
if os.path.isfile(filepath):
res = self.session.post(url=self.url + apiurl,
files=[('sample_file', open(filepath, mode='rb'))],
params=params)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text))
else:
raise SampleFileNotFoundError('Given sample file was not found.') | python | def submit_sample(self, filepath, filename, tags=['TheHive']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/submit?sample_file'
params = {'sample_filename_b64enc': base64.b64encode(filename.encode('utf-8')),
'reanalyze': self.reanalyze}
if tags:
params['tags'] = ','.join(tags)
if os.path.isfile(filepath):
res = self.session.post(url=self.url + apiurl,
files=[('sample_file', open(filepath, mode='rb'))],
params=params)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text))
else:
raise SampleFileNotFoundError('Given sample file was not found.') | [
"def",
"submit_sample",
"(",
"self",
",",
"filepath",
",",
"filename",
",",
"tags",
"=",
"[",
"'TheHive'",
"]",
")",
":",
"apiurl",
"=",
"'/rest/sample/submit?sample_file'",
"params",
"=",
"{",
"'sample_filename_b64enc'",
":",
"base64",
".",
"b64encode",
"(",
... | Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict | [
"Uploads",
"a",
"new",
"sample",
"to",
"VMRay",
"api",
".",
"Filename",
"gets",
"sent",
"base64",
"encoded",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VMRay/vmrayclient.py#L95-L124 | train | 225,742 |
TheHive-Project/Cortex-Analyzers | analyzers/FileInfo/submodules/submodule_manalyze.py | ManalyzeSubmodule.build_results | def build_results(self, results):
"""Properly format the results"""
self.add_result_subsection(
'Exploit mitigation techniques',
{
'level': results.get('Plugins', {}).get('mitigation', {}).get('level', None),
'summary': results.get('Plugins', {}).get('mitigation', {}).get('summary', None),
'content': results.get('Plugins', {}).get('mitigation', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious strings',
{
'level': results.get('Plugins', {}).get('strings', {}).get('level', None),
'summary': results.get('Plugins', {}).get('strings', {}).get('summary', None),
'content': results.get('Plugins', {}).get('strings', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious imports',
{
'level': results.get('Plugins', {}).get('imports', {}).get('level', None),
'summary': results.get('Plugins', {}).get('imports', {}).get('summary', None),
'content': results.get('Plugins', {}).get('imports', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Packer',
{
'level': results.get('Plugins', {}).get('packer', {}).get('level', None),
'summary': results.get('Plugins', {}).get('packer', {}).get('summary', None),
'content': results.get('Plugins', {}).get('packer', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Clamav',
{
'level': results.get('Plugins', {}).get('clamav', {}).get('level', None),
'summary': results.get('Plugins', {}).get('clamav', {}).get('summary', None),
'content': results.get('Plugins', {}).get('clamav', {}).get('plugin_output', None)
}
)
self.add_result_subsection('Manalyze raw output', json.dumps(results, indent=4)) | python | def build_results(self, results):
"""Properly format the results"""
self.add_result_subsection(
'Exploit mitigation techniques',
{
'level': results.get('Plugins', {}).get('mitigation', {}).get('level', None),
'summary': results.get('Plugins', {}).get('mitigation', {}).get('summary', None),
'content': results.get('Plugins', {}).get('mitigation', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious strings',
{
'level': results.get('Plugins', {}).get('strings', {}).get('level', None),
'summary': results.get('Plugins', {}).get('strings', {}).get('summary', None),
'content': results.get('Plugins', {}).get('strings', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious imports',
{
'level': results.get('Plugins', {}).get('imports', {}).get('level', None),
'summary': results.get('Plugins', {}).get('imports', {}).get('summary', None),
'content': results.get('Plugins', {}).get('imports', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Packer',
{
'level': results.get('Plugins', {}).get('packer', {}).get('level', None),
'summary': results.get('Plugins', {}).get('packer', {}).get('summary', None),
'content': results.get('Plugins', {}).get('packer', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Clamav',
{
'level': results.get('Plugins', {}).get('clamav', {}).get('level', None),
'summary': results.get('Plugins', {}).get('clamav', {}).get('summary', None),
'content': results.get('Plugins', {}).get('clamav', {}).get('plugin_output', None)
}
)
self.add_result_subsection('Manalyze raw output', json.dumps(results, indent=4)) | [
"def",
"build_results",
"(",
"self",
",",
"results",
")",
":",
"self",
".",
"add_result_subsection",
"(",
"'Exploit mitigation techniques'",
",",
"{",
"'level'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'mitigation'... | Properly format the results | [
"Properly",
"format",
"the",
"results"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/FileInfo/submodules/submodule_manalyze.py#L65-L107 | train | 225,743 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | v4_int_to_packed | def v4_int_to_packed(address):
"""The binary representation of this address.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The binary representation of this address.
Raises:
ValueError: If the integer is too large to be an IPv4 IP
address.
"""
if address > _BaseV4._ALL_ONES:
raise ValueError('Address too large for IPv4')
return Bytes(struct.pack('!I', address)) | python | def v4_int_to_packed(address):
"""The binary representation of this address.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The binary representation of this address.
Raises:
ValueError: If the integer is too large to be an IPv4 IP
address.
"""
if address > _BaseV4._ALL_ONES:
raise ValueError('Address too large for IPv4')
return Bytes(struct.pack('!I', address)) | [
"def",
"v4_int_to_packed",
"(",
"address",
")",
":",
"if",
"address",
">",
"_BaseV4",
".",
"_ALL_ONES",
":",
"raise",
"ValueError",
"(",
"'Address too large for IPv4'",
")",
"return",
"Bytes",
"(",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"address",
")",
")"... | The binary representation of this address.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The binary representation of this address.
Raises:
ValueError: If the integer is too large to be an IPv4 IP
address. | [
"The",
"binary",
"representation",
"of",
"this",
"address",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L122-L137 | train | 225,744 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _get_prefix_length | def _get_prefix_length(number1, number2, bits):
"""Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two numbers.
"""
for i in range(bits):
if number1 >> i == number2 >> i:
return bits - i
return 0 | python | def _get_prefix_length(number1, number2, bits):
"""Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two numbers.
"""
for i in range(bits):
if number1 >> i == number2 >> i:
return bits - i
return 0 | [
"def",
"_get_prefix_length",
"(",
"number1",
",",
"number2",
",",
"bits",
")",
":",
"for",
"i",
"in",
"range",
"(",
"bits",
")",
":",
"if",
"number1",
">>",
"i",
"==",
"number2",
">>",
"i",
":",
"return",
"bits",
"-",
"i",
"return",
"0"
] | Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two numbers. | [
"Get",
"the",
"number",
"of",
"leading",
"bits",
"that",
"are",
"same",
"for",
"two",
"numbers",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L170-L185 | train | 225,745 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseNet._prefix_from_ip_int | def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from a bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format.
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask.
"""
prefixlen = self._max_prefixlen
while prefixlen:
if ip_int & 1:
break
ip_int >>= 1
prefixlen -= 1
if ip_int == (1 << prefixlen) - 1:
return prefixlen
else:
raise NetmaskValueError('Bit pattern does not match /1*0*/') | python | def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from a bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format.
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask.
"""
prefixlen = self._max_prefixlen
while prefixlen:
if ip_int & 1:
break
ip_int >>= 1
prefixlen -= 1
if ip_int == (1 << prefixlen) - 1:
return prefixlen
else:
raise NetmaskValueError('Bit pattern does not match /1*0*/') | [
"def",
"_prefix_from_ip_int",
"(",
"self",
",",
"ip_int",
")",
":",
"prefixlen",
"=",
"self",
".",
"_max_prefixlen",
"while",
"prefixlen",
":",
"if",
"ip_int",
"&",
"1",
":",
"break",
"ip_int",
">>=",
"1",
"prefixlen",
"-=",
"1",
"if",
"ip_int",
"==",
"(... | Return prefix length from a bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format.
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask. | [
"Return",
"prefix",
"length",
"from",
"a",
"bitwise",
"netmask",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L854-L877 | train | 225,746 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseNet._prefix_from_prefix_string | def _prefix_from_prefix_string(self, prefixlen_str):
"""Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range.
"""
try:
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
raise ValueError
prefixlen = int(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
raise ValueError
except ValueError:
raise NetmaskValueError('%s is not a valid prefix length' %
prefixlen_str)
return prefixlen | python | def _prefix_from_prefix_string(self, prefixlen_str):
"""Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range.
"""
try:
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
raise ValueError
prefixlen = int(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
raise ValueError
except ValueError:
raise NetmaskValueError('%s is not a valid prefix length' %
prefixlen_str)
return prefixlen | [
"def",
"_prefix_from_prefix_string",
"(",
"self",
",",
"prefixlen_str",
")",
":",
"try",
":",
"if",
"not",
"_BaseV4",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"prefixlen_str",
")",
":",
"raise",
"ValueError",
"prefixlen",
"=",
"int",
"(",
"prefixlen_str",... | Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range. | [
"Turn",
"a",
"prefix",
"length",
"string",
"into",
"an",
"integer",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L879-L901 | train | 225,747 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseNet.masked | def masked(self):
"""Return the network object with the host bits masked out."""
return IPNetwork('%s/%d' % (self.network, self._prefixlen),
version=self._version) | python | def masked(self):
"""Return the network object with the host bits masked out."""
return IPNetwork('%s/%d' % (self.network, self._prefixlen),
version=self._version) | [
"def",
"masked",
"(",
"self",
")",
":",
"return",
"IPNetwork",
"(",
"'%s/%d'",
"%",
"(",
"self",
".",
"network",
",",
"self",
".",
"_prefixlen",
")",
",",
"version",
"=",
"self",
".",
"_version",
")"
] | Return the network object with the host bits masked out. | [
"Return",
"the",
"network",
"object",
"with",
"the",
"host",
"bits",
"masked",
"out",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L999-L1002 | train | 225,748 |
TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseV6._string_from_ip_int | def _string_from_ip_int(self, ip_int=None):
"""Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones.
"""
if not ip_int and ip_int != 0:
ip_int = int(self._ip)
if ip_int > self._ALL_ONES:
raise ValueError('IPv6 address is too large')
hex_str = '%032x' % ip_int
hextets = []
for x in range(0, 32, 4):
hextets.append('%x' % int(hex_str[x:x+4], 16))
hextets = self._compress_hextets(hextets)
return ':'.join(hextets) | python | def _string_from_ip_int(self, ip_int=None):
"""Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones.
"""
if not ip_int and ip_int != 0:
ip_int = int(self._ip)
if ip_int > self._ALL_ONES:
raise ValueError('IPv6 address is too large')
hex_str = '%032x' % ip_int
hextets = []
for x in range(0, 32, 4):
hextets.append('%x' % int(hex_str[x:x+4], 16))
hextets = self._compress_hextets(hextets)
return ':'.join(hextets) | [
"def",
"_string_from_ip_int",
"(",
"self",
",",
"ip_int",
"=",
"None",
")",
":",
"if",
"not",
"ip_int",
"and",
"ip_int",
"!=",
"0",
":",
"ip_int",
"=",
"int",
"(",
"self",
".",
"_ip",
")",
"if",
"ip_int",
">",
"self",
".",
"_ALL_ONES",
":",
"raise",
... | Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones. | [
"Turns",
"a",
"128",
"-",
"bit",
"integer",
"into",
"hexadecimal",
"notation",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L1532-L1557 | train | 225,749 |
TheHive-Project/Cortex-Analyzers | analyzers/Malwares/malwares_api.py | Api.scan_file | def scan_file(self, this_file, this_filename):
""" Submit a file to be scanned by Malwares
:param this_file: File to be scanned (200MB file size limit)
:param this_filename: Filename for scanned file
:return: JSON response that contains scan_id and permalink.
"""
params = {
'api_key': self.api_key,
'filename': this_filename
}
try:
files = {'file': (this_file.name, open(this_file.name, 'rb'), 'application/octet-stream')}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/upload', files=files, data=params)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def scan_file(self, this_file, this_filename):
""" Submit a file to be scanned by Malwares
:param this_file: File to be scanned (200MB file size limit)
:param this_filename: Filename for scanned file
:return: JSON response that contains scan_id and permalink.
"""
params = {
'api_key': self.api_key,
'filename': this_filename
}
try:
files = {'file': (this_file.name, open(this_file.name, 'rb'), 'application/octet-stream')}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/upload', files=files, data=params)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"scan_file",
"(",
"self",
",",
"this_file",
",",
"this_filename",
")",
":",
"params",
"=",
"{",
"'api_key'",
":",
"self",
".",
"api_key",
",",
"'filename'",
":",
"this_filename",
"}",
"try",
":",
"files",
"=",
"{",
"'file'",
":",
"(",
"this_file",... | Submit a file to be scanned by Malwares
:param this_file: File to be scanned (200MB file size limit)
:param this_filename: Filename for scanned file
:return: JSON response that contains scan_id and permalink. | [
"Submit",
"a",
"file",
"to",
"be",
"scanned",
"by",
"Malwares"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Malwares/malwares_api.py#L17-L38 | train | 225,750 |
TheHive-Project/Cortex-Analyzers | analyzers/GoogleSafebrowsing/safebrowsing.py | SafebrowsingClient.__prepare_body | def __prepare_body(self, search_value, search_type='url'):
"""
Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type: str
:returns: http body as dict
:rtype: dict
"""
body = {
'client': {
'clientId': self.client_id,
'clientVersion': self.client_version
}
}
if search_type == 'url':
data = {
'threatTypes': [
'MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE', 'POTENTIALLY_HARMFUL_APPLICATION'
],
'platformTypes': ['ANY_PLATFORM', 'ALL_PLATFORMS', 'WINDOWS', 'LINUX', 'OSX', 'ANDROID', 'IOS'],
'threatEntryTypes': ['URL']
}
elif search_type == 'ip':
data = {
'threatTypes': ['MALWARE'],
'platformTypes': ['WINDOWS', 'LINUX', 'OSX'],
'threatEntryTypes': ['IP_RANGE']
}
else:
raise SearchTypeNotSupportedError('Currently supported search types are \'url\' and \'ip\'.')
# TODO: Only found threatEntry 'url' in the docs. What to use for ip_range?
data['threatEntries'] = [{'url': search_value}]
body['threatInfo'] = data
return body | python | def __prepare_body(self, search_value, search_type='url'):
"""
Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type: str
:returns: http body as dict
:rtype: dict
"""
body = {
'client': {
'clientId': self.client_id,
'clientVersion': self.client_version
}
}
if search_type == 'url':
data = {
'threatTypes': [
'MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE', 'POTENTIALLY_HARMFUL_APPLICATION'
],
'platformTypes': ['ANY_PLATFORM', 'ALL_PLATFORMS', 'WINDOWS', 'LINUX', 'OSX', 'ANDROID', 'IOS'],
'threatEntryTypes': ['URL']
}
elif search_type == 'ip':
data = {
'threatTypes': ['MALWARE'],
'platformTypes': ['WINDOWS', 'LINUX', 'OSX'],
'threatEntryTypes': ['IP_RANGE']
}
else:
raise SearchTypeNotSupportedError('Currently supported search types are \'url\' and \'ip\'.')
# TODO: Only found threatEntry 'url' in the docs. What to use for ip_range?
data['threatEntries'] = [{'url': search_value}]
body['threatInfo'] = data
return body | [
"def",
"__prepare_body",
"(",
"self",
",",
"search_value",
",",
"search_type",
"=",
"'url'",
")",
":",
"body",
"=",
"{",
"'client'",
":",
"{",
"'clientId'",
":",
"self",
".",
"client_id",
",",
"'clientVersion'",
":",
"self",
".",
"client_version",
"}",
"}"... | Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type: str
:returns: http body as dict
:rtype: dict | [
"Prepares",
"the",
"http",
"body",
"for",
"querying",
"safebrowsing",
"api",
".",
"Maybe",
"the",
"list",
"need",
"to",
"get",
"adjusted",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/GoogleSafebrowsing/safebrowsing.py#L26-L63 | train | 225,751 |
TheHive-Project/Cortex-Analyzers | analyzers/Robtex/robtex.py | RobtexAnalyzer.query_rpdns | def query_rpdns(self):
"""
Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list
"""
results = requests.get('https://freeapi.robtex.com/pdns/reverse/{}'.format(self.get_data())).text.split('\r\n')
jsonresults = []
for idx, r in enumerate(results):
if len(r) > 0:
jsonresults.append(json.loads(r))
return jsonresults | python | def query_rpdns(self):
"""
Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list
"""
results = requests.get('https://freeapi.robtex.com/pdns/reverse/{}'.format(self.get_data())).text.split('\r\n')
jsonresults = []
for idx, r in enumerate(results):
if len(r) > 0:
jsonresults.append(json.loads(r))
return jsonresults | [
"def",
"query_rpdns",
"(",
"self",
")",
":",
"results",
"=",
"requests",
".",
"get",
"(",
"'https://freeapi.robtex.com/pdns/reverse/{}'",
".",
"format",
"(",
"self",
".",
"get_data",
"(",
")",
")",
")",
".",
"text",
".",
"split",
"(",
"'\\r\\n'",
")",
"jso... | Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list | [
"Queries",
"robtex",
"reverse",
"pdns",
"-",
"api",
"using",
"an",
"ip",
"as",
"parameter"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Robtex/robtex.py#L22-L34 | train | 225,752 |
TheHive-Project/Cortex-Analyzers | analyzers/FileInfo/submodules/submodule_rtfobj.py | RTFObjectSubmodule.module_summary | def module_summary(self):
"""Count the malicious and suspicious sections, check for CVE description"""
suspicious = 0
malicious = 0
count = 0
cve = False
taxonomies = []
for section in self.results:
if section['submodule_section_content']['class'] == 'malicious':
malicious += 1
elif section['submodule_section_content']['class'] == 'suspicious':
suspicious += 1
if 'CVE' in section['submodule_section_content']['clsid_description']:
cve = True
count += 1
if malicious > 0:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'MaliciousRTFObjects', malicious))
if suspicious > 0:
taxonomies.append(self.build_taxonomy('suspicious', 'FileInfo', 'SuspiciousRTFObjects', suspicious))
if cve:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'PossibleCVEExploit', 'True'))
taxonomies.append(self.build_taxonomy('info', 'FileInfo', 'RTFObjects', count))
self.summary['taxonomies'] = taxonomies
return self.summary | python | def module_summary(self):
"""Count the malicious and suspicious sections, check for CVE description"""
suspicious = 0
malicious = 0
count = 0
cve = False
taxonomies = []
for section in self.results:
if section['submodule_section_content']['class'] == 'malicious':
malicious += 1
elif section['submodule_section_content']['class'] == 'suspicious':
suspicious += 1
if 'CVE' in section['submodule_section_content']['clsid_description']:
cve = True
count += 1
if malicious > 0:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'MaliciousRTFObjects', malicious))
if suspicious > 0:
taxonomies.append(self.build_taxonomy('suspicious', 'FileInfo', 'SuspiciousRTFObjects', suspicious))
if cve:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'PossibleCVEExploit', 'True'))
taxonomies.append(self.build_taxonomy('info', 'FileInfo', 'RTFObjects', count))
self.summary['taxonomies'] = taxonomies
return self.summary | [
"def",
"module_summary",
"(",
"self",
")",
":",
"suspicious",
"=",
"0",
"malicious",
"=",
"0",
"count",
"=",
"0",
"cve",
"=",
"False",
"taxonomies",
"=",
"[",
"]",
"for",
"section",
"in",
"self",
".",
"results",
":",
"if",
"section",
"[",
"'submodule_s... | Count the malicious and suspicious sections, check for CVE description | [
"Count",
"the",
"malicious",
"and",
"suspicious",
"sections",
"check",
"for",
"CVE",
"description"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/FileInfo/submodules/submodule_rtfobj.py#L20-L50 | train | 225,753 |
TheHive-Project/Cortex-Analyzers | analyzers/TorProject/tor_project.py | TorProjectClient.search_tor_node | def search_tor_node(self, ip):
"""Lookup an IP address to check if it is a known tor exit node.
:param ip: The IP address to lookup
:type ip: str
:return: Data relative to the tor node. If `ip`is a tor exit node
it will contain a `node` key with the hash of the node and
a `last_status` key with the last update time of the node.
If `ip` is not a tor exit node, the function will return an
empty dictionary.
:rtype: dict
"""
data = {}
tmp = {}
present = datetime.utcnow().replace(tzinfo=pytz.utc)
for line in self._get_raw_data().splitlines():
params = line.split(' ')
if params[0] == 'ExitNode':
tmp['node'] = params[1]
elif params[0] == 'ExitAddress':
tmp['last_status'] = params[2] + 'T' + params[3] + '+0000'
last_status = parse(tmp['last_status'])
if (self.delta is None or
(present - last_status) < self.delta):
data[params[1]] = tmp
tmp = {}
else:
pass
return data.get(ip, {}) | python | def search_tor_node(self, ip):
"""Lookup an IP address to check if it is a known tor exit node.
:param ip: The IP address to lookup
:type ip: str
:return: Data relative to the tor node. If `ip`is a tor exit node
it will contain a `node` key with the hash of the node and
a `last_status` key with the last update time of the node.
If `ip` is not a tor exit node, the function will return an
empty dictionary.
:rtype: dict
"""
data = {}
tmp = {}
present = datetime.utcnow().replace(tzinfo=pytz.utc)
for line in self._get_raw_data().splitlines():
params = line.split(' ')
if params[0] == 'ExitNode':
tmp['node'] = params[1]
elif params[0] == 'ExitAddress':
tmp['last_status'] = params[2] + 'T' + params[3] + '+0000'
last_status = parse(tmp['last_status'])
if (self.delta is None or
(present - last_status) < self.delta):
data[params[1]] = tmp
tmp = {}
else:
pass
return data.get(ip, {}) | [
"def",
"search_tor_node",
"(",
"self",
",",
"ip",
")",
":",
"data",
"=",
"{",
"}",
"tmp",
"=",
"{",
"}",
"present",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"for",
"line",
"in",
"self"... | Lookup an IP address to check if it is a known tor exit node.
:param ip: The IP address to lookup
:type ip: str
:return: Data relative to the tor node. If `ip`is a tor exit node
it will contain a `node` key with the hash of the node and
a `last_status` key with the last update time of the node.
If `ip` is not a tor exit node, the function will return an
empty dictionary.
:rtype: dict | [
"Lookup",
"an",
"IP",
"address",
"to",
"check",
"if",
"it",
"is",
"a",
"known",
"tor",
"exit",
"node",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/TorProject/tor_project.py#L52-L80 | train | 225,754 |
TheHive-Project/Cortex-Analyzers | analyzers/Censys/censys_analyzer.py | CensysAnalyzer.search_hosts | def search_hosts(self, ip):
"""
Searches for a host using its ipv4 address
:param ip: ipv4 address as string
:type ip: str
:return: dict
"""
c = CensysIPv4(api_id=self.__uid, api_secret=self.__api_key)
return c.view(ip) | python | def search_hosts(self, ip):
"""
Searches for a host using its ipv4 address
:param ip: ipv4 address as string
:type ip: str
:return: dict
"""
c = CensysIPv4(api_id=self.__uid, api_secret=self.__api_key)
return c.view(ip) | [
"def",
"search_hosts",
"(",
"self",
",",
"ip",
")",
":",
"c",
"=",
"CensysIPv4",
"(",
"api_id",
"=",
"self",
".",
"__uid",
",",
"api_secret",
"=",
"self",
".",
"__api_key",
")",
"return",
"c",
".",
"view",
"(",
"ip",
")"
] | Searches for a host using its ipv4 address
:param ip: ipv4 address as string
:type ip: str
:return: dict | [
"Searches",
"for",
"a",
"host",
"using",
"its",
"ipv4",
"address"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Censys/censys_analyzer.py#L24-L33 | train | 225,755 |
TheHive-Project/Cortex-Analyzers | analyzers/Censys/censys_analyzer.py | CensysAnalyzer.search_certificate | def search_certificate(self, hash):
"""
Searches for a specific certificate using its hash
:param hash: certificate hash
:type hash: str
:return: dict
"""
c = CensysCertificates(api_id=self.__uid, api_secret=self.__api_key)
return c.view(hash) | python | def search_certificate(self, hash):
"""
Searches for a specific certificate using its hash
:param hash: certificate hash
:type hash: str
:return: dict
"""
c = CensysCertificates(api_id=self.__uid, api_secret=self.__api_key)
return c.view(hash) | [
"def",
"search_certificate",
"(",
"self",
",",
"hash",
")",
":",
"c",
"=",
"CensysCertificates",
"(",
"api_id",
"=",
"self",
".",
"__uid",
",",
"api_secret",
"=",
"self",
".",
"__api_key",
")",
"return",
"c",
".",
"view",
"(",
"hash",
")"
] | Searches for a specific certificate using its hash
:param hash: certificate hash
:type hash: str
:return: dict | [
"Searches",
"for",
"a",
"specific",
"certificate",
"using",
"its",
"hash"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Censys/censys_analyzer.py#L35-L44 | train | 225,756 |
TheHive-Project/Cortex-Analyzers | analyzers/StopForumSpam/stopforumspam_client.py | StopforumspamClient.get_data | def get_data(self, datatype, data):
""" Look for an IP address or an email address in the spammer database.
:param datatype: Which type of data is to be looked up.
Allowed values are 'ip' or 'mail'.
:param data: The value to be looked up through the API.
:type datatype: str
:type data: str
:return: Data relative to the looked up artifact.
:rtype: dict
"""
result = {}
params = StopforumspamClient._set_payload(datatype, data)
response = self.client.get(
'https://api.stopforumspam.org/api',
params=params, proxies=self.proxies)
response.raise_for_status()
report = response.json()
if report['success']:
data = report[StopforumspamClient._type_conversion[datatype]]
result = self._data_conversion(data)
else:
pass
return result | python | def get_data(self, datatype, data):
""" Look for an IP address or an email address in the spammer database.
:param datatype: Which type of data is to be looked up.
Allowed values are 'ip' or 'mail'.
:param data: The value to be looked up through the API.
:type datatype: str
:type data: str
:return: Data relative to the looked up artifact.
:rtype: dict
"""
result = {}
params = StopforumspamClient._set_payload(datatype, data)
response = self.client.get(
'https://api.stopforumspam.org/api',
params=params, proxies=self.proxies)
response.raise_for_status()
report = response.json()
if report['success']:
data = report[StopforumspamClient._type_conversion[datatype]]
result = self._data_conversion(data)
else:
pass
return result | [
"def",
"get_data",
"(",
"self",
",",
"datatype",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"params",
"=",
"StopforumspamClient",
".",
"_set_payload",
"(",
"datatype",
",",
"data",
")",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'ht... | Look for an IP address or an email address in the spammer database.
:param datatype: Which type of data is to be looked up.
Allowed values are 'ip' or 'mail'.
:param data: The value to be looked up through the API.
:type datatype: str
:type data: str
:return: Data relative to the looked up artifact.
:rtype: dict | [
"Look",
"for",
"an",
"IP",
"address",
"or",
"an",
"email",
"address",
"in",
"the",
"spammer",
"database",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/StopForumSpam/stopforumspam_client.py#L47-L70 | train | 225,757 |
sdispater/orator | orator/orm/factory.py | Factory.construct | def construct(cls, faker, path_to_factories=None):
"""
Create a new factory container.
:param faker: A faker generator instance
:type faker: faker.Generator
:param path_to_factories: The path to factories
:type path_to_factories: str
:rtype: Factory
"""
factory = faker.__class__()
if path_to_factories is not None and os.path.isdir(path_to_factories):
for filename in os.listdir(path_to_factories):
if os.path.isfile(filename):
cls._resolve(path_to_factories, filename)
return factory | python | def construct(cls, faker, path_to_factories=None):
"""
Create a new factory container.
:param faker: A faker generator instance
:type faker: faker.Generator
:param path_to_factories: The path to factories
:type path_to_factories: str
:rtype: Factory
"""
factory = faker.__class__()
if path_to_factories is not None and os.path.isdir(path_to_factories):
for filename in os.listdir(path_to_factories):
if os.path.isfile(filename):
cls._resolve(path_to_factories, filename)
return factory | [
"def",
"construct",
"(",
"cls",
",",
"faker",
",",
"path_to_factories",
"=",
"None",
")",
":",
"factory",
"=",
"faker",
".",
"__class__",
"(",
")",
"if",
"path_to_factories",
"is",
"not",
"None",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path_to_fact... | Create a new factory container.
:param faker: A faker generator instance
:type faker: faker.Generator
:param path_to_factories: The path to factories
:type path_to_factories: str
:rtype: Factory | [
"Create",
"a",
"new",
"factory",
"container",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L25-L44 | train | 225,758 |
sdispater/orator | orator/orm/factory.py | Factory.define | def define(self, klass, name="default"):
"""
Define a class with a given set of attributes.
:param klass: The class
:type klass: class
:param name: The short name
:type name: str
"""
def decorate(func):
@wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
self.register(klass, func, name=name)
return wrapped
return decorate | python | def define(self, klass, name="default"):
"""
Define a class with a given set of attributes.
:param klass: The class
:type klass: class
:param name: The short name
:type name: str
"""
def decorate(func):
@wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
self.register(klass, func, name=name)
return wrapped
return decorate | [
"def",
"define",
"(",
"self",
",",
"klass",
",",
"name",
"=",
"\"default\"",
")",
":",
"def",
"decorate",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"fun... | Define a class with a given set of attributes.
:param klass: The class
:type klass: class
:param name: The short name
:type name: str | [
"Define",
"a",
"class",
"with",
"a",
"given",
"set",
"of",
"attributes",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L58-L78 | train | 225,759 |
sdispater/orator | orator/orm/factory.py | Factory.create_as | def create_as(self, klass, name, **attributes):
"""
Create an instance of the given model and type and persist it to the database.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param attributes: The instance attributes
:type attributes: dict
:return: mixed
"""
return self.of(klass, name).create(**attributes) | python | def create_as(self, klass, name, **attributes):
"""
Create an instance of the given model and type and persist it to the database.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param attributes: The instance attributes
:type attributes: dict
:return: mixed
"""
return self.of(klass, name).create(**attributes) | [
"def",
"create_as",
"(",
"self",
",",
"klass",
",",
"name",
",",
"*",
"*",
"attributes",
")",
":",
"return",
"self",
".",
"of",
"(",
"klass",
",",
"name",
")",
".",
"create",
"(",
"*",
"*",
"attributes",
")"
] | Create an instance of the given model and type and persist it to the database.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param attributes: The instance attributes
:type attributes: dict
:return: mixed | [
"Create",
"an",
"instance",
"of",
"the",
"given",
"model",
"and",
"type",
"and",
"persist",
"it",
"to",
"the",
"database",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L127-L142 | train | 225,760 |
sdispater/orator | orator/orm/factory.py | Factory.make_as | def make_as(self, klass, name, **attributes):
"""
Create an instance of the given model and type.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param attributes: The instance attributes
:type attributes: dict
:return: mixed
"""
return self.of(klass, name).make(**attributes) | python | def make_as(self, klass, name, **attributes):
"""
Create an instance of the given model and type.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param attributes: The instance attributes
:type attributes: dict
:return: mixed
"""
return self.of(klass, name).make(**attributes) | [
"def",
"make_as",
"(",
"self",
",",
"klass",
",",
"name",
",",
"*",
"*",
"attributes",
")",
":",
"return",
"self",
".",
"of",
"(",
"klass",
",",
"name",
")",
".",
"make",
"(",
"*",
"*",
"attributes",
")"
] | Create an instance of the given model and type.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param attributes: The instance attributes
:type attributes: dict
:return: mixed | [
"Create",
"an",
"instance",
"of",
"the",
"given",
"model",
"and",
"type",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L158-L173 | train | 225,761 |
sdispater/orator | orator/orm/factory.py | Factory.of | def of(self, klass, name="default"):
"""
Create a builder for the given model.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:return: orator.orm.factory_builder.FactoryBuilder
"""
return FactoryBuilder(
klass, name, self._definitions, self._faker, self._resolver
) | python | def of(self, klass, name="default"):
"""
Create a builder for the given model.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:return: orator.orm.factory_builder.FactoryBuilder
"""
return FactoryBuilder(
klass, name, self._definitions, self._faker, self._resolver
) | [
"def",
"of",
"(",
"self",
",",
"klass",
",",
"name",
"=",
"\"default\"",
")",
":",
"return",
"FactoryBuilder",
"(",
"klass",
",",
"name",
",",
"self",
".",
"_definitions",
",",
"self",
".",
"_faker",
",",
"self",
".",
"_resolver",
")"
] | Create a builder for the given model.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:return: orator.orm.factory_builder.FactoryBuilder | [
"Create",
"a",
"builder",
"for",
"the",
"given",
"model",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L213-L227 | train | 225,762 |
sdispater/orator | orator/orm/factory.py | Factory.build | def build(self, klass, name="default", amount=None):
"""
Makes a factory builder with a specified amount.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param amount: The number of models to create
:type amount: int
:return: mixed
"""
if amount is None:
if isinstance(name, int):
amount = name
name = "default"
else:
amount = 1
return self.of(klass, name).times(amount) | python | def build(self, klass, name="default", amount=None):
"""
Makes a factory builder with a specified amount.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param amount: The number of models to create
:type amount: int
:return: mixed
"""
if amount is None:
if isinstance(name, int):
amount = name
name = "default"
else:
amount = 1
return self.of(klass, name).times(amount) | [
"def",
"build",
"(",
"self",
",",
"klass",
",",
"name",
"=",
"\"default\"",
",",
"amount",
"=",
"None",
")",
":",
"if",
"amount",
"is",
"None",
":",
"if",
"isinstance",
"(",
"name",
",",
"int",
")",
":",
"amount",
"=",
"name",
"name",
"=",
"\"defau... | Makes a factory builder with a specified amount.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param amount: The number of models to create
:type amount: int
:return: mixed | [
"Makes",
"a",
"factory",
"builder",
"with",
"a",
"specified",
"amount",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory.py#L229-L251 | train | 225,763 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_renamed_diff | def _get_renamed_diff(self, blueprint, command, column, schema):
"""
Get a new column instance with the new column name.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param command: The command
:type command: Fluent
:param column: The column
:type column: orator.dbal.Column
:param schema: The schema
:type schema: orator.dbal.SchemaManager
:rtype: orator.dbal.TableDiff
"""
table_diff = self._get_table_diff(blueprint, schema)
return self._set_renamed_columns(table_diff, command, column) | python | def _get_renamed_diff(self, blueprint, command, column, schema):
"""
Get a new column instance with the new column name.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param command: The command
:type command: Fluent
:param column: The column
:type column: orator.dbal.Column
:param schema: The schema
:type schema: orator.dbal.SchemaManager
:rtype: orator.dbal.TableDiff
"""
table_diff = self._get_table_diff(blueprint, schema)
return self._set_renamed_columns(table_diff, command, column) | [
"def",
"_get_renamed_diff",
"(",
"self",
",",
"blueprint",
",",
"command",
",",
"column",
",",
"schema",
")",
":",
"table_diff",
"=",
"self",
".",
"_get_table_diff",
"(",
"blueprint",
",",
"schema",
")",
"return",
"self",
".",
"_set_renamed_columns",
"(",
"t... | Get a new column instance with the new column name.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param command: The command
:type command: Fluent
:param column: The column
:type column: orator.dbal.Column
:param schema: The schema
:type schema: orator.dbal.SchemaManager
:rtype: orator.dbal.TableDiff | [
"Get",
"a",
"new",
"column",
"instance",
"with",
"the",
"new",
"column",
"name",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L43-L63 | train | 225,764 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._set_renamed_columns | def _set_renamed_columns(self, table_diff, command, column):
"""
Set the renamed columns on the table diff.
:rtype: orator.dbal.TableDiff
"""
new_column = Column(command.to, column.get_type(), column.to_dict())
table_diff.renamed_columns = {command.from_: new_column}
return table_diff | python | def _set_renamed_columns(self, table_diff, command, column):
"""
Set the renamed columns on the table diff.
:rtype: orator.dbal.TableDiff
"""
new_column = Column(command.to, column.get_type(), column.to_dict())
table_diff.renamed_columns = {command.from_: new_column}
return table_diff | [
"def",
"_set_renamed_columns",
"(",
"self",
",",
"table_diff",
",",
"command",
",",
"column",
")",
":",
"new_column",
"=",
"Column",
"(",
"command",
".",
"to",
",",
"column",
".",
"get_type",
"(",
")",
",",
"column",
".",
"to_dict",
"(",
")",
")",
"tab... | Set the renamed columns on the table diff.
:rtype: orator.dbal.TableDiff | [
"Set",
"the",
"renamed",
"columns",
"on",
"the",
"table",
"diff",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L65-L75 | train | 225,765 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_command_by_name | def _get_command_by_name(self, blueprint, name):
"""
Get the primary key command it it exists.
"""
commands = self._get_commands_by_name(blueprint, name)
if len(commands):
return commands[0] | python | def _get_command_by_name(self, blueprint, name):
"""
Get the primary key command it it exists.
"""
commands = self._get_commands_by_name(blueprint, name)
if len(commands):
return commands[0] | [
"def",
"_get_command_by_name",
"(",
"self",
",",
"blueprint",
",",
"name",
")",
":",
"commands",
"=",
"self",
".",
"_get_commands_by_name",
"(",
"blueprint",
",",
"name",
")",
"if",
"len",
"(",
"commands",
")",
":",
"return",
"commands",
"[",
"0",
"]"
] | Get the primary key command it it exists. | [
"Get",
"the",
"primary",
"key",
"command",
"it",
"it",
"exists",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L143-L150 | train | 225,766 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_commands_by_name | def _get_commands_by_name(self, blueprint, name):
"""
Get all of the commands with a given name.
"""
return list(filter(lambda value: value.name == name, blueprint.get_commands())) | python | def _get_commands_by_name(self, blueprint, name):
"""
Get all of the commands with a given name.
"""
return list(filter(lambda value: value.name == name, blueprint.get_commands())) | [
"def",
"_get_commands_by_name",
"(",
"self",
",",
"blueprint",
",",
"name",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"value",
":",
"value",
".",
"name",
"==",
"name",
",",
"blueprint",
".",
"get_commands",
"(",
")",
")",
")"
] | Get all of the commands with a given name. | [
"Get",
"all",
"of",
"the",
"commands",
"with",
"a",
"given",
"name",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L152-L156 | train | 225,767 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar.prefix_list | def prefix_list(self, prefix, values):
"""
Add a prefix to a list of values.
"""
return list(map(lambda value: prefix + " " + value, values)) | python | def prefix_list(self, prefix, values):
"""
Add a prefix to a list of values.
"""
return list(map(lambda value: prefix + " " + value, values)) | [
"def",
"prefix_list",
"(",
"self",
",",
"prefix",
",",
"values",
")",
":",
"return",
"list",
"(",
"map",
"(",
"lambda",
"value",
":",
"prefix",
"+",
"\" \"",
"+",
"value",
",",
"values",
")",
")"
] | Add a prefix to a list of values. | [
"Add",
"a",
"prefix",
"to",
"a",
"list",
"of",
"values",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L169-L173 | train | 225,768 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_default_value | def _get_default_value(self, value):
"""
Format a value so that it can be used in "default" clauses.
"""
if isinstance(value, QueryExpression):
return value
if isinstance(value, bool):
return "'%s'" % int(value)
return "'%s'" % value | python | def _get_default_value(self, value):
"""
Format a value so that it can be used in "default" clauses.
"""
if isinstance(value, QueryExpression):
return value
if isinstance(value, bool):
return "'%s'" % int(value)
return "'%s'" % value | [
"def",
"_get_default_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"QueryExpression",
")",
":",
"return",
"value",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"\"'%s'\"",
"%",
"int",
"(",
"valu... | Format a value so that it can be used in "default" clauses. | [
"Format",
"a",
"value",
"so",
"that",
"it",
"can",
"be",
"used",
"in",
"default",
"clauses",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L187-L197 | train | 225,769 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_changed_diff | def _get_changed_diff(self, blueprint, schema):
"""
Get the table diffrence for the given changes.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param schema: The schema
:type schema: orator.dbal.SchemaManager
:rtype: orator.dbal.TableDiff
"""
table = schema.list_table_details(
self.get_table_prefix() + blueprint.get_table()
)
return Comparator().diff_table(
table, self._get_table_with_column_changes(blueprint, table)
) | python | def _get_changed_diff(self, blueprint, schema):
"""
Get the table diffrence for the given changes.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param schema: The schema
:type schema: orator.dbal.SchemaManager
:rtype: orator.dbal.TableDiff
"""
table = schema.list_table_details(
self.get_table_prefix() + blueprint.get_table()
)
return Comparator().diff_table(
table, self._get_table_with_column_changes(blueprint, table)
) | [
"def",
"_get_changed_diff",
"(",
"self",
",",
"blueprint",
",",
"schema",
")",
":",
"table",
"=",
"schema",
".",
"list_table_details",
"(",
"self",
".",
"get_table_prefix",
"(",
")",
"+",
"blueprint",
".",
"get_table",
"(",
")",
")",
"return",
"Comparator",
... | Get the table diffrence for the given changes.
:param blueprint: The blueprint
:type blueprint: Blueprint
:param schema: The schema
:type schema: orator.dbal.SchemaManager
:rtype: orator.dbal.TableDiff | [
"Get",
"the",
"table",
"diffrence",
"for",
"the",
"given",
"changes",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L237-L255 | train | 225,770 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_table_with_column_changes | def _get_table_with_column_changes(self, blueprint, table):
"""
Get a copy of the given table after making the column changes.
:param blueprint: The blueprint
:type blueprint: Blueprint
:type table: orator.dbal.table.Table
:rtype: orator.dbal.table.Table
"""
table = table.clone()
for fluent in blueprint.get_changed_columns():
column = self._get_column_for_change(table, fluent)
for key, value in fluent.get_attributes().items():
option = self._map_fluent_option(key)
if option is not None:
method = "set_%s" % option
if hasattr(column, method):
getattr(column, method)(self._map_fluent_value(option, value))
return table | python | def _get_table_with_column_changes(self, blueprint, table):
"""
Get a copy of the given table after making the column changes.
:param blueprint: The blueprint
:type blueprint: Blueprint
:type table: orator.dbal.table.Table
:rtype: orator.dbal.table.Table
"""
table = table.clone()
for fluent in blueprint.get_changed_columns():
column = self._get_column_for_change(table, fluent)
for key, value in fluent.get_attributes().items():
option = self._map_fluent_option(key)
if option is not None:
method = "set_%s" % option
if hasattr(column, method):
getattr(column, method)(self._map_fluent_value(option, value))
return table | [
"def",
"_get_table_with_column_changes",
"(",
"self",
",",
"blueprint",
",",
"table",
")",
":",
"table",
"=",
"table",
".",
"clone",
"(",
")",
"for",
"fluent",
"in",
"blueprint",
".",
"get_changed_columns",
"(",
")",
":",
"column",
"=",
"self",
".",
"_get_... | Get a copy of the given table after making the column changes.
:param blueprint: The blueprint
:type blueprint: Blueprint
:type table: orator.dbal.table.Table
:rtype: orator.dbal.table.Table | [
"Get",
"a",
"copy",
"of",
"the",
"given",
"table",
"after",
"making",
"the",
"column",
"changes",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L257-L282 | train | 225,771 |
sdispater/orator | orator/schema/grammars/grammar.py | SchemaGrammar._get_column_for_change | def _get_column_for_change(self, table, fluent):
"""
Get the column instance for a column change.
:type table: orator.dbal.table.Table
:rtype: orator.dbal.column.Column
"""
return table.change_column(
fluent.name, self._get_column_change_options(fluent)
).get_column(fluent.name) | python | def _get_column_for_change(self, table, fluent):
"""
Get the column instance for a column change.
:type table: orator.dbal.table.Table
:rtype: orator.dbal.column.Column
"""
return table.change_column(
fluent.name, self._get_column_change_options(fluent)
).get_column(fluent.name) | [
"def",
"_get_column_for_change",
"(",
"self",
",",
"table",
",",
"fluent",
")",
":",
"return",
"table",
".",
"change_column",
"(",
"fluent",
".",
"name",
",",
"self",
".",
"_get_column_change_options",
"(",
"fluent",
")",
")",
".",
"get_column",
"(",
"fluent... | Get the column instance for a column change.
:type table: orator.dbal.table.Table
:rtype: orator.dbal.column.Column | [
"Get",
"the",
"column",
"instance",
"for",
"a",
"column",
"change",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/grammars/grammar.py#L284-L294 | train | 225,772 |
sdispater/orator | orator/orm/relations/pivot.py | Pivot._get_delete_query | def _get_delete_query(self):
"""
Get the query builder for a delete operation on the pivot.
:rtype: orator.orm.Builder
"""
foreign = self.get_attribute(self.__foreign_key)
query = self.new_query().where(self.__foreign_key, foreign)
return query.where(self.__other_key, self.get_attribute(self.__other_key)) | python | def _get_delete_query(self):
"""
Get the query builder for a delete operation on the pivot.
:rtype: orator.orm.Builder
"""
foreign = self.get_attribute(self.__foreign_key)
query = self.new_query().where(self.__foreign_key, foreign)
return query.where(self.__other_key, self.get_attribute(self.__other_key)) | [
"def",
"_get_delete_query",
"(",
"self",
")",
":",
"foreign",
"=",
"self",
".",
"get_attribute",
"(",
"self",
".",
"__foreign_key",
")",
"query",
"=",
"self",
".",
"new_query",
"(",
")",
".",
"where",
"(",
"self",
".",
"__foreign_key",
",",
"foreign",
")... | Get the query builder for a delete operation on the pivot.
:rtype: orator.orm.Builder | [
"Get",
"the",
"query",
"builder",
"for",
"a",
"delete",
"operation",
"on",
"the",
"pivot",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/pivot.py#L63-L73 | train | 225,773 |
sdispater/orator | orator/orm/relations/pivot.py | Pivot.set_pivot_keys | def set_pivot_keys(self, foreign_key, other_key):
"""
Set the key names for the pivot model instance
"""
self.__foreign_key = foreign_key
self.__other_key = other_key
return self | python | def set_pivot_keys(self, foreign_key, other_key):
"""
Set the key names for the pivot model instance
"""
self.__foreign_key = foreign_key
self.__other_key = other_key
return self | [
"def",
"set_pivot_keys",
"(",
"self",
",",
"foreign_key",
",",
"other_key",
")",
":",
"self",
".",
"__foreign_key",
"=",
"foreign_key",
"self",
".",
"__other_key",
"=",
"other_key",
"return",
"self"
] | Set the key names for the pivot model instance | [
"Set",
"the",
"key",
"names",
"for",
"the",
"pivot",
"model",
"instance"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/pivot.py#L89-L96 | train | 225,774 |
sdispater/orator | orator/orm/factory_builder.py | FactoryBuilder.create | def create(self, **attributes):
"""
Create a collection of models and persist them to the database.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
results = self.make(**attributes)
if self._amount == 1:
if self._resolver:
results.set_connection_resolver(self._resolver)
results.save()
else:
if self._resolver:
results.each(lambda r: r.set_connection_resolver(self._resolver))
for result in results:
result.save()
return results | python | def create(self, **attributes):
"""
Create a collection of models and persist them to the database.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
results = self.make(**attributes)
if self._amount == 1:
if self._resolver:
results.set_connection_resolver(self._resolver)
results.save()
else:
if self._resolver:
results.each(lambda r: r.set_connection_resolver(self._resolver))
for result in results:
result.save()
return results | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"results",
"=",
"self",
".",
"make",
"(",
"*",
"*",
"attributes",
")",
"if",
"self",
".",
"_amount",
"==",
"1",
":",
"if",
"self",
".",
"_resolver",
":",
"results",
".",
"set_conn... | Create a collection of models and persist them to the database.
:param attributes: The models attributes
:type attributes: dict
:return: mixed | [
"Create",
"a",
"collection",
"of",
"models",
"and",
"persist",
"them",
"to",
"the",
"database",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory_builder.py#L41-L64 | train | 225,775 |
sdispater/orator | orator/orm/factory_builder.py | FactoryBuilder.make | def make(self, **attributes):
"""
Create a collection of models.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
if self._amount == 1:
return self._make_instance(**attributes)
else:
results = []
for _ in range(self._amount):
results.append(self._make_instance(**attributes))
return Collection(results) | python | def make(self, **attributes):
"""
Create a collection of models.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
if self._amount == 1:
return self._make_instance(**attributes)
else:
results = []
for _ in range(self._amount):
results.append(self._make_instance(**attributes))
return Collection(results) | [
"def",
"make",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"if",
"self",
".",
"_amount",
"==",
"1",
":",
"return",
"self",
".",
"_make_instance",
"(",
"*",
"*",
"attributes",
")",
"else",
":",
"results",
"=",
"[",
"]",
"for",
"_",
"in",
"... | Create a collection of models.
:param attributes: The models attributes
:type attributes: dict
:return: mixed | [
"Create",
"a",
"collection",
"of",
"models",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory_builder.py#L66-L83 | train | 225,776 |
sdispater/orator | orator/orm/factory_builder.py | FactoryBuilder._make_instance | def _make_instance(self, **attributes):
"""
Make an instance of the model with the given attributes.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
definition = self._definitions[self._klass][self._name](self._faker)
definition.update(attributes)
instance = self._klass()
instance.force_fill(**definition)
return instance | python | def _make_instance(self, **attributes):
"""
Make an instance of the model with the given attributes.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
definition = self._definitions[self._klass][self._name](self._faker)
definition.update(attributes)
instance = self._klass()
instance.force_fill(**definition)
return instance | [
"def",
"_make_instance",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"definition",
"=",
"self",
".",
"_definitions",
"[",
"self",
".",
"_klass",
"]",
"[",
"self",
".",
"_name",
"]",
"(",
"self",
".",
"_faker",
")",
"definition",
".",
"update",
... | Make an instance of the model with the given attributes.
:param attributes: The models attributes
:type attributes: dict
:return: mixed | [
"Make",
"an",
"instance",
"of",
"the",
"model",
"with",
"the",
"given",
"attributes",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/factory_builder.py#L85-L100 | train | 225,777 |
sdispater/orator | orator/connections/connection.py | run | def run(wrapped):
"""
Special decorator encapsulating query method.
"""
@wraps(wrapped)
def _run(self, query, bindings=None, *args, **kwargs):
self._reconnect_if_missing_connection()
start = time.time()
try:
result = wrapped(self, query, bindings, *args, **kwargs)
except Exception as e:
result = self._try_again_if_caused_by_lost_connection(
e, query, bindings, wrapped
)
t = self._get_elapsed_time(start)
self.log_query(query, bindings, t)
return result
return _run | python | def run(wrapped):
"""
Special decorator encapsulating query method.
"""
@wraps(wrapped)
def _run(self, query, bindings=None, *args, **kwargs):
self._reconnect_if_missing_connection()
start = time.time()
try:
result = wrapped(self, query, bindings, *args, **kwargs)
except Exception as e:
result = self._try_again_if_caused_by_lost_connection(
e, query, bindings, wrapped
)
t = self._get_elapsed_time(start)
self.log_query(query, bindings, t)
return result
return _run | [
"def",
"run",
"(",
"wrapped",
")",
":",
"@",
"wraps",
"(",
"wrapped",
")",
"def",
"_run",
"(",
"self",
",",
"query",
",",
"bindings",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_reconnect_if_missing_connection",
"... | Special decorator encapsulating query method. | [
"Special",
"decorator",
"encapsulating",
"query",
"method",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/connections/connection.py#L21-L43 | train | 225,778 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.where_pivot | def where_pivot(self, column, operator=None, value=None, boolean="and"):
"""
Set a where clause for a pivot table column.
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
:type operator: str
:param value: The value of the where clause
:type value: mixed
:param boolean: The boolean of the where clause
:type boolean: str
:return: self
:rtype: self
"""
self._pivot_wheres.append([column, operator, value, boolean])
return self._query.where(
"%s.%s" % (self._table, column), operator, value, boolean
) | python | def where_pivot(self, column, operator=None, value=None, boolean="and"):
"""
Set a where clause for a pivot table column.
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
:type operator: str
:param value: The value of the where clause
:type value: mixed
:param boolean: The boolean of the where clause
:type boolean: str
:return: self
:rtype: self
"""
self._pivot_wheres.append([column, operator, value, boolean])
return self._query.where(
"%s.%s" % (self._table, column), operator, value, boolean
) | [
"def",
"where_pivot",
"(",
"self",
",",
"column",
",",
"operator",
"=",
"None",
",",
"value",
"=",
"None",
",",
"boolean",
"=",
"\"and\"",
")",
":",
"self",
".",
"_pivot_wheres",
".",
"append",
"(",
"[",
"column",
",",
"operator",
",",
"value",
",",
... | Set a where clause for a pivot table column.
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
:type operator: str
:param value: The value of the where clause
:type value: mixed
:param boolean: The boolean of the where clause
:type boolean: str
:return: self
:rtype: self | [
"Set",
"a",
"where",
"clause",
"for",
"a",
"pivot",
"table",
"column",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L62-L85 | train | 225,779 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.or_where_pivot | def or_where_pivot(self, column, operator=None, value=None):
"""
Set an or where clause for a pivot table column.
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
:type operator: str
:param value: The value of the where clause
:type value: mixed
:return: self
:rtype: BelongsToMany
"""
return self.where_pivot(column, operator, value, "or") | python | def or_where_pivot(self, column, operator=None, value=None):
"""
Set an or where clause for a pivot table column.
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
:type operator: str
:param value: The value of the where clause
:type value: mixed
:return: self
:rtype: BelongsToMany
"""
return self.where_pivot(column, operator, value, "or") | [
"def",
"or_where_pivot",
"(",
"self",
",",
"column",
",",
"operator",
"=",
"None",
",",
"value",
"=",
"None",
")",
":",
"return",
"self",
".",
"where_pivot",
"(",
"column",
",",
"operator",
",",
"value",
",",
"\"or\"",
")"
] | Set an or where clause for a pivot table column.
:param column: The column of the where clause, can also be a QueryBuilder instance for sub where
:type column: str|Builder
:param operator: The operator of the where clause
:type operator: str
:param value: The value of the where clause
:type value: mixed
:return: self
:rtype: BelongsToMany | [
"Set",
"an",
"or",
"where",
"clause",
"for",
"a",
"pivot",
"table",
"column",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L87-L103 | train | 225,780 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.first | def first(self, columns=None):
"""
Execute the query and get the first result.
:type columns: list
"""
self._query.take(1)
results = self.get(columns)
if len(results) > 0:
return results.first()
return | python | def first(self, columns=None):
"""
Execute the query and get the first result.
:type columns: list
"""
self._query.take(1)
results = self.get(columns)
if len(results) > 0:
return results.first()
return | [
"def",
"first",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"self",
".",
"_query",
".",
"take",
"(",
"1",
")",
"results",
"=",
"self",
".",
"get",
"(",
"columns",
")",
"if",
"len",
"(",
"results",
")",
">",
"0",
":",
"return",
"results",
... | Execute the query and get the first result.
:type columns: list | [
"Execute",
"the",
"query",
"and",
"get",
"the",
"first",
"result",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L105-L118 | train | 225,781 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.first_or_fail | def first_or_fail(self, columns=None):
"""
Execute the query and get the first result or raise an exception.
:type columns: list
:raises: ModelNotFound
"""
model = self.first(columns)
if model is not None:
return model
raise ModelNotFound(self._parent.__class__) | python | def first_or_fail(self, columns=None):
"""
Execute the query and get the first result or raise an exception.
:type columns: list
:raises: ModelNotFound
"""
model = self.first(columns)
if model is not None:
return model
raise ModelNotFound(self._parent.__class__) | [
"def",
"first_or_fail",
"(",
"self",
",",
"columns",
"=",
"None",
")",
":",
"model",
"=",
"self",
".",
"first",
"(",
"columns",
")",
"if",
"model",
"is",
"not",
"None",
":",
"return",
"model",
"raise",
"ModelNotFound",
"(",
"self",
".",
"_parent",
".",... | Execute the query and get the first result or raise an exception.
:type columns: list
:raises: ModelNotFound | [
"Execute",
"the",
"query",
"and",
"get",
"the",
"first",
"result",
"or",
"raise",
"an",
"exception",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L120-L132 | train | 225,782 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany._hydrate_pivot_relation | def _hydrate_pivot_relation(self, models):
"""
Hydrate the pivot table relationship on the models.
:type models: list
"""
for model in models:
pivot = self.new_existing_pivot(self._clean_pivot_attributes(model))
model.set_relation("pivot", pivot) | python | def _hydrate_pivot_relation(self, models):
"""
Hydrate the pivot table relationship on the models.
:type models: list
"""
for model in models:
pivot = self.new_existing_pivot(self._clean_pivot_attributes(model))
model.set_relation("pivot", pivot) | [
"def",
"_hydrate_pivot_relation",
"(",
"self",
",",
"models",
")",
":",
"for",
"model",
"in",
"models",
":",
"pivot",
"=",
"self",
".",
"new_existing_pivot",
"(",
"self",
".",
"_clean_pivot_attributes",
"(",
"model",
")",
")",
"model",
".",
"set_relation",
"... | Hydrate the pivot table relationship on the models.
:type models: list | [
"Hydrate",
"the",
"pivot",
"table",
"relationship",
"on",
"the",
"models",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L159-L168 | train | 225,783 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.touch | def touch(self):
"""
Touch all of the related models of the relationship.
"""
key = self.get_related().get_key_name()
columns = self.get_related_fresh_update()
ids = self.get_related_ids()
if len(ids) > 0:
self.get_related().new_query().where_in(key, ids).update(columns) | python | def touch(self):
"""
Touch all of the related models of the relationship.
"""
key = self.get_related().get_key_name()
columns = self.get_related_fresh_update()
ids = self.get_related_ids()
if len(ids) > 0:
self.get_related().new_query().where_in(key, ids).update(columns) | [
"def",
"touch",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"get_related",
"(",
")",
".",
"get_key_name",
"(",
")",
"columns",
"=",
"self",
".",
"get_related_fresh_update",
"(",
")",
"ids",
"=",
"self",
".",
"get_related_ids",
"(",
")",
"if",
"len"... | Touch all of the related models of the relationship. | [
"Touch",
"all",
"of",
"the",
"related",
"models",
"of",
"the",
"relationship",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L391-L402 | train | 225,784 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.get_related_ids | def get_related_ids(self):
"""
Get all of the IDs for the related models.
:rtype: list
"""
related = self.get_related()
full_key = related.get_qualified_key_name()
return self.get_query().select(full_key).lists(related.get_key_name()) | python | def get_related_ids(self):
"""
Get all of the IDs for the related models.
:rtype: list
"""
related = self.get_related()
full_key = related.get_qualified_key_name()
return self.get_query().select(full_key).lists(related.get_key_name()) | [
"def",
"get_related_ids",
"(",
"self",
")",
":",
"related",
"=",
"self",
".",
"get_related",
"(",
")",
"full_key",
"=",
"related",
".",
"get_qualified_key_name",
"(",
")",
"return",
"self",
".",
"get_query",
"(",
")",
".",
"select",
"(",
"full_key",
")",
... | Get all of the IDs for the related models.
:rtype: list | [
"Get",
"all",
"of",
"the",
"IDs",
"for",
"the",
"related",
"models",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L404-L414 | train | 225,785 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.save_many | def save_many(self, models, joinings=None):
"""
Save a list of new models and attach them to the parent model
:type models: list
:type joinings: dict
:rtype: list
"""
if joinings is None:
joinings = {}
for key, model in enumerate(models):
self.save(model, joinings.get(key), False)
self.touch_if_touching()
return models | python | def save_many(self, models, joinings=None):
"""
Save a list of new models and attach them to the parent model
:type models: list
:type joinings: dict
:rtype: list
"""
if joinings is None:
joinings = {}
for key, model in enumerate(models):
self.save(model, joinings.get(key), False)
self.touch_if_touching()
return models | [
"def",
"save_many",
"(",
"self",
",",
"models",
",",
"joinings",
"=",
"None",
")",
":",
"if",
"joinings",
"is",
"None",
":",
"joinings",
"=",
"{",
"}",
"for",
"key",
",",
"model",
"in",
"enumerate",
"(",
"models",
")",
":",
"self",
".",
"save",
"("... | Save a list of new models and attach them to the parent model
:type models: list
:type joinings: dict
:rtype: list | [
"Save",
"a",
"list",
"of",
"new",
"models",
"and",
"attach",
"them",
"to",
"the",
"parent",
"model"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L435-L452 | train | 225,786 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.first_or_create | def first_or_create(
self, _attributes=None, _joining=None, _touch=True, **attributes
):
"""
Get the first related model record matching the attributes or create it.
:param attributes: The attributes
:type attributes: dict
:rtype: Model
"""
if _attributes is not None:
attributes.update(_attributes)
instance = self._query.where(attributes).first()
if instance is None:
instance = self.create(attributes, _joining or {}, _touch)
return instance | python | def first_or_create(
self, _attributes=None, _joining=None, _touch=True, **attributes
):
"""
Get the first related model record matching the attributes or create it.
:param attributes: The attributes
:type attributes: dict
:rtype: Model
"""
if _attributes is not None:
attributes.update(_attributes)
instance = self._query.where(attributes).first()
if instance is None:
instance = self.create(attributes, _joining or {}, _touch)
return instance | [
"def",
"first_or_create",
"(",
"self",
",",
"_attributes",
"=",
"None",
",",
"_joining",
"=",
"None",
",",
"_touch",
"=",
"True",
",",
"*",
"*",
"attributes",
")",
":",
"if",
"_attributes",
"is",
"not",
"None",
":",
"attributes",
".",
"update",
"(",
"_... | Get the first related model record matching the attributes or create it.
:param attributes: The attributes
:type attributes: dict
:rtype: Model | [
"Get",
"the",
"first",
"related",
"model",
"record",
"matching",
"the",
"attributes",
"or",
"create",
"it",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L490-L508 | train | 225,787 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.sync | def sync(self, ids, detaching=True):
"""
Sync the intermediate tables with a list of IDs or collection of models
"""
changes = {"attached": [], "detached": [], "updated": []}
if isinstance(ids, Collection):
ids = ids.model_keys()
current = self._new_pivot_query().lists(self._other_key).all()
records = self._format_sync_list(ids)
detach = [x for x in current if x not in records.keys()]
if detaching and len(detach) > 0:
self.detach(detach)
changes["detached"] = detach
changes.update(self._attach_new(records, current, False))
if len(changes["attached"]) or len(changes["updated"]):
self.touch_if_touching()
return changes | python | def sync(self, ids, detaching=True):
"""
Sync the intermediate tables with a list of IDs or collection of models
"""
changes = {"attached": [], "detached": [], "updated": []}
if isinstance(ids, Collection):
ids = ids.model_keys()
current = self._new_pivot_query().lists(self._other_key).all()
records = self._format_sync_list(ids)
detach = [x for x in current if x not in records.keys()]
if detaching and len(detach) > 0:
self.detach(detach)
changes["detached"] = detach
changes.update(self._attach_new(records, current, False))
if len(changes["attached"]) or len(changes["updated"]):
self.touch_if_touching()
return changes | [
"def",
"sync",
"(",
"self",
",",
"ids",
",",
"detaching",
"=",
"True",
")",
":",
"changes",
"=",
"{",
"\"attached\"",
":",
"[",
"]",
",",
"\"detached\"",
":",
"[",
"]",
",",
"\"updated\"",
":",
"[",
"]",
"}",
"if",
"isinstance",
"(",
"ids",
",",
... | Sync the intermediate tables with a list of IDs or collection of models | [
"Sync",
"the",
"intermediate",
"tables",
"with",
"a",
"list",
"of",
"IDs",
"or",
"collection",
"of",
"models"
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L572-L597 | train | 225,788 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany._format_sync_list | def _format_sync_list(self, records):
"""
Format the sync list so that it is keyed by ID.
"""
results = {}
for attributes in records:
if not isinstance(attributes, dict):
id, attributes = attributes, {}
else:
id = list(attributes.keys())[0]
attributes = attributes[id]
results[id] = attributes
return results | python | def _format_sync_list(self, records):
"""
Format the sync list so that it is keyed by ID.
"""
results = {}
for attributes in records:
if not isinstance(attributes, dict):
id, attributes = attributes, {}
else:
id = list(attributes.keys())[0]
attributes = attributes[id]
results[id] = attributes
return results | [
"def",
"_format_sync_list",
"(",
"self",
",",
"records",
")",
":",
"results",
"=",
"{",
"}",
"for",
"attributes",
"in",
"records",
":",
"if",
"not",
"isinstance",
"(",
"attributes",
",",
"dict",
")",
":",
"id",
",",
"attributes",
"=",
"attributes",
",",
... | Format the sync list so that it is keyed by ID. | [
"Format",
"the",
"sync",
"list",
"so",
"that",
"it",
"is",
"keyed",
"by",
"ID",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L599-L614 | train | 225,789 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.attach | def attach(self, id, attributes=None, touch=True):
"""
Attach a model to the parent.
"""
if isinstance(id, orator.orm.Model):
id = id.get_key()
query = self.new_pivot_statement()
if not isinstance(id, list):
id = [id]
query.insert(self._create_attach_records(id, attributes))
if touch:
self.touch_if_touching() | python | def attach(self, id, attributes=None, touch=True):
"""
Attach a model to the parent.
"""
if isinstance(id, orator.orm.Model):
id = id.get_key()
query = self.new_pivot_statement()
if not isinstance(id, list):
id = [id]
query.insert(self._create_attach_records(id, attributes))
if touch:
self.touch_if_touching() | [
"def",
"attach",
"(",
"self",
",",
"id",
",",
"attributes",
"=",
"None",
",",
"touch",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"id",
",",
"orator",
".",
"orm",
".",
"Model",
")",
":",
"id",
"=",
"id",
".",
"get_key",
"(",
")",
"query",
... | Attach a model to the parent. | [
"Attach",
"a",
"model",
"to",
"the",
"parent",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L648-L663 | train | 225,790 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany._create_attach_records | def _create_attach_records(self, ids, attributes):
"""
Create a list of records to insert into the pivot table.
"""
records = []
timed = self._has_pivot_column(self.created_at()) or self._has_pivot_column(
self.updated_at()
)
for key, value in enumerate(ids):
records.append(self._attacher(key, value, attributes, timed))
return records | python | def _create_attach_records(self, ids, attributes):
"""
Create a list of records to insert into the pivot table.
"""
records = []
timed = self._has_pivot_column(self.created_at()) or self._has_pivot_column(
self.updated_at()
)
for key, value in enumerate(ids):
records.append(self._attacher(key, value, attributes, timed))
return records | [
"def",
"_create_attach_records",
"(",
"self",
",",
"ids",
",",
"attributes",
")",
":",
"records",
"=",
"[",
"]",
"timed",
"=",
"self",
".",
"_has_pivot_column",
"(",
"self",
".",
"created_at",
"(",
")",
")",
"or",
"self",
".",
"_has_pivot_column",
"(",
"... | Create a list of records to insert into the pivot table. | [
"Create",
"a",
"list",
"of",
"records",
"to",
"insert",
"into",
"the",
"pivot",
"table",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L665-L678 | train | 225,791 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany._attacher | def _attacher(self, key, value, attributes, timed):
"""
Create a full attachment record payload.
"""
id, extra = self._get_attach_id(key, value, attributes)
record = self._create_attach_record(id, timed)
if extra:
record.update(extra)
return record | python | def _attacher(self, key, value, attributes, timed):
"""
Create a full attachment record payload.
"""
id, extra = self._get_attach_id(key, value, attributes)
record = self._create_attach_record(id, timed)
if extra:
record.update(extra)
return record | [
"def",
"_attacher",
"(",
"self",
",",
"key",
",",
"value",
",",
"attributes",
",",
"timed",
")",
":",
"id",
",",
"extra",
"=",
"self",
".",
"_get_attach_id",
"(",
"key",
",",
"value",
",",
"attributes",
")",
"record",
"=",
"self",
".",
"_create_attach_... | Create a full attachment record payload. | [
"Create",
"a",
"full",
"attachment",
"record",
"payload",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L680-L691 | train | 225,792 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany._get_attach_id | def _get_attach_id(self, key, value, attributes):
"""
Get the attach record ID and extra attributes.
"""
if isinstance(value, dict):
key = list(value.keys())[0]
attributes.update(value[key])
return [key, attributes]
return value, attributes | python | def _get_attach_id(self, key, value, attributes):
"""
Get the attach record ID and extra attributes.
"""
if isinstance(value, dict):
key = list(value.keys())[0]
attributes.update(value[key])
return [key, attributes]
return value, attributes | [
"def",
"_get_attach_id",
"(",
"self",
",",
"key",
",",
"value",
",",
"attributes",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"key",
"=",
"list",
"(",
"value",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"attributes",
".",
... | Get the attach record ID and extra attributes. | [
"Get",
"the",
"attach",
"record",
"ID",
"and",
"extra",
"attributes",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L693-L703 | train | 225,793 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany._set_timestamps_on_attach | def _set_timestamps_on_attach(self, record, exists=False):
"""
Set the creation an update timestamps on an attach record.
"""
fresh = self._parent.fresh_timestamp()
if not exists and self._has_pivot_column(self.created_at()):
record[self.created_at()] = fresh
if self._has_pivot_column(self.updated_at()):
record[self.updated_at()] = fresh
return record | python | def _set_timestamps_on_attach(self, record, exists=False):
"""
Set the creation an update timestamps on an attach record.
"""
fresh = self._parent.fresh_timestamp()
if not exists and self._has_pivot_column(self.created_at()):
record[self.created_at()] = fresh
if self._has_pivot_column(self.updated_at()):
record[self.updated_at()] = fresh
return record | [
"def",
"_set_timestamps_on_attach",
"(",
"self",
",",
"record",
",",
"exists",
"=",
"False",
")",
":",
"fresh",
"=",
"self",
".",
"_parent",
".",
"fresh_timestamp",
"(",
")",
"if",
"not",
"exists",
"and",
"self",
".",
"_has_pivot_column",
"(",
"self",
".",... | Set the creation an update timestamps on an attach record. | [
"Set",
"the",
"creation",
"an",
"update",
"timestamps",
"on",
"an",
"attach",
"record",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L720-L732 | train | 225,794 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.detach | def detach(self, ids=None, touch=True):
"""
Detach models from the relationship.
"""
if isinstance(ids, orator.orm.model.Model):
ids = ids.get_key()
if ids is None:
ids = []
query = self._new_pivot_query()
if not isinstance(ids, list):
ids = [ids]
if len(ids) > 0:
query.where_in(self._other_key, ids)
if touch:
self.touch_if_touching()
results = query.delete()
return results | python | def detach(self, ids=None, touch=True):
"""
Detach models from the relationship.
"""
if isinstance(ids, orator.orm.model.Model):
ids = ids.get_key()
if ids is None:
ids = []
query = self._new_pivot_query()
if not isinstance(ids, list):
ids = [ids]
if len(ids) > 0:
query.where_in(self._other_key, ids)
if touch:
self.touch_if_touching()
results = query.delete()
return results | [
"def",
"detach",
"(",
"self",
",",
"ids",
"=",
"None",
",",
"touch",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"ids",
",",
"orator",
".",
"orm",
".",
"model",
".",
"Model",
")",
":",
"ids",
"=",
"ids",
".",
"get_key",
"(",
")",
"if",
"ids... | Detach models from the relationship. | [
"Detach",
"models",
"from",
"the",
"relationship",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L734-L757 | train | 225,795 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.touch_if_touching | def touch_if_touching(self):
"""
Touch if the parent model is being touched.
"""
if self._touching_parent():
self.get_parent().touch()
if self.get_parent().touches(self._relation_name):
self.touch() | python | def touch_if_touching(self):
"""
Touch if the parent model is being touched.
"""
if self._touching_parent():
self.get_parent().touch()
if self.get_parent().touches(self._relation_name):
self.touch() | [
"def",
"touch_if_touching",
"(",
"self",
")",
":",
"if",
"self",
".",
"_touching_parent",
"(",
")",
":",
"self",
".",
"get_parent",
"(",
")",
".",
"touch",
"(",
")",
"if",
"self",
".",
"get_parent",
"(",
")",
".",
"touches",
"(",
"self",
".",
"_relat... | Touch if the parent model is being touched. | [
"Touch",
"if",
"the",
"parent",
"model",
"is",
"being",
"touched",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L759-L767 | train | 225,796 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.with_pivot | def with_pivot(self, *columns):
"""
Set the columns on the pivot table to retrieve.
"""
columns = list(columns)
self._pivot_columns += columns
return self | python | def with_pivot(self, *columns):
"""
Set the columns on the pivot table to retrieve.
"""
columns = list(columns)
self._pivot_columns += columns
return self | [
"def",
"with_pivot",
"(",
"self",
",",
"*",
"columns",
")",
":",
"columns",
"=",
"list",
"(",
"columns",
")",
"self",
".",
"_pivot_columns",
"+=",
"columns",
"return",
"self"
] | Set the columns on the pivot table to retrieve. | [
"Set",
"the",
"columns",
"on",
"the",
"pivot",
"table",
"to",
"retrieve",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L819-L827 | train | 225,797 |
sdispater/orator | orator/orm/relations/belongs_to_many.py | BelongsToMany.with_timestamps | def with_timestamps(self, created_at=None, updated_at=None):
"""
Specify that the pivot table has creation and update columns.
"""
if not created_at:
created_at = self.created_at()
if not updated_at:
updated_at = self.updated_at()
return self.with_pivot(created_at, updated_at) | python | def with_timestamps(self, created_at=None, updated_at=None):
"""
Specify that the pivot table has creation and update columns.
"""
if not created_at:
created_at = self.created_at()
if not updated_at:
updated_at = self.updated_at()
return self.with_pivot(created_at, updated_at) | [
"def",
"with_timestamps",
"(",
"self",
",",
"created_at",
"=",
"None",
",",
"updated_at",
"=",
"None",
")",
":",
"if",
"not",
"created_at",
":",
"created_at",
"=",
"self",
".",
"created_at",
"(",
")",
"if",
"not",
"updated_at",
":",
"updated_at",
"=",
"s... | Specify that the pivot table has creation and update columns. | [
"Specify",
"that",
"the",
"pivot",
"table",
"has",
"creation",
"and",
"update",
"columns",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to_many.py#L829-L839 | train | 225,798 |
sdispater/orator | orator/orm/relations/belongs_to.py | BelongsTo._get_eager_model_keys | def _get_eager_model_keys(self, models):
"""
Gather the keys from a list of related models.
:type models: list
:rtype: list
"""
keys = []
for model in models:
value = getattr(model, self._foreign_key)
if value is not None and value not in keys:
keys.append(value)
if not len(keys):
return [0]
return keys | python | def _get_eager_model_keys(self, models):
"""
Gather the keys from a list of related models.
:type models: list
:rtype: list
"""
keys = []
for model in models:
value = getattr(model, self._foreign_key)
if value is not None and value not in keys:
keys.append(value)
if not len(keys):
return [0]
return keys | [
"def",
"_get_eager_model_keys",
"(",
"self",
",",
"models",
")",
":",
"keys",
"=",
"[",
"]",
"for",
"model",
"in",
"models",
":",
"value",
"=",
"getattr",
"(",
"model",
",",
"self",
".",
"_foreign_key",
")",
"if",
"value",
"is",
"not",
"None",
"and",
... | Gather the keys from a list of related models.
:type models: list
:rtype: list | [
"Gather",
"the",
"keys",
"from",
"a",
"list",
"of",
"related",
"models",
"."
] | bd90bf198ee897751848f9a92e49d18e60a74136 | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/belongs_to.py#L87-L106 | train | 225,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.