docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Reads artifact definitions from a file-like object.
Args:
file_object (file): file-like object to read from.
Yields:
ArtifactDefinition: an artifact definition.
Raises:
FormatError: if the format of the JSON artifact definition is not set
or incorrect. | def ReadFileObject(self, file_object):
# TODO: add try, except?
json_definitions = json.loads(file_object.read())
last_artifact_definition = None
for json_definition in json_definitions:
try:
artifact_definition = self.ReadArtifactDefinitionValues(json_definition)
except errors... | 307,119 |
Reads artifact definitions from a file-like object.
Args:
file_object (file): file-like object to read from.
Yields:
ArtifactDefinition: an artifact definition.
Raises:
FormatError: if the format of the YAML artifact definition is not set
or incorrect. | def ReadFileObject(self, file_object):
# TODO: add try, except?
yaml_generator = yaml.safe_load_all(file_object)
last_artifact_definition = None
for yaml_definition in yaml_generator:
try:
artifact_definition = self.ReadArtifactDefinitionValues(yaml_definition)
except errors.Fo... | 307,120 |
Writes artifact definitions to a file.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions to be written.
filename (str): name of the file to write artifacts to. | def WriteArtifactsFile(self, artifacts, filename):
with open(filename, 'w') as file_object:
file_object.write(self.FormatArtifacts(artifacts)) | 307,121 |
Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition. | def FormatArtifacts(self, artifacts):
artifact_definitions = [artifact.AsDict() for artifact in artifacts]
json_data = json.dumps(artifact_definitions)
return json_data | 307,122 |
Formats artifacts to desired output format.
Args:
artifacts (list[ArtifactDefinition]): artifact definitions.
Returns:
str: formatted string of artifact definition. | def FormatArtifacts(self, artifacts):
# TODO: improve output formatting of yaml
artifact_definitions = [artifact.AsDict() for artifact in artifacts]
yaml_data = yaml.safe_dump_all(artifact_definitions)
return yaml_data | 307,123 |
Initializes an artifact definition.
Args:
name (str): name that uniquely identifiers the artifact definition.
description (Optional[str]): description of the artifact definition. | def __init__(self, name, description=None):
super(ArtifactDefinition, self).__init__()
self.conditions = []
self.description = description
self.name = name
self.labels = []
self.provides = []
self.sources = []
self.supported_os = []
self.urls = [] | 307,124 |
Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object | def from_b58check(private_key):
b58dec = base58.b58decode_check(private_key)
version = b58dec[0]
assert version in [PrivateKey.TESTNET_VERSION,
PrivateKey.MAINNET_VERSION]
return PrivateKey(int.from_bytes(b58dec[1:], 'big')) | 307,592 |
Generates a public key object from an integer.
Note:
This assumes that the upper 32 bytes of the integer
are the x component of the public key point and the
lower 32 bytes are the y component.
Args:
i (Bignum): A 512-bit integer representing the public
... | def from_int(i):
point = ECPointAffine.from_int(bitcoin_curve, i)
return PublicKey.from_point(point) | 307,598 |
Attempts to create PublicKey object by deriving it
from the message and signature.
Args:
message (bytes): The message to be verified.
signature (Signature): The signature for message.
The recovery_id must not be None!
Returns:
PublicKey:
... | def from_signature(message, signature):
if signature.recovery_id is None:
raise ValueError("The signature must have a recovery_id.")
msg = get_bytes(message)
pub_keys = bitcoin_curve.recover_public_key(msg,
signature,
... | 307,600 |
Verifies a message signed using PrivateKey.sign_bitcoin()
or any of the bitcoin utils (e.g. bitcoin-cli, bx, etc.)
Args:
message(bytes): The message that the signature corresponds to.
signature (bytes or str): A Base64 encoded signature
address (str): Base58Check enc... | def verify_bitcoin(message, signature, address):
magic_sig = base64.b64decode(signature)
magic = magic_sig[0]
sig = Signature.from_bytes(magic_sig[1:])
sig.recovery_id = (magic - 27) & 0x3
compressed = ((magic - 27) & 0x4) != 0
# Build the message that was sign... | 307,601 |
Address property that returns the Base58Check
encoded version of the HASH160.
Args:
compressed (bool): Whether or not the compressed key should
be used.
testnet (bool): Whether or not the key is intended for testnet
usage. False indicates mainnet us... | def address(self, compressed=True, testnet=False):
version = '0x'
return version + binascii.hexlify(self.keccak[12:]).decode('ascii') | 307,603 |
Decodes a Signature that was DER-encoded.
Args:
der (bytes or str): The DER encoding to be decoded.
Returns:
Signature: The deserialized signature. | def from_der(der):
d = get_bytes(der)
# d must conform to (from btcd):
# [0 ] 0x30 - ASN.1 identifier for sequence
# [1 ] <1-byte> - total remaining length
# [2 ] 0x02 - ASN.1 identifier to specify an integer follows
# [3 ] <1-byte> - length of R
... | 307,606 |
Extracts the r and s components from a byte string.
Args:
b (bytes): A 64-byte long string. The first 32 bytes are
extracted as the r component and the second 32 bytes
are extracted as the s component.
Returns:
Signature: A Signature object.
... | def from_bytes(b):
if len(b) != 64:
raise ValueError("from_bytes: Signature length != 64.")
r = int.from_bytes(b[0:32], 'big')
s = int.from_bytes(b[32:64], 'big')
return Signature(r, s) | 307,607 |
Generates either a HDPrivateKey or HDPublicKey from the underlying
bytes.
The serialization must conform to the description in:
https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format
Args:
b (bytes): A byte stream conforming to the above.
... | def from_bytes(b):
if len(b) < 78:
raise ValueError("b must be at least 78 bytes long.")
version = int.from_bytes(b[:4], 'big')
depth = b[4]
parent_fingerprint = b[5:9]
index = int.from_bytes(b[9:13], 'big')
chain_code = b[13:45]
key_bytes = ... | 307,612 |
Generates a Base58Check encoding of this key.
Args:
testnet (bool): True if the key is to be used with
testnet, False otherwise.
Returns:
str: A Base58Check encoded string representing the key. | def to_b58check(self, testnet=False):
b = self.testnet_bytes if testnet else bytes(self)
return base58.b58encode_check(b) | 307,617 |
Generates a master key from system entropy.
Args:
strength (int): Amount of entropy desired. This should be
a multiple of 32 between 128 and 256.
passphrase (str): An optional passphrase for the generated
mnemonic string.
Returns:
HDPri... | def master_key_from_entropy(passphrase='', strength=128):
if strength % 32 != 0:
raise ValueError("strength must be a multiple of 32")
if strength < 128 or strength > 256:
raise ValueError("strength should be >= 128 and <= 256")
entropy = rand_bytes(strength // 8... | 307,619 |
Generates a master key from a provided seed.
Args:
seed (bytes or str): a string of bytes or a hex string
Returns:
HDPrivateKey: the master private key. | def master_key_from_seed(seed):
S = get_bytes(seed)
I = hmac.new(b"Bitcoin seed", S, hashlib.sha512).digest()
Il, Ir = I[:32], I[32:]
parse_Il = int.from_bytes(Il, 'big')
if parse_Il == 0 or parse_Il >= bitcoin_curve.n:
raise ValueError("Bad seed, resulting i... | 307,620 |
Derives a child private key from a parent
private key. It is not possible to derive a child
private key from a public parent key.
Args:
parent_private_key (HDPrivateKey): | def from_parent(parent_key, i):
if not isinstance(parent_key, HDPrivateKey):
raise TypeError("parent_key must be an HDPrivateKey object.")
hmac_key = parent_key.chain_code
if i & 0x80000000:
hmac_data = b'\x00' + bytes(parent_key._key) + i.to_bytes(length=4, byt... | 307,621 |
Address property that returns the Base58Check
encoded version of the HASH160.
Args:
compressed (bool): Whether or not the compressed key should
be used.
testnet (bool): Whether or not the key is intended for testnet
usage. False indicates mainnet us... | def address(self, compressed=True, testnet=False):
return self._key.address(True, testnet) | 307,629 |
Fit :class`Extractor` features and model to a training dataset.
Args:
blocks (List[Block])
labels (``np.ndarray``)
weights (``np.ndarray``)
Returns:
:class`Extractor` | def fit(self, documents, labels, weights=None):
block_groups = np.array([self.blockifier.blockify(doc) for doc in documents])
mask = [self._has_enough_blocks(blocks) for blocks in block_groups]
block_groups = block_groups[mask]
labels = np.concatenate(np.array(labels)[mask])
... | 308,882 |
Gather the html, labels, and weights of many files' data.
Primarily useful for training/testing an :class`Extractor`.
Args:
data: Output of :func:`dragnet.data_processing.prepare_all_data`.
Returns:
Tuple[List[Block], np.array(int), np.array(int)]: All blocks, all
... | def get_html_labels_weights(self, data):
all_html = []
all_labels = []
all_weights = []
for html, content, comments in data:
all_html.append(html)
labels, weights = self._get_labels_and_weights(
content, comments)
all_labels.ap... | 308,883 |
Predict class (content=1 or not-content=0) of the blocks in one or many
HTML document(s).
Args:
documents (str or List[str]): HTML document(s)
Returns:
``np.ndarray`` or List[``np.ndarray``]: array of binary predictions
for content (1) or not-content (0)... | def predict(self, documents, **kwargs):
if isinstance(documents, (str, bytes, unicode_, np.unicode_)):
return self._predict_one(documents, **kwargs)
else:
return np.concatenate([self._predict_one(doc, **kwargs) for doc in documents]) | 308,887 |
Predict class (content=1 or not-content=0) of each block in an HTML
document.
Args:
documents (str): HTML document
Returns:
``np.ndarray``: array of binary predictions for content (1) or
not-content (0). | def _predict_one(self, document, encoding=None, return_blocks=False):
# blockify
blocks = self.blockifier.blockify(document, encoding=encoding)
# get features
try:
features = self.features.transform(blocks)
except ValueError: # Can't make features, predict no... | 308,888 |
Evaluate the performance of an extractor model's binary classification
predictions, typically at the block level, of whether a block is content
or not.
Args:
y_true (``np.ndarray``)
y_pred (``np.ndarray``)
weights (``np.ndarray``)
Returns:
Dict[str, float] | def evaluate_model_predictions(y_true, y_pred, weights=None):
if isinstance(y_pred[0], np.ndarray):
y_pred = np.concatenate(y_pred)
if isinstance(y_true[0], np.ndarray):
y_true = np.concatenate(y_true)
if (weights is not None) and (isinstance(weights[0], np.ndarray)):
weights = ... | 308,896 |
Read the HTML file corresponding to identifier ``fileroot``
in the raw HTML directory below the root ``data_dir``.
Args:
data_dir (str)
fileroot (str)
encoding (str)
Returns:
str | def read_html_file(data_dir, fileroot, encoding=None):
fname = os.path.join(
data_dir, RAW_HTML_DIRNAME, fileroot + RAW_HTML_EXT)
encodings = (encoding,) if encoding else ('utf-8', 'iso-8859-1') # 'utf-16'
for encoding in encodings:
try:
with io.open(fname, mode='rt', encod... | 308,906 |
Read the gold standard content file corresponding to identifier ``fileroot``
in the gold standard directory below the root ``data_dir``.
Args:
data_dir (str)
fileroot (str)
encoding (str)
cetr (bool): if True, assume no comments and parse the gold standard
to remove ... | def read_gold_standard_file(data_dir, fileroot, encoding=None, cetr=False):
fname = os.path.join(
data_dir, GOLD_STANDARD_DIRNAME, fileroot + GOLD_STANDARD_EXT)
encodings = (encoding,) if encoding else ('utf-8', 'utf-16', 'iso-8859-1')
for encoding in encodings:
try:
with io... | 308,907 |
Read the gold standard blocks file corresponding to identifier ``fileroot``
in the gold standard blocks directory below the root ``data_dir``.
Args:
data_dir (str)
fileroot (str)
split_blocks (bool): If True, split the file's content into blocks.
Returns:
str or List[str] | def read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True):
fname = os.path.join(
data_dir, GOLD_STANDARD_BLOCKS_DIRNAME, fileroot + GOLD_STANDARD_BLOCKS_EXT)
with io.open(fname, mode='r') as f:
data = f.read()
if split_blocks:
return filter(None, data[:-1].split(... | 308,908 |
Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float, int, List[str]], List[float, int, List[str]]]]
See Also:
:func:`prepare_data` | def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1):
gs_blocks_dir = os.path.join(data_dir, GOLD_STANDARD_BLOCKS_DIRNAME)
gs_blocks_filenames = get_filenames(
gs_blocks_dir, full_path=False, match_regex=re.escape(GOLD_STANDARD_BLOCKS_EXT))
gs_blocks_fileroots = (
re.search(r'(.+... | 308,911 |
Load a pickled ``Extractor`` model from disk.
Args:
filename (str): Name of pickled model file under ``dirname``.
dirname (str): Name of directory on disk containing the pickled model.
If None, dragnet's default pickled model directory is used:
/path/to/dragnet/pickled_model... | def load_pickled_model(filename, dirname=None):
if dirname is None:
pkg_filename = pkgutil.get_loader('dragnet').get_filename('dragnet')
pkg_dirname = os.path.dirname(pkg_filename)
dirname = os.path.join(pkg_dirname, 'pickled_models', model_path)
filepath = os.path.join(dirname, fil... | 308,926 |
Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` is not a file-like object that takes by... | def write_to_fp(self, fp):
# When disabling ssl verify in requests (for proxies and firewalls),
# urllib3 prints an insecure warning on stdout. We disable that.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
text_parts = self._tokenize(self.text)
lo... | 309,286 |
Do the TTS API request and write result to file.
Args:
savefile (string): The path and file name to save the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request. | def save(self, savefile):
with open(str(savefile), 'wb') as f:
self.write_to_fp(f)
log.debug("Saved to %s", savefile) | 309,287 |
Run each regex substitution on ``text``.
Args:
text (string): the input text.
Returns:
string: text after all substitutions have been sequentially
applied. | def run(self, text):
for regex in self.regexes:
text = regex.sub(self.repl, text)
return text | 309,294 |
Run each substitution on ``text``.
Args:
text (string): the input text.
Returns:
string: text after all substitutions have been sequentially
applied. | def run(self, text):
for pp in self.pre_processors:
text = pp.run(text)
return text | 309,297 |
Calculate ROUGE scores between each pair of
lines (hyp_file[i], ref_file[i]).
Args:
* hyp_path: hypothesis file path
* ref_path: references file path
* avg (False): whether to get an average scores or a list | def get_scores(self, avg=False, ignore_empty=False):
hyp_path, ref_path = self.hyp_path, self.ref_path
with io.open(hyp_path, encoding="utf-8", mode="r") as hyp_file:
hyps = [line[:-1] for line in hyp_file]
with io.open(ref_path, encoding="utf-8", mode="r") as ref_file:
... | 309,306 |
Handle the orelse part of an if or try node.
Args:
orelse(list[Node])
test(Node)
Returns:
The last nodes of the orelse branch. | def handle_or_else(self, orelse, test):
if isinstance(orelse[0], ast.If):
control_flow_node = self.visit(orelse[0])
# Prefix the if label with 'el'
control_flow_node.test.label = 'el' + control_flow_node.test.label
test.connect(control_flow_node.test)
... | 310,434 |
Save the local scope before entering a function call by saving all the LHS's of assignments so far.
Args:
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.
Returns:
saved_variable... | def save_local_scope(
self,
line_number,
saved_function_call_index
):
saved_variables = list()
saved_variables_so_far = set()
first_node = None
# Make e.g. save_N_LHS = assignment.LHS for each AssignmentNode
for assignment in [node for node i... | 310,467 |
Visits the nodes of a user defined function.
Args:
definition(LocalModuleDefinition): Definition of the function being added.
first_node(EntryOrExitNode or None or RestoreNode): Used to connect previous statements to this function.
Returns:
the_new_nodes(list[Node])... | def visit_and_get_function_nodes(
self,
definition,
first_node
):
len_before_visiting_func = len(self.nodes)
previous_node = self.nodes[-1]
entry_node = self.append_node(EntryOrExitNode('Function Entry ' +
... | 310,470 |
Restore the previously saved variables to their original values.
Args:
saved_variables(list[SavedVariable])
args_mapping(dict): A mapping of call argument to definition argument.
line_number(int): Of the def of the function call about to be entered into.
Note: We do no... | def restore_saved_local_scope(
self,
saved_variables,
args_mapping,
line_number
):
restore_nodes = list()
for var in saved_variables:
# Is var.RHS a call argument?
if var.RHS in args_mapping:
# If so, use the correspond... | 310,471 |
Handle the return from a function during a function call.
Args:
call_node(ast.Call) : The node that calls the definition.
function_nodes(list[Node]): List of nodes of the function being called.
saved_function_call_index(int): Unique number for each call.
first_no... | def return_handler(
self,
call_node,
function_nodes,
saved_function_call_index,
first_node
):
if any(isinstance(node, YieldNode) for node in function_nodes):
# Presence of a `YieldNode` means that the function is a generator
rhs_prefix... | 310,472 |
Prints issues in color-coded text format.
Args:
vulnerabilities: list of vulnerabilities to report
fileobj: The output file object, which may be sys.stdout | def report(
vulnerabilities,
fileobj,
print_sanitised,
):
n_vulnerabilities = len(vulnerabilities)
unsanitised_vulnerabilities = [v for v in vulnerabilities if not isinstance(v, SanitisedVulnerability)]
n_unsanitised = len(unsanitised_vulnerabilities)
n_sanitised = n_vulnerabilities - n... | 310,477 |
Create a Node that can be used in a CFG.
Args:
label(str): The label of the node, describing its expression.
line_number(Optional[int]): The line of the expression of the Node. | def __init__(self, label, ast_node, *, line_number=None, path):
self.label = label
self.ast_node = ast_node
if line_number:
self.line_number = line_number
elif ast_node:
self.line_number = ast_node.lineno
else:
self.line_number = None
... | 310,505 |
Create a Restore node.
Args:
label(str): The label of the node, describing the expression it represents.
left_hand_side(str): The variable on the left hand side of the assignment. Used for analysis.
right_hand_side_variables(list[str]): A list of variables on the right hand ... | def __init__(self, label, left_hand_side, right_hand_side_variables, *, line_number, path):
super().__init__(label, left_hand_side, None, right_hand_side_variables, line_number=line_number, path=path) | 310,513 |
Identify sources, sinks and sanitisers in a CFG.
Args:
cfg(CFG): CFG to find sources, sinks and sanitisers in.
sources(tuple): list of sources, a source is a (source, sanitiser) tuple.
sinks(tuple): list of sources, a sink is a (sink, sanitiser) tuple.
nosec_lines(set): lines with #... | def identify_triggers(
cfg,
sources,
sinks,
lattice,
nosec_lines
):
assignment_nodes = filter_cfg_nodes(cfg, AssignmentNode)
tainted_nodes = filter_cfg_nodes(cfg, TaintedNode)
tainted_trigger_nodes = [
TriggerNode(
Source('Framework function URL parameter'),
... | 310,536 |
Sets the secondary_nodes attribute of each source in the sources list.
Args:
assignment_nodes([AssignmentNode])
sources([tuple])
lattice(Lattice): the lattice we're analysing. | def find_secondary_sources(
assignment_nodes,
sources,
lattice
):
for source in sources:
source.secondary_nodes = find_assignments(assignment_nodes, source, lattice) | 310,538 |
Find triggers from the trigger_word_list in the nodes.
Args:
nodes(list[Node]): the nodes to find triggers in.
trigger_word_list(list[Union[Sink, Source]]): list of trigger words to look for.
nosec_lines(set): lines with # nosec whitelisting
Returns:
List of found TriggerNodes | def find_triggers(
nodes,
trigger_words,
nosec_lines
):
trigger_nodes = list()
for node in nodes:
if node.line_number not in nosec_lines:
trigger_nodes.extend(iter(label_contains(node, trigger_words)))
return trigger_nodes | 310,542 |
Determine if node contains any of the trigger_words provided.
Args:
node(Node): CFG node to check.
trigger_words(list[Union[Sink, Source]]): list of trigger words to look for.
Returns:
Iterable of TriggerNodes found. Can be multiple because multiple
trigger_words can be in one ... | def label_contains(
node,
triggers
):
for trigger in triggers:
if trigger.trigger_word in node.label:
yield TriggerNode(trigger, node) | 310,543 |
Build a dict of string -> TriggerNode pairs, where the string
is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser.
Args:
cfg(CFG): cfg to traverse.
sinks_in_file(list[TriggerNode]): list of TriggerNodes containing
the sinks in the ... | def build_sanitiser_node_dict(
cfg,
sinks_in_file
):
sanitisers = list()
for sink in sinks_in_file:
sanitisers.extend(sink.sanitisers)
sanitisers_in_file = list()
for sanitiser in sanitisers:
for cfg_node in cfg.nodes:
if sanitiser in cfg_node.label:
... | 310,544 |
Find nodes containing a particular sanitiser.
Args:
sanitiser(string): sanitiser to look for.
sanitisers_in_file(list[Node]): list of CFG nodes with the sanitiser.
Returns:
Iterable of sanitiser nodes. | def find_sanitiser_nodes(
sanitiser,
sanitisers_in_file
):
for sanitiser_tuple in sanitisers_in_file:
if sanitiser == sanitiser_tuple.trigger_word:
yield sanitiser_tuple.cfg_node | 310,545 |
Traverses the def-use graph to find all paths from source to sink that cause a vulnerability.
Args:
current_node()
sink()
def_use(dict):
chain(list(Node)): A path of nodes between source and sink. | def get_vulnerability_chains(
current_node,
sink,
def_use,
chain=[]
):
for use in def_use[current_node]:
if use == sink:
yield chain
else:
vuln_chain = list(chain)
vuln_chain.append(use)
yield from get_vulnerability_chains(
... | 310,548 |
Find vulnerabilities in a list of CFGs from a trigger_word_file.
Args:
cfg_list(list[CFG]): the list of CFGs to scan.
blackbox_mapping_file(str)
sources_and_sinks_file(str)
interactive(bool): determines if we ask the user about blackbox functions not in the mapping file.
Returns... | def find_vulnerabilities(
cfg_list,
blackbox_mapping_file,
sources_and_sinks_file,
interactive=False,
nosec_lines=defaultdict(set)
):
vulnerabilities = list()
definitions = parse(sources_and_sinks_file)
with open(blackbox_mapping_file) as infile:
blackbox_mapping = json.loa... | 310,553 |
Replace any aliases in label with the fully qualified name.
Args:
label -- A label : str representing a name (e.g. myos.system)
aliases -- A dict of {alias: real_name} (e.g. {'myos': 'os'})
>>> fully_qualify_alias_labels('myos.mycall', {'myos':'os'})
'os.mycall' | def fully_qualify_alias_labels(label, aliases):
for alias, full_name in aliases.items():
if label == alias:
return full_name
elif label.startswith(alias+'.'):
return full_name + label[len(alias):]
return label | 310,669 |
Generate an Abstract Syntax Tree using the ast module.
Args:
path(str): The path to the file e.g. example/foo/bar.py | def generate_ast(path):
if os.path.isfile(path):
with open(path, 'r') as f:
try:
tree = ast.parse(f.read())
return PytTransformer().visit(tree)
except SyntaxError: # pragma: no cover
global recursive
if not recursi... | 310,673 |
Argument container class.
Args:
args(list(ast.args): The arguments in a function AST node. | def __init__(self, args):
self.args = args.args
self.varargs = args.vararg
self.kwarg = args.kwarg
self.kwonlyargs = args.kwonlyargs
self.defaults = args.defaults
self.kw_defaults = args.kw_defaults
self.arguments = list()
if self.args:
... | 310,675 |
Prints issues in JSON format.
Args:
vulnerabilities: list of vulnerabilities to report
fileobj: The output file object, which may be sys.stdout | def report(
vulnerabilities,
fileobj,
print_sanitised,
):
TZ_AGNOSTIC_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
time_string = datetime.utcnow().strftime(TZ_AGNOSTIC_FORMAT)
machine_output = {
'generated_at': time_string,
'vulnerabilities': [
vuln.as_dict() for vuln in vulne... | 310,678 |
infer a function argument value according to the call context
Arguments:
funcnode: The function being called.
name: The name of the argument whose value is being inferred.
context: Inference context object | def infer_argument(self, funcnode, name, context):
if name in self.duplicated_keywords:
raise exceptions.InferenceError(
"The arguments passed to {func!r} " " have duplicate keywords.",
call_site=self,
func=funcnode,
arg=name,
... | 310,857 |
Splits registration ids in several lists of max 1000 registration ids per list
Args:
registration_ids (list): FCM device registration ID
Yields:
generator: list including lists with registration ids | def registration_id_chunks(self, registration_ids):
try:
xrange
except NameError:
xrange = range
# Yield successive 1000-sized (max fcm recipients per request) chunks from registration_ids
for i in xrange(0, len(registration_ids), self.FCM_MAX_RECIPIENTS... | 312,132 |
Standardized json.dumps function with separators and sorted keys set
Args:
data (dict or list): data to be dumped
Returns:
string: json | def json_dumps(self, data):
return json.dumps(
data,
separators=(',', ':'),
sort_keys=True,
cls=self.json_encoder,
ensure_ascii=False
).encode('utf8') | 312,133 |
Makes a request for registration info and returns the response object
Args:
registration_id: id to be checked
Returns:
response of registration info request | def registration_info_request(self, registration_id):
return self.requests_session.get(
self.INFO_END_POINT + registration_id,
params={'details': 'true'}
) | 312,137 |
Checks registration ids and excludes inactive ids
Args:
registration_ids (list, optional): list of ids to be cleaned
Returns:
list: cleaned registration ids | def clean_registration_ids(self, registration_ids=[]):
valid_registration_ids = []
for registration_id in registration_ids:
details = self.registration_info_request(registration_id)
if details.status_code == 200:
valid_registration_ids.append(registration... | 312,138 |
Returns details related to a registration id if it exists otherwise return None
Args:
registration_id: id to be checked
Returns:
dict: info about registration id
None: if id doesn't exist | def get_registration_id_info(self, registration_id):
response = self.registration_info_request(registration_id)
if response.status_code == 200:
return response.json()
return None | 312,139 |
Subscribes a list of registration ids to a topic
Args:
registration_ids (list): ids to be subscribed
topic_name (str): name of topic
Returns:
True: if operation succeeded
Raises:
InvalidDataError: data sent to server was incorrectly formatted
... | def subscribe_registration_ids_to_topic(self, registration_ids, topic_name):
url = 'https://iid.googleapis.com/iid/v1:batchAdd'
payload = {
'to': '/topics/' + topic_name,
'registration_tokens': registration_ids,
}
response = self.requests_session.post(url... | 312,140 |
Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error... | def IsErrorSuppressedByNolint(category, linenum):
return (linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set())) | 312,371 |
Checks for horizontal spacing around operators.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckOperatorSpacing(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Don't try to do spacing checks for operator methods. Do this by
# replacing the troublesome characters with something else,
# preserving column position for all other characters.
#
# The replacement is... | 312,376 |
Check if the token ending on (linenum, column) is the end of template<>.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is end of a template parameter list, False otherw... | def IsTemplateParameterList(clean_lines, linenum, column):
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, column)
if (startpos > -1 and
Search(r'\btemplate\s*$', clean_lines.elided[startline][0:startpos])):
return True
return False | 312,377 |
Check if current constructor or operator is deleted or default.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if this is a deleted or default constructor. | def IsDeletedOrDefault(clean_lines, linenum):
open_paren = clean_lines.elided[linenum].find('(')
if open_paren < 0:
return False
(close_line, _, close_paren) = CloseExpression(
clean_lines, linenum, open_paren)
if close_paren < 0:
return False
return Match(r'\s*=\s*(?:delete|default)\b', clos... | 312,379 |
Check if RValue reference is allowed on a particular line.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
typenames: set of type names from template-argument-list.
Returns:
True if line is within the region where RValue references are allo... | def IsRValueAllowed(clean_lines, linenum, typenames):
# Allow region marked by PUSH/POP macros
for i in xrange(linenum, 0, -1):
line = clean_lines.elided[i]
if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line):
if not line.endswith('PUSH'):
return False
for j in xrange(linen... | 312,380 |
Find list of template arguments associated with this function declaration.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: Line number containing the start of the function declaration,
usually one line after the end of the template-argument-list.
Returns:
Set of t... | def GetTemplateArgs(clean_lines, linenum):
# Find start of function
func_line = linenum
while func_line > 0:
line = clean_lines.elided[func_line]
if Match(r'^\s*$', line):
return set()
if line.find('(') >= 0:
break
func_line -= 1
if func_line == 0:
return set()
# Collapse t... | 312,381 |
Check for rvalue references.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested block... | def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error):
# Find lines missing spaces around &&.
# TODO(unknown): currently we don't check for rvalue references
# with spaces surrounding the && to avoid false positives with
# boolean expressions.
line = clean_lines.elided[linenum]
m... | 312,382 |
Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckBraces(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone is using
# braces in a block to explicitly create a new scope, which is com... | 312,383 |
Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" block... | 312,384 |
Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')... | def _DropCommonSuffixes(filename):
for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
'inl.h', 'impl.h', 'internal.h'):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.... | 312,386 |
Determines if the given filename has a suffix that identifies it as a test.
Args:
filename: The input filename.
Returns:
True if 'filename' looks like a test, False otherwise. | def _IsTestFilename(filename):
if (filename.endswith('_test.cc') or
filename.endswith('_unittest.cc') or
filename.endswith('_regtest.cc')):
return True
else:
return False | 312,387 |
Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckGlobalStatic(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Match two lines at a time to support multiline declarations
if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
line += clean_lines.elided[linenum + 1].strip()
# Check for people decla... | 312,388 |
Check that default lambda captures are not used.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def CheckDefaultLambdaCaptures(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# A lambda introducer specifies a default capture if it starts with "[="
# or if it starts with "[&" _not_ followed by an identifier.
match = Match(r'^(.*)\[\s*(?:=|&[^\w])', line)
if match:
# Fou... | 312,392 |
Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | def FlagCxx11Features(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
# Flag unapproved C++11 headers.
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
if include and include.group(1) in ('cfenv',
'condition_variable',
... | 312,394 |
Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further. | def ProcessConfigOverrides(filename):
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")... | 312,395 |
Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint. | def ParseArguments(args):
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
... | 312,396 |
Report if too many lines in function body.
Args:
error: The function to call with any errors found.
filename: The name of the current file.
linenum: The number of the line to check. | def Check(self, error, filename, linenum):
if Match(r'T(EST|est)', self.current_function):
base_trigger = self._TEST_TRIGGER
else:
base_trigger = self._NORMAL_TRIGGER
trigger = base_trigger * 2**_VerboseLevel()
if self.lines_in_function > trigger:
error_level = int(math.log(self.... | 312,399 |
Tree Render Style.
Args:
vertical: Sign for vertical line.
cont: Chars for a continued branch.
end: Chars for the last branch. | def __init__(self, vertical, cont, end):
super(AbstractStyle, self).__init__()
self.vertical = vertical
self.cont = cont
self.end = end
assert (len(cont) == len(vertical) and len(cont) == len(end)), (
"'%s', '%s' and '%s' need to have equal length" % (vertica... | 312,694 |
This call returns an array of symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
version (string); API version
Returns:
dataframe: result | def symbolsDF(token='', version=''):
df = pd.DataFrame(symbols(token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df | 312,711 |
This call returns an array of symbols the Investors Exchange supports for trading.
This list is updated daily as of 7:45 a.m. ET. Symbols may be added or removed by the Investors Exchange after the list was produced.
https://iexcloud.io/docs/api/#iex-symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
... | def iexSymbolsDF(token='', version=''):
df = pd.DataFrame(iexSymbols(token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df | 312,712 |
This call returns an array of mutual fund symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#mutual-fund-symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result | def mutualFundSymbolsDF(token='', version=''):
df = pd.DataFrame(mutualFundSymbols(token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df | 312,713 |
This call returns an array of OTC symbols that IEX Cloud supports for API calls.
https://iexcloud.io/docs/api/#otc-symbols
8am, 9am, 12pm, 1pm UTC daily
Args:
token (string); Access token
version (string); API version
Returns:
DataFrame: result | def otcSymbolsDF(token='', version=''):
df = pd.DataFrame(otcSymbols(token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df | 312,714 |
Pulls balance sheet data. Available quarterly (4 quarters) and annually (4 years)
https://iexcloud.io/docs/api/#balance-sheet
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dic... | def balanceSheet(symbol, token='', version=''):
_raiseIfNotStr(symbol)
return _getJson('stock/' + symbol + '/balance-sheet', token, version) | 312,739 |
Pulls balance sheet data. Available quarterly (4 quarters) and annually (4 years)
https://iexcloud.io/docs/api/#balance-sheet
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
Dat... | def balanceSheetDF(symbol, token='', version=''):
val = balanceSheet(symbol, token, version)
df = pd.io.json.json_normalize(val, 'balancesheet', 'symbol')
_toDatetime(df)
_reindex(df, 'reportDate')
return df | 312,740 |
Batch several data requests into one invocation
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (string); Date range for chart
last (int);
token (string); Access token
... | def batch(symbols, fields=None, range_='1m', last=10, token='', version=''):
fields = fields or _BATCH_TYPES[:10] # limit 10
if not isinstance(symbols, [].__class__):
if not isinstance(symbols, str):
raise PyEXception('batch expects string or list of strings for symbols argument')
... | 312,741 |
Batch several data requests into one invocation
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (string); Date range for chart
last (int);
token (string); Access token
... | def batchDF(symbols, fields=None, range_='1m', last=10, token='', version=''):
x = batch(symbols, fields, range_, last, token, version)
ret = {}
if isinstance(symbols, str):
for field in x.keys():
ret[field] = _MAPPING[field](x[field])
else:
for symbol in x.keys():
... | 312,742 |
Optimized batch to fetch as much as possible at once
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (string); Date range for chart
last (int);
token (string); Access token
... | def bulkBatch(symbols, fields=None, range_='1m', last=10, token='', version=''):
fields = fields or _BATCH_TYPES
args = []
empty_data = []
list_orig = empty_data.__class__
if not isinstance(symbols, list_orig):
raise PyEXception('Symbols must be of type list')
for i in range(0, le... | 312,743 |
Optimized batch to fetch as much as possible at once
https://iexcloud.io/docs/api/#batch-requests
Args:
symbols (list); List of tickers to request
fields (list); List of fields to request
range_ (string); Date range for chart
last (int);
token (string); Access token
... | def bulkBatchDF(symbols, fields=None, range_='1m', last=10, token='', version=''):
dat = bulkBatch(symbols, fields, range_, last, token, version)
ret = {}
for symbol in dat:
for field in dat[symbol]:
if field not in ret:
ret[field] = pd.DataFrame()
d = d... | 312,744 |
Book data
https://iextrading.com/developer/docs/#book
realtime during Investors Exchange market hours
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result | def bookDF(symbol, token='', version=''):
x = book(symbol, token, version)
df = _bookToDF(x)
return df | 312,746 |
Pulls cash flow data. Available quarterly (4 quarters) or annually (4 years).
https://iexcloud.io/docs/api/#cash-flow
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: resul... | def cashFlow(symbol, token='', version=''):
_raiseIfNotStr(symbol)
return _getJson('stock/' + symbol + '/cash-flow', token, version) | 312,747 |
Pulls cash flow data. Available quarterly (4 quarters) or annually (4 years).
https://iexcloud.io/docs/api/#cash-flow
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: ... | def cashFlowDF(symbol, token='', version=''):
val = cashFlow(symbol, token, version)
df = pd.io.json.json_normalize(val, 'cashflow', 'symbol')
_toDatetime(df)
_reindex(df, 'reportDate')
df.replace(to_replace=[None], value=np.nan, inplace=True)
return df | 312,748 |
Returns an array of quote objects for a given collection type. Currently supported collection types are sector, tag, and list
https://iexcloud.io/docs/api/#collections
Args:
tag (string); Sector, Tag, or List
collectionName (string); Associated name for tag
token (string); Access to... | def collections(tag, collectionName, token='', version=''):
if tag not in _COLLECTION_TAGS:
raise PyEXception('Tag must be in %s' % str(_COLLECTION_TAGS))
return _getJson('stock/market/collection/' + tag + '?collectionName=' + collectionName, token, version) | 312,754 |
Returns an array of quote objects for a given collection type. Currently supported collection types are sector, tag, and list
https://iexcloud.io/docs/api/#collections
Args:
tag (string); Sector, Tag, or List
collectionName (string); Associated name for tag
token (string); Access to... | def collectionsDF(tag, query, token='', version=''):
df = pd.DataFrame(collections(tag, query, token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df | 312,755 |
Company reference data
https://iexcloud.io/docs/api/#company
Updates at 4am and 5am UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result | def company(symbol, token='', version=''):
_raiseIfNotStr(symbol)
return _getJson('stock/' + symbol + '/company', token, version) | 312,756 |
Company reference data
https://iexcloud.io/docs/api/#company
Updates at 4am and 5am UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result | def companyDF(symbol, token='', version=''):
c = company(symbol, token, version)
df = _companyToDF(c)
return df | 312,758 |
This returns the 15 minute delayed market quote.
https://iexcloud.io/docs/api/#delayed-quote
15min delayed
4:30am - 8pm ET M-F when market is open
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: res... | def delayedQuote(symbol, token='', version=''):
_raiseIfNotStr(symbol)
return _getJson('stock/' + symbol + '/delayed-quote', token, version) | 312,759 |
This returns the 15 minute delayed market quote.
https://iexcloud.io/docs/api/#delayed-quote
15min delayed
4:30am - 8pm ET M-F when market is open
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame... | def delayedQuoteDF(symbol, token='', version=''):
df = pd.io.json.json_normalize(delayedQuote(symbol, token, version))
_toDatetime(df)
_reindex(df, 'symbol')
return df | 312,760 |
Dividend history
https://iexcloud.io/docs/api/#dividends
Updated at 9am UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result | def dividends(symbol, timeframe='ytd', token='', version=''):
_raiseIfNotStr(symbol)
if timeframe not in _TIMEFRAME_DIVSPLIT:
raise PyEXception('Range must be in %s' % str(_TIMEFRAME_DIVSPLIT))
return _getJson('stock/' + symbol + '/dividends/' + timeframe, token, version) | 312,761 |
Dividend history
https://iexcloud.io/docs/api/#dividends
Updated at 9am UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result | def dividendsDF(symbol, timeframe='ytd', token='', version=''):
d = dividends(symbol, timeframe, token, version)
df = _dividendsToDF(d)
return df | 312,763 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.